text:
__author__ = 'tylin'
__version__ = '2.0'
# Interface for accessing the Microsoft COCO dataset.

# Microsoft COCO is a large image dataset designed for object detection,
# segmentation, and caption generation. pycocotools is a Python API that
# assists in loading, parsing and visualizing the annotations in COCO.
# Please visit http://mscoco.org/ for more information on COCO, including
# for the data, paper, and tutorials. The exact format of the annotations
# is also described on the COCO website. For example usage of the pycocotools
# please see pycocotools_demo.ipynb. In addition to this API, please download both
# the COCO images and annotations in order to run the demo.

# An alternative to using the API is to load the annotations directly
# into Python dictionary
# Using the API provides additional utility functions. Note that this API
# supports both *instance* and *caption* annotations. In the case of
# captions not all functions are defined (e.g. categories are undefined).

# The following API functions are defined:
#  COCO       - COCO api class that loads COCO annotation file and prepare data structures.
#  decodeMask - Decode binary mask M encoded via run-length encoding.
#  encodeMask - Encode binary mask M using run-length encoding.
#  getAnnIds  - Get ann ids that satisfy given filter conditions.
#  getCatIds  - Get cat ids that satisfy given filter conditions.
#  getImgIds  - Get img ids that satisfy given filter conditions.
#  loadAnns   - Load anns with the specified ids.
#  loadCats   - Load cats with the specified ids.
#  loadImgs   - Load imgs with the specified ids.
#  annToMask  - Convert segmentation in an annotation to binary mask.
#  showAnns   - Display the specified annotations.
#  loadRes    - Load algorithm results and create API for accessing them.
#  download   - Download COCO images from mscoco.org server.
# Throughout the API "ann"=annotation, "cat"=category, and "img"=image.
# Help on each functions can be accessed by: "help COCO>function".

# See also COCO>decodeMask,
# COCO>encodeMask, COCO>getAnnIds, COCO>getCatIds,
# COCO>getImgIds, COCO>loadAnns, COCO>loadCats,
# COCO>loadImgs, COCO>annToMask, COCO>showAnns

# Microsoft COCO Toolbox.      version 2.0
# Data, paper, and tutorials available at:  http://mscoco.org/
# Code written by Piotr Dollar and Tsung-Yi Lin, 2014.
# Licensed under the Simplified BSD License [see bsd.txt]

import json
import time
import matplotlib.pyplot as plt
from matplotlib.collections import PatchCollection
from matplotlib.patches import Polygon
import numpy as np
import copy
import itertools
from . import mask as maskUtils
import os
from collections import defaultdict
import sys
PYTHON_VERSION = sys.version_info[0]
if PYTHON_VERSION == 2:
    from urllib import urlretrieve
elif PYTHON_VERSION == 3:
    from urllib.request import urlretrieve

def _isArrayLike(obj):
    return hasattr(obj, '__iter__') and hasattr(obj, '__len__')

class COCO:
    def __init__(self, annotation_file=None):
        """
        Constructor of Microsoft COCO helper class for reading and visualizing annotations.
        :param annotation_file (str): location of annotation file
        :param image_folder (str): location to the folder that hosts images.
        :return:
        """
        # load dataset
        self.dataset,self.anns,self.cats,self.imgs = dict(),dict(),dict(),dict()
        self.imgToAnns, self.catToImgs = defaultdict(list), defaultdict(list)
        if not annotation_file == None:
            print('loading annotations into memory...')
            tic = time.time()
            dataset = json.load(open(annotation_file, 'r'))
            assert type(dataset)==dict, 'annotation file format {} not supported'.format(type(dataset))
            print('Done (t={:0.2f}s)'.format(time.time()- tic))
            self.dataset = dataset
            self.createIndex()

    def createIndex(self):
        # create index
        print('creating index...')
        anns, cats, imgs = {}, {}, {}
        imgToAnns,catToImgs = defaultdict(list),defaultdict(list)
        if 'annotations' in self.dataset:
            for ann in self.dataset['annotations']:
                imgToAnns[ann['image_id']].append(ann)
                anns[ann['id']] = ann

        if 'images' in self.dataset:
            for img in self.dataset['images']:
                imgs[img['id']] = img

        if 'categories' in self.dataset:
            for cat in self.dataset['categories']:
                cats[cat['id']] = cat

        if 'annotations' in self.dataset and 'categories' in self.dataset:
            for ann in self.dataset['annotations']:
                catToImgs[ann['category_id']].append(ann['image_id'])

        print('index created!')

        # create class members
        self.anns = anns
        self.imgToAnns = imgToAnns
        self.catToImgs = catToImgs
        self.imgs = imgs
        self.cats = cats

    def info(self):
        """
        Print information about the annotation file.
        :return:
        """
        for key, value in self.dataset['info'].items():
            print('{}: {}'.format(key, value))

    def getAnnIds(self, imgIds=[], catIds=[], areaRng=[], iscrowd=None):
        """
        Get ann ids that satisfy given filter conditions. default skips that filter
        :param imgIds  (int array)     : get anns for given imgs
               catIds  (int array)     : get anns for given cats
               areaRng (float array)   : get anns for given area range (e.g. [0 inf])
               iscrowd (boolean)       : get anns for given crowd label (False or True)
        :return: ids (int array)       : integer array of ann ids
        """
        imgIds = imgIds if _isArrayLike(imgIds) else [imgIds]
        catIds = catIds if _isArrayLike(catIds) else [catIds]

        if len(imgIds) == len(catIds) == len(areaRng) == 0:
            anns = self.dataset['annotations']
        else:
            if not len(imgIds) == 0:
                lists = [self.imgToAnns[imgId] for imgId in imgIds if imgId in self.imgToAnns]
                anns = list(itertools.chain.from_iterable(lists))
            else:
                anns = self.dataset['annotations']
            anns = anns if len(catIds)  == 0 else [ann for ann in anns if ann['category_id'] in catIds]
            anns = anns if len(areaRng) == 0 else [ann for ann in anns if ann['area'] > areaRng[0] and ann['area'] < areaRng[1]]
        if not iscrowd == None:
            ids = [ann['id'] for ann in anns if ann['iscrowd'] == iscrowd]
        else:
            ids = [ann['id'] for ann in anns]
        return ids

    def getCatIds(self, catNms=[], supNms=[], catIds=[]):
        """
        filtering parameters. default skips that filter.
        :param catNms (str array)  : get cats for given cat names
        :param supNms (str array)  : get cats for given supercategory names
        :param catIds (int array)  : get cats for given cat ids
        :return: ids (int array)   : integer array of cat ids
        """
        catNms = catNms if _isArrayLike(catNms) else [catNms]
        supNms = supNms if _isArrayLike(supNms) else [supNms]
        catIds = catIds if _isArrayLike(catIds) else [catIds]

        if len(catNms) == len(supNms) == len(catIds) == 0:
            cats = self.dataset['categories']
        else:
            cats = self.dataset['categories']
            cats = cats if len(catNms) == 0 else [cat for cat in cats if cat['name']          in catNms]
            cats = cats if len(supNms) == 0 else [cat for cat in cats if cat['supercategory'] in supNms]
            cats = cats if len(catIds) == 0 else [cat for cat in cats if cat['id']            in catIds]
        ids = [cat['id'] for cat in cats]
        return ids

    def getImgIds(self, imgIds=[], catIds=[]):
        '''
        Get img ids that satisfy given filter conditions.
        :param imgIds (int array) : get imgs for given ids
        :param catIds (int array) : get imgs with all given cats
        :return: ids (int array)  : integer array of img ids
        '''
        imgIds = imgIds if _isArrayLike(imgIds) else [imgIds]
        catIds = catIds if _isArrayLike(catIds) else [catIds]

        if len(imgIds) == len(catIds) == 0:
            ids = self.imgs.keys()
        else:
            ids = set(imgIds)
            for i, catId in enumerate(catIds):
                if i == 0 and len(ids) == 0:
                    ids = set(self.catToImgs[catId])
                else:
                    ids &= set(self.catToImgs[catId])
        return list(ids)

    def loadAnns(self, ids=[]):
        """
        Load anns with the specified ids.
        :param ids (int array)       : integer ids specifying anns
        :return: anns (object array) : loaded ann objects
        """
        if _isArrayLike(ids):
            return [self.anns[id] for id in ids]
        elif type(ids) == int:
            return [self.anns[ids]]

    def loadCats(self, ids=[]):
        """
        Load cats with the specified ids.
        :param ids (int array)       : integer ids specifying cats
        :return: cats (object array) : loaded cat objects
        """
        if _isArrayLike(ids):
            return [self.cats[id] for id in ids]
        elif type(ids) == int:
            return [self.cats[ids]]

    def loadImgs(self, ids=[]):
        """
        Load anns with the specified ids.
        :param ids (int array)       : integer ids specifying img
        :return: imgs (object array) : loaded img objects
        """
        if _isArrayLike(ids):
            return [self.imgs[id] for id in ids]
        elif type(ids) == int:
            return [self.imgs[ids]]

    def showAnns(self, anns):
        """
        Display the specified annotations.
        :param anns (array of object): annotations to display
        :return: None
        """
        if len(anns) == 0:
            return 0
        if 'segmentation' in anns[0] or 'keypoints' in anns[0]:
            datasetType = 'instances'
        elif 'caption' in anns[0]:
            datasetType = 'captions'
        else:
            raise Exception('datasetType not supported')
        if datasetType == 'instances':
            ax = plt.gca()
            ax.set_autoscale_on(False)
            polygons = []
            color = []
            for ann in anns:
                c = (np.random.random((1, 3))*0.6+0.4).tolist()[0]
                if 'segmentation' in ann:
                    if type(ann['segmentation']) == list:
                        # polygon
                        for seg in ann['segmentation']:
                            poly = np.array(seg).reshape((int(len(seg)/2), 2))
                            polygons.append(Polygon(poly))
                            color.append(c)
                    else:
                        # mask
                        t = self.imgs[ann['image_id']]
                        if type(ann['segmentation']['counts']) == list:
                            rle = maskUtils.frPyObjects([ann['segmentation']], t['height'], t['width'])
                        else:
                            rle = [ann['segmentation']]
                        m = maskUtils.decode(rle)
                        img = np.ones( (m.shape[0], m.shape[1], 3) )
                        if ann['iscrowd'] == 1:
                            color_mask = np.array([2.0,166.0,101.0])/255
                        if ann['iscrowd'] == 0:
                            color_mask = np.random.random((1, 3)).tolist()[0]
                        for i in range(3):
                            img[:,:,i] = color_mask[i]
                        ax.imshow(np.dstack( (img, m*0.5) ))
                if 'keypoints' in ann and type(ann['keypoints']) == list:
                    # turn skeleton into zero-based index
                    sks = np.array(self.loadCats(ann['category_id'])[0]['skeleton'])-1
                    kp = np.array(ann['keypoints'])
                    x = kp[0::3]
                    y = kp[1::3]
                    v = kp[2::3]
                    for sk in sks:
                        if np.all(v[sk]>0):
                            plt.plot(x[sk],y[sk], linewidth=3, color=c)
                    plt.plot(x[v>0], y[v>0],'o',markersize=8, markerfacecolor=c, markeredgecolor='k',markeredgewidth=2)
                    plt.plot(x[v>1], y[v>1],'o',markersize=8, markerfacecolor=c, markeredgecolor=c, markeredgewidth=2)
            p = PatchCollection(polygons, facecolor=color, linewidths=0, alpha=0.4)
            ax.add_collection(p)
            p = PatchCollection(polygons, facecolor='none', edgecolors=color, linewidths=2)
            ax.add_collection(p)
        elif datasetType == 'captions':
            for ann in anns:
                print(ann['caption'])

    def loadRes(self, resFile):
        """
        Load result file and return a result api object.
        :param   resFile (str)     : file name of result file
        :return: res (obj)         : result api object
        """
        res = COCO()
        res.dataset['images'] = [img for img in self.dataset['images']]

        print('Loading and preparing results...')
        tic = time.time()
        if type(resFile) == str or type(resFile) == unicode:
            anns = json.load(open(resFile))
        elif type(resFile) == np.ndarray:
            anns = self.loadNumpyAnnotations(resFile)
        else:
            anns = resFile
        assert type(anns) == list, 'results in not an array of objects'
        annsImgIds = [ann['image_id'] for ann in anns]
        assert set(annsImgIds) == (set(annsImgIds) & set(self.getImgIds())), \
               'Results do not correspond to current coco set'
        if 'caption' in anns[0]:
            imgIds = set([img['id'] for img in res.dataset['images']]) & set([ann['image_id'] for ann in anns])
            res.dataset['images'] = [img for img in res.dataset['images'] if img['id'] in imgIds]
            for id, ann in enumerate(anns):
                ann['id'] = id+1
        elif 'bbox' in anns[0] and not anns[0]['bbox'] == []:
            res.dataset['categories'] = copy.deepcopy(self.dataset['categories'])
            for id, ann in enumerate(anns):
                bb = ann['bbox']
                x1, x2, y1, y2 = [bb[0], bb[0]+bb[2], bb[1], bb[1]+bb[3]]
                if not 'segmentation' in ann:
                    ann['segmentation'] = [[x1, y1, x1, y2, x2, y2, x2, y1]]
                ann['area'] = bb[2]*bb[3]
                ann['id'] = id+1
                ann['iscrowd'] = 0
        elif 'segmentation' in anns[0]:
            res.dataset['categories'] = copy.deepcopy(self.dataset['categories'])
            for id, ann in enumerate(anns):
                # now only support compressed RLE format as segmentation results
                ann['area'] = maskUtils.area(ann['segmentation'])
                if not 'bbox' in ann:
                    ann['bbox'] = maskUtils.toBbox(ann['segmentation'])
                ann['id'] = id+1
                ann['iscrowd'] = 0
        elif 'keypoints' in anns[0]:
            res.dataset['categories'] = copy.deepcopy(self.dataset['categories'])
            for id, ann in enumerate(anns):
                s = ann['keypoints']
                x = s[0::3]
                y = s[1::3]
                x0,x1,y0,y1 = np.min(x), np.max(x), np.min(y), np.max(y)
                ann['area'] = (x1-x0)*(y1-y0)
                ann['id'] = id + 1
                ann['bbox'] = [x0,y0,x1-x0,y1-y0]
        print('DONE (t={:0.2f}s)'.format(time.time()- tic))

        res.dataset['annotations'] = anns
        res.createIndex()
        return res

    def download(self, tarDir = None, imgIds = [] ):
        '''
        Download COCO images from mscoco.org server.
        :param tarDir (str): COCO results directory name
               imgIds (list): images to be downloaded
        :return:
        '''
        if tarDir is None:
            print('Please specify target directory')
            return -1
        if len(imgIds) == 0:
            imgs = self.imgs.values()
        else:
            imgs = self.loadImgs(imgIds)
        N = len(imgs)
        if not os.path.exists(tarDir):
            os.makedirs(tarDir)
        for i, img in enumerate(imgs):
            tic = time.time()
            fname = os.path.join(tarDir, img['file_name'])
            if not os.path.exists(fname):
                urlretrieve(img['coco_url'], fname)
            print('downloaded {}/{} images (t={:0.1f}s)'.format(i, N, time.time()- tic))

    def loadNumpyAnnotations(self, data):
        """
        Convert result data from a numpy array [Nx7] where each row contains {imageID,x1,y1,w,h,score,class}
        :param  data (numpy.ndarray)
        :return: annotations (python nested list)
        """
        print('Converting ndarray to lists...')
        assert(type(data) == np.ndarray)
        print(data.shape)
        assert(data.shape[1] == 7)
        N = data.shape[0]
        ann = []
        for i in range(N):
            if i % 1000000 == 0:
                print('{}/{}'.format(i,N))
            ann += [{
                'image_id'  : int(data[i, 0]),
                'bbox'  : [ data[i, 1], data[i, 2], data[i, 3], data[i, 4] ],
                'score' : data[i, 5],
                'category_id': int(data[i, 6]),
                }]
        return ann

    def annToRLE(self, ann):
        """
        Convert annotation which can be polygons, uncompressed RLE to RLE.
        :return: binary mask (numpy 2D array)
        """
        t = self.imgs[ann['image_id']]
        h, w = t['height'], t['width']
        segm = ann['segmentation']
        if type(segm) == list:
            # polygon -- a single object might consist of multiple parts
            # we merge all parts into one mask rle code
            rles = maskUtils.frPyObjects(segm, h, w)
            rle = maskUtils.merge(rles)
        elif type(segm['counts']) == list:
            # uncompressed RLE
            rle = maskUtils.frPyObjects(segm, h, w)
        else:
            # rle
            rle = ann['segmentation']
        return rle

    def annToMask(self, ann):
        """
        Convert annotation which can be polygons, uncompressed RLE, or RLE to binary mask.
        :return: binary mask (numpy 2D array)
        """
        rle = self.annToRLE(ann)
        m = maskUtils.decode(rle)
        return m


text:
A tool to import cryptomap-based site-to-site VPN tunnel entries from an ASA configuration file to a Meraki dashboard organization.
--------------------------------------

# Important notes

* The script will only import VPN tunnel configuration as third-party VPN peers, not firewalling rules
* The script has been built as a MVP to convert a very specific ASA 9.8(4)20 configuration. Using it with other configurations may require modification of the script
* The script consists of two files, **cryptomap_converter.py** and **asa_config_parser_module.py**, which need to be in the same folder for the script to run. The one you run to initiate the script is **cryptomap_converter.py**

# Prerequisites

1. Install Python 3 and the requests module. You can find them here
* https://www.python.org/
* https://docs.python-requests.org

2. Enable site-to-site VPN in Meraki dashboard by making your MX security appliance a hub or a spoke: https://documentation.meraki.com/MX/Site-to-site_VPN/Site-to-Site_VPN_Settings
3. If you want to limit availability of the converted tunnels to certain MXs in your organization, create a network tag and associate it with their networks: https://documentation.meraki.com/General_Administration/Organizations_and_Networks/Organization_Menu/Manage_Tags

# Usage instructions

Script syntax, Windows:
```
python cryptomap_converter.py [-k <api_key>] [-o <org_name>] [-f <file_name>] [-t <tag>]
```

Script syntax, Linux and Mac:
```
python3 cryptomap_converter.py [-k <api_key>] [-o <org_name>] [-f <file_name>] [-t <tag>]
```

Optional arguments:
* `-k <api_key>`: Your Meraki Dashboard API key. If omitted, the script will try to use one stored in OS environment variable MERAKI_DASHBOARD_API_KEY
* `-o <org_name>`: The name of the organization to pull the OpenAPI spec from. This parameter can be omitted if your API key can only access one organization
* `-f <file_name>`: The name of the ASA configuration input file. If omitted, "asa.cfg" will be used as default
* `-t <tag>`: The name of the network tag you want to make the converted tunnels available to. If omitted, default availability is "All networks"

Example, convert configuration stored in file "asa.cfg" into organization with name "Big Industries Inc" and
make it available to MXs in networks tagged "asa-vpn":
```
python cryptomap_converter.py -k 1234 -o "Big Industries Inc" -t asa-vpn
```

redpajama_set_name: RedPajamaGithub


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

package com.azure.resourcemanager.hdinsight.generated;

import com.azure.core.util.Context;

/** Samples for PrivateEndpointConnections ListByCluster. */
public final class PrivateEndpointConnectionsListByClusterSamples {
    /*
     * x-ms-original-file: specification/hdinsight/resource-manager/Microsoft.HDInsight/stable/2021-06-01/examples/GetAllPrivateEndpointConnectionsInCluster.json
     */
    /**
     * Sample code: Get all private endpoint connections for a specific HDInsight cluster.
     *
     * @param manager Entry point to HDInsightManager.
     */
    public static void getAllPrivateEndpointConnectionsForASpecificHDInsightCluster(
        com.azure.resourcemanager.hdinsight.HDInsightManager manager) {
        manager.privateEndpointConnections().listByCluster("rg1", "cluster1", Context.NONE);
    }
}


text:
Editing Divition

<?php echo render('divition/_form'); ?>

	<?php echo Html::anchor('divition/view/'.$divition->id, 'View'); ?> |
	<?php echo Html::anchor('divition', 'Back'); ?>


text:
[![Circle CI](https://circleci.com/gh/masahitojp/botan-mapdb.svg?style=svg)](https://circleci.com/gh/masahitojp/botan-mapdb)

tiny chat bot framework for Java SE 8.(like a Hubot)
It's for persistent data.

## requirement

Java8

## License

Apache License, Version 2.0


text:
AddCSLuaFile()

SWEP.Base = "weapon_base"

SWEP.PrintName 				= "Claws"
SWEP.Category				= "AOTM"
SWEP.Purpose				= "Do some damage."
SWEP.Instructions			= "Primary: Attack.\nSecondary: Mimic.\nReload: Scream."
SWEP.Spawnable				= true
SWEP.AdminSpawnable			= true

if CLIENT then
	SWEP.BounceWeaponIcon	= false
	SWEP.WepSelectIcon		= surface.GetTextureID( "attack_of_the_mimics/vgui/wep_icons/claws" )
end

SWEP.Slot 					= 0
SWEP.SlotPos				= 0

SWEP.ViewModelFOV			= 62
SWEP.ViewModelFlip			= false
SWEP.ViewModel 				= Model( "models/weapons/c_arms_animations.mdl" )
SWEP.WorldModel				= Model( "models/weapons/c_arms_animations.mdl" )
SWEP.HoldType				= "normal"
SWEP.UseHands				= false
SWEP.DrawCrosshair			= true
SWEP.AccurateCrosshair		= true

SWEP.DeploySpeed 			= 1.0

SWEP.Primary.Delay 			= 1.0

SWEP.Primary.Sound 			= Sound("npc/fast_zombie/claw_miss1.wav")
SWEP.Primary.HitSound 		= {
	Sound("npc/fast_zombie/claw_strike1.wav"),
	Sound("npc/fast_zombie/claw_strike2.wav"),
	Sound("npc/fast_zombie/claw_strike3.wav")
}
SWEP.Primary.Damage			= 15
SWEP.Primary.ClipSize		= -1
SWEP.Primary.DefaultClip	= -1
SWEP.Primary.Automatic		= true
SWEP.Primary.Ammo			= "none"

SWEP.Secondary.Delay 		= 1.0

SWEP.Secondary.ClipSize		= -1
SWEP.Secondary.DefaultClip	= -1
SWEP.Secondary.Automatic	= false
SWEP.Secondary.Ammo			= "none"

SWEP.DrawAmmo				= false

SWEP.Scream					= {}
SWEP.Scream.Delay			= 30
SWEP.Scream.Sounds			= {
	Sound("npc/fast_zombie/fz_scream1.wav")
}

SWEP.is_for_mimics = true

local CLAW_DAMAGE_SCALE
if SERVER then
	CLAW_DAMAGE_SCALE = CreateConVar("aotm_mimic_claw_damage_scale", "1.0", FCVAR_SERVER_CAN_EXECUTE+FCVAR_NOTIFY+FCVAR_ARCHIVE)
elseif CLIENT then
	CLAW_DAMAGE_SCALE = GetConVar("aotm_mimic_claw_damage_scale")
end

function SWEP:Initialize()
	self:SetDeploySpeed(self.DeploySpeed)

	if self.SetHoldType then
		self:SetHoldType(self.HoldType)
	end

	if SERVER then
		self.next_scream_ready = 0
	end
end

function SWEP:SetupDataTables()
	self:NetworkVar("Bool", 0, "ScreamReady")
end

if SERVER then
	function SWEP:Think()
		if not self:GetScreamReady() then
			if CurTime() > self.next_scream_ready then
				self.Owner:SetIsHiding(true)
				self:SetScreamReady(true)
			end
		end
	end
end

function SWEP:PrimaryAttack()
	if not self:CanPrimaryAttack() then return end

	self:SetNextPrimaryFire( CurTime() + self.Primary.Delay )
	self:SetNextSecondaryFire( CurTime() + self.Primary.Delay )

	if not IsValid(self.Owner) then return end

	local owner = self.Owner

	owner:LagCompensation(true)

	owner:AddVCDSequenceToGestureSlot( GESTURE_SLOT_ATTACK_AND_RELOAD, owner:LookupSequence("range_melee"), 0, true )

	local spos = self.Owner:GetShootPos()
	local sdest = spos + (self.Owner:GetAimVector() * 70)

	local kmins = Vector(1,1,1) * -10
	local kmaxs = Vector(1,1,1) * 10

	local tr = util.TraceHull({start=spos, endpos=sdest, filter=self.Owner, mask=MASK_SHOT_HULL, mins=kmins, maxs=kmaxs})

	-- Hull might hit environment stuff that line does not hit
	if not IsValid(tr.Entity) then
		tr = util.TraceLine({start=spos, endpos=sdest, filter=self.Owner, mask=MASK_SHOT_HULL})
	end

	local hitEnt = tr.Entity

	self:EmitSound( self.Primary.Sound )

	-- effects
	if tr.Hit then
		self:EmitSound( self.Primary.HitSound[math.random(#self.Primary.HitSound)] )
	end

	if SERVER and tr.Hit then
		local dmg = DamageInfo()

		local dmg_scale = 1.0

		if not owner:GetIsTired() then
			dmg_scale = dmg_scale * Lerp(owner:GetEnergy()/100.0, 1.0, 2.0)
		end

		if hitEnt:IsPlayer() then
			local ang = hitEnt:GetAngles()
			ang.pitch = 0
			local forward = ang:Forward()
			local dist = hitEnt:GetPos():Distance(owner:GetPos())

			dmg_scale = dmg_scale * (math.max(forward:Dot(owner:GetAimVector())*1, 0)+1)
			dmg_scale = dmg_scale * math.Clamp( math.InvLerp(dist, 90, 35), 0.1, 1 )
		elseif hitEnt:GetClass() == "prop_door_rotating" then
			dmg_scale = dmg_scale * 4.0
		end

		dmg_scale = dmg_scale * CLAW_DAMAGE_SCALE:GetFloat(1.0)

		dmg:SetDamage(self.Primary.Damage*dmg_scale)
		dmg:SetMaxDamage(self.Primary.Damage*dmg_scale)
		dmg:SetAttacker(owner)
		dmg:SetInflictor(self.Weapon or self)
		dmg:SetDamageForce(owner:GetAimVector() * 3000)
		dmg:SetDamagePosition(owner:GetPos())
		dmg:SetDamageType(DMG_SLASH)

		hitEnt:DispatchTraceAttack(dmg, spos + (owner:GetAimVector() * 3), sdest)
	end

	owner:LagCompensation(false)

	if SERVER then
		if IsValid(owner) then
			owner:SetEnergy(owner:GetEnergy()-20)
		end
	end
end

function SWEP:CanPrimaryAttack()
   if not IsValid(self.Owner) then return end

   return not self.Owner:GetIsTired()
end

function SWEP:SecondaryAttack()
	if not self:CanSecondaryAttack() then return end

	self:SetNextPrimaryFire( CurTime() + self.Secondary.Delay )
	self:SetNextSecondaryFire( CurTime() + self.Secondary.Delay )

	if not IsValid(self.Owner) then return end

	local owner = self.Owner

	if SERVER then
		owner:LagCompensation(true)

		local spos = self.Owner:GetShootPos()
		local sdest = spos + (self.Owner:GetAimVector() * 70)

		local kmins = Vector(1,1,1) * -10
		local kmaxs = Vector(1,1,1) * 10

		local tr = util.TraceHull({start=spos, endpos=sdest, filter=self.Owner, mask=MASK_SHOT_HULL, mins=kmins, maxs=kmaxs})

		-- Hull might hit environment stuff that line does not hit
		if not IsValid(tr.Entity) then
			tr = util.TraceLine({start=spos, endpos=sdest, filter=self.Owner, mask=MASK_SHOT_HULL})
		end

		local hitEnt = tr.Entity

		if IsValid(hitEnt) and not hitEnt:IsWorld() then
			local mimic_body = owner:GetMimicBody()

			if hitEnt:IsPlayer() and hitEnt:Team() == TEAM_MIMIC then
				mimic_body:Mimic(hitEnt:GetMimicBody():GetModel(), hitEnt:GetMimicBody():GetSkin())
			else
				mimic_body:Mimic(hitEnt:GetModel(), hitEnt:GetSkin())
			end
		end

		owner:LagCompensation(false)
	end
end

function SWEP:CanSecondaryAttack()
	if not IsValid(self.Owner) then return end

	return true
end

function SWEP:Reload()
	if not self:GetScreamReady() then return end

	self.Owner:AddVCDSequenceToGestureSlot( GESTURE_SLOT_ATTACK_AND_RELOAD, self.Owner:LookupSequence("taunt_zombie"), 0, true )

	if SERVER then
		self.Owner:EmitSound( self.Scream.Sounds[math.random(#self.Scream.Sounds)], 95, Lerp(math.random(), 80, 100) )
		hook.Call( "AOTM_MimicScream", nil, self.Owner:GetPos() )

		self.Owner:SetEnergy(99)

		self.Owner:SetIsHiding(false)

		self:SetScreamReady(false)
		self.next_scream_ready = CurTime() + self.Scream.Delay
	else
		self.scream_init = CurTime()
	end
end


text:
package rest;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;

import org.xml.sax.SAXException;

import xml.Sax;
import xml.Styliser;
import xml.StyliserInterface;

/*
 * This Class help to read and write files
 */
public class Inout {

	public Inout() {

	}

	/*
	 * Read a file from a path and return a string
	 */
	public static String readfile(String file) {
		try(BufferedReader br = new BufferedReader(new FileReader(file))) {
	        StringBuilder sb = new StringBuilder();
	        String line = br.readLine();

	        while (line != null) {
	            sb.append(line);
	            sb.append(System.lineSeparator());
	            line = br.readLine();
	        }

	        return sb.toString();
	    } catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	// Save the input stream to a local file
	public static void saveFile(String input, String source) throws IOException {
		String filePath = "src/rest/" + source + ".xml";
	     input = input.replace("><", ">\n<");

	    Writer out = new BufferedWriter(
	    		new OutputStreamWriter(
	    				new FileOutputStream(filePath), "UTF-8"));
	    try {
			out.write(input); 	// write into the file
			out.close();		// close the file

		} catch (Exception e) {
			System.out.println(e.getMessage());
			out.close();
		}
	}

	// Launch these methods after a previous process
	public static void postprocess(String input, String source, String type)
			throws IOException, ParserConfigurationException, SAXException {

		// Build the file path
		String filePath = "src/rest/" + source + ".xml";

		// Save the file locally
		saveFile(input, source);

		// Test the source
		if (source.equals("lastfm")) {
			// We want this source to be the main
			StyliserInterface styliser = new Styliser();
			register(styliser, filePath, source, type);

		} else {

			// For others sources
			// Parse with SAX the other XML's API (Musicbrainz)
			Sax.compare("src/rest/" + source + ".xml");
		}
	}

	// Callback method
	public static void register(StyliserInterface styliser, String file, String fileName, String type)
			throws ParserConfigurationException {
		try {

			// Test the query's type
			if (type.equals("album")) {
				// Format the xml
				styliser.transform(file, "src/xml/album.xsl", fileName);
				Sax.mediaType = "album";

			} else if (type.equals("artist")) {
				// Format the xml
				styliser.transform(file, "src/xml/artist.xsl", fileName);
				Sax.mediaType = "artist";

			} else if (type.equals("track")) {
				// Format the xml
				styliser.transform(file, "src/xml/track.xsl", fileName);
				Sax.mediaType = "track";

			}

			Sax.parse("src/xml/" + fileName + ".xml");

		} catch (TransformerException | SAXException | IOException e) {
			e.printStackTrace();
		}
	}
}


text:
import fibonacci from 'utils/fibonacci';
import createUID from 'utils/createUID';
describe("fibonacci", ()=>{
  it("fibonacci", ()=>{
    expect(fibonacci(8)).toEqual(21);
  });
  it("fibonacci", ()=>{
    expect(fibonacci(1)).toEqual(1);
  });
  it("fibonacci", ()=>{
    expect(fibonacci(-1)).toEqual(1);
  });
  it("createUID", ()=>{
    expect(createUID().length).toEqual(36);
  });
  it("createUID", ()=>{
    expect(typeof createUID() == 'string').toEqual(true);
  });
});


text:
layout: post
title: Building Mosquitto 1.4
modified:
excerpt: "How to build the Mosquitto MQTT broker on Linux"
comments: true
tags: [tech,mosquitto,mqtt,websockets,integration]
image:
  feature: mosquito.jpg
  credit: John Tann
  creditlink: https://www.flickr.com/photos/31031835@N08/
---

{% include _toc.html %}

*EDIT (21st Jan 2015): updated to reflect move of repo.*

## Why are we doing this?

I wanted to use [MQTT][MQTT] to interact with a browser-based application in order to deliver real-time interactions such as notifications. Having read [Oriel Ruis' instructions][OrielRuisPost], my initial approach was to put [Lighttpd][Lighttpd] in front of [Mosquitto][Mosquitto], and tunnel websockets, but it was perplexing how we were going to secure it.

I asked a [question on StackOverflow][StackoverflowQuestion] and then, in mid-July 2014, [Mosquitto got websockets][MosquittoWebsockets]. This will allow us to more easily use existing security models for MQTT.

However, since (at the time of writing) it was still pre-release, we need to compile v1.4 ourselves.

## How to do it

These instructions were successful on a clean build of [Mint Linux 17][LinuxMint], i.e. Ubuntu 14.04.

The [Brass Moustaches](#brass-moustaches) section towards the end of this post lists the additional steps I took due to missing dependencies.

Your mileage may vary...

### Install libwebsockets

**Option 1**: build instructions for an newer version...

    sudo apt-get install cmake libssl-dev

    cd <SRC>   # i.e. your source code home

    wget http://git.warmcat.com/cgi-bin/cgit/libwebsockets/snapshot/libwebsockets-1.3-chrome37-firefox30.tar.gz

    tar -xzvf libwebsockets-1.3-chrome37-firefox30.tar.gz
    cd libwebsockets-1.3-chrome37-firefox30/
    mkdir build
    cd build
    cmake .. -DOPENSSL_ROOT_DIR=/usr/bin/openssl
    make
    sudo make install

**Option 2**: build instructions for an older version...

    cd <SRC>   # i.e. your source code home

    wget http://git.warmcat.com/cgi-bin/cgit/libwebsockets/snapshot/libwebsockets-1.22-chrome26-firefox18.tar.gz

    tar -xzvf libwebsockets-1.22-chrome26-firefox18.tar.gz
    sudo apt-get install autoconf
    cd libwebsockets-1.22-chrome26-firefox18/
    ./autogen.sh
     ./configure
    make
    sudo make install

### Install git tools

    sudo apt-get install git

### Clone the Mosquitto repo and switch to the 1.4 branch

    cd <SRC>   # i.e. your source code home

    cd mosquitto/
    git clone https://git.eclipse.org/r/mosquitto/org.eclipse.mosquitto
    cd org.eclipse.mosquitto/
    git checkout origin/1.4

### make it

First edit `config.mk` and ensure that the websockets option is set to "yes".

    WITH_WEBSOCKETS:=yes

Then install pre-reqs:-

    sudo apt-get install uuid-dev xsltproc docbook-xsl

And then...

    make
    make test
    sudo make install

If need be, [edit or create your config file][MosquittoConfig] and create the service user ID.

    sudo vi /etc/mosquitto/mosquitto.conf
    sudo useradd -r -m -d /var/lib/mosquitto -s /usr/sbin/nologin -g nogroup mosquitto

Then start it up...

    sudo /usr/local/sbin/mosquitto -c /etc/mosquitto/mosquitto.conf

And you're done.

## Brass Moustaches

*Aside*: [brass moustache etymology](/2014/07/25/brass-moustache).

### zlib

If you get an error about missing zlib, do this:-

    cd <SRC>   # i.e. your source code home

    wget http://zlib.net/zlib-1.2.8.tar.gz
    tar xvf zlib-1.2.8.tar.gz
    cd zlib-1.2.8
    ./configure
    make
    make test
    sudo make install

### ares.h

If you get an error about missing ares.h, do this:-

    cd <SRC>   # i.e. your source code home

    wget http://c-ares.haxx.se/download/c-ares-1.10.0.tar.gz
    tar xvf c-ares-1.10.0.tar.gz
    cd c-ares-1.10.0
    ./configure
    make
    sudo make install

### make test and libwebsockets

`make test` failed for me. As per [https://answers.launchpad.net/mosquitto/+question/252173](https://answers.launchpad.net/mosquitto/+question/252173), it might be that the websockets build has not put the library on the shared library path.

To diagnose this, just try bringing the test broker up directly:-

    cd <SRC>/org.eclipse.mosquitto/test/broker

    ../../src/mosquitto -p 1888

If it's the shared library problem, you'll see this immediately. To resolve this, do something like:-

    find /usr -name libwebsockets.so

Mine was in /usr/local/lib64/libwebsockets.so

    sudo vi /etc/ld.so.conf.d/lib64c.conf

...and add the following lines:-

    # lib64c default configuration
    /usr/local/lib64

...and then:-

    sudo ldconfig

...and try the test again.

[MQTT]: http://mqtt.org/
[OrielRuisPost]: http://oriolrius.cat/blog/2013/09/25/server-send-push-notifications-to-client-browser-without-polling/
[Lighttpd]: http://www.lighttpd.net
[Mosquitto]: http://mosquitto.org/
[StackOverflowQuestion]: http://stackoverflow.com/questions/24488512/how-to-secure-mqtt-over-websockets
[MosquittoWebsockets]: http://jpmens.net/2014/07/03/the-mosquitto-mqtt-broker-gets-websockets-support
[LinuxMint]: http://www.linuxmint.com
[BrassMoustaches]: /2014/07/25/brass-moustache
[MosquittoConfig]: http://mosquitto.org/man/mosquitto-conf-5.html
[BrassMoustacheDef]: /2014/07/25/brass-moustache
[LoadPublicKey]: https://confluence.atlassian.com/display/BITBUCKET/Troubleshoot+SSH+Issues#TroubleshootSSHIssues-Permissiondenied(publickey)orNosuitableresponsefromremote


text:
import argparse
import json
import os
import shutil
import warnings

import onnx.backend.test.case.model as model_test
import onnx.backend.test.case.node as node_test
from onnx import numpy_helper

TOP_DIR = os.path.realpath(os.path.dirname(__file__))
DATA_DIR = os.path.join(TOP_DIR, "data")

def generate_data(args: argparse.Namespace) -> None:
    def prepare_dir(path: str) -> None:
        if os.path.exists(path):
            shutil.rmtree(path)
        os.makedirs(path)

    # Clean the output directory before generating data for node testcases
    # It is used to check new generated data is correct in CIs
    node_root = os.path.join(args.output, "node")
    original_dir_number = len(
        [name for name in os.listdir(node_root) if os.path.isfile(name)]
    )
    if args.clean and os.path.exists(node_root):
        shutil.rmtree(node_root)
        os.makedirs(node_root)

    cases = model_test.collect_testcases()
    # If op_type is specified, only include those testcases including the given operator
    # Otherwise, include all of the testcases
    cases += node_test.collect_testcases(args.op_type)
    node_number = 0

    for case in cases:
        output_dir = os.path.join(args.output, case.kind, case.name)
        prepare_dir(output_dir)
        if case.kind == "node":
            node_number += 1
        if case.kind == "real":
            with open(os.path.join(output_dir, "data.json"), "w") as fi:
                json.dump(
                    {
                        "url": case.url,
                        "model_name": case.model_name,
                        "rtol": case.rtol,
                        "atol": case.atol,
                    },
                    fi,
                    sort_keys=True,
                )
        else:
            assert case.model
            with open(os.path.join(output_dir, "model.onnx"), "wb") as f:
                f.write(case.model.SerializeToString())
            assert case.data_sets
            for i, (inputs, outputs) in enumerate(case.data_sets):
                data_set_dir = os.path.join(output_dir, f"test_data_set_{i}")
                prepare_dir(data_set_dir)
                for j, input in enumerate(inputs):
                    with open(os.path.join(data_set_dir, f"input_{j}.pb"), "wb") as f:
                        if case.model.graph.input[j].type.HasField("map_type"):
                            f.write(
                                numpy_helper.from_dict(
                                    input, case.model.graph.input[j].name
                                ).SerializeToString()
                            )
                        elif case.model.graph.input[j].type.HasField("sequence_type"):
                            f.write(
                                numpy_helper.from_list(
                                    input, case.model.graph.input[j].name
                                ).SerializeToString()
                            )
                        elif case.model.graph.input[j].type.HasField("optional_type"):
                            f.write(
                                numpy_helper.from_optional(
                                    input, case.model.graph.input[j].name
                                ).SerializeToString()
                            )
                        else:
                            assert case.model.graph.input[j].type.HasField(
                                "tensor_type"
                            )
                            f.write(
                                numpy_helper.from_array(
                                    input, case.model.graph.input[j].name
                                ).SerializeToString()
                            )
                for j, output in enumerate(outputs):
                    with open(os.path.join(data_set_dir, f"output_{j}.pb"), "wb") as f:
                        if case.model.graph.output[j].type.HasField("map_type"):
                            f.write(
                                numpy_helper.from_dict(
                                    output, case.model.graph.output[j].name
                                ).SerializeToString()
                            )
                        elif case.model.graph.output[j].type.HasField("sequence_type"):
                            f.write(
                                numpy_helper.from_list(
                                    output, case.model.graph.output[j].name
                                ).SerializeToString()
                            )
                        elif case.model.graph.output[j].type.HasField("optional_type"):
                            f.write(
                                numpy_helper.from_optional(
                                    output, case.model.graph.output[j].name
                                ).SerializeToString()
                            )
                        else:
                            assert case.model.graph.output[j].type.HasField(
                                "tensor_type"
                            )
                            f.write(
                                numpy_helper.from_array(
                                    output, case.model.graph.output[j].name
                                ).SerializeToString()
                            )
    if not args.clean and node_number != original_dir_number:
        warnings.warn(
            "There are some models under 'onnx/backend/test/data/node' which cannot not"
            + " be generated by the script from 'onnx/backend/test/case/node'. Please add"
            + " '--clean' option for 'python onnx/backend/test/cmd_tools.py generate-data'"
            + " to cleanup the existing directories and regenerate them.",
            Warning,
            stacklevel=2,
        )

def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser("backend-test-tools")
    subparsers = parser.add_subparsers()

    subparser = subparsers.add_parser(
        "generate-data", help="convert testcases to test data."
    )
    subparser.add_argument(
        "-c",
        "--clean",
        default=False,
        action="store_true",
        help="Clean the output directory before generating data for node testcases.",
    )
    subparser.add_argument(
        "-o",
        "--output",
        default=DATA_DIR,
        help="output directory (default: %(default)s)",
    )
    subparser.add_argument(
        "-t",
        "--op_type",
        default=None,
        help="op_type for test case generation. (generates test data for the specified op_type only.)",
    )
    subparser.set_defaults(func=generate_data)

    return parser.parse_args()

def main() -> None:
    args = parse_args()
    args.func(args)

if __name__ == "__main__":
    main()


text:
from nose.tools import eq_, ok_

from django.contrib.auth.models import User
from django.test import TestCase

from us_ignite.apps.models import Application
from us_ignite.apps.tests.fixtures import get_application
from us_ignite.awards.models import Award, ApplicationAward, HubAward, UserAward
from us_ignite.awards.tests import fixtures
from us_ignite.hubs.models import Hub
from us_ignite.hubs.tests.fixtures import get_hub
from us_ignite.profiles.tests.fixtures import get_user

class TestAwardModel(TestCase):

    def tearDown(self):
        for model in [Award]:
            model.objects.all().delete()

    def test_create_award_is_successful(self):
        data = {
            'name': 'Gold star',
        }
        instance = Award.objects.create(**data)
        ok_(instance.id)
        eq_(instance.name, 'Gold star')
        ok_(instance.slug)
        eq_(instance.description, '')
        eq_(instance.image, '')

class TestApplicationAwardModel(TestCase):

    def tearDown(self):
        for model in [Award, Application, User]:
            model.objects.all().delete()

    def test_application_award_creation_is_successful(self):
        user = get_user('us-ignite')
        application = get_application(owner=user)
        award = fixtures.get_award(name='Gold star')
        data = {
            'application': application,
            'award': award,
        }
        instance = ApplicationAward.objects.create(**data)
        ok_(instance.id)
        ok_(instance.created)
        eq_(instance.application, application)
        eq_(instance.award, award)

class TestHubAwardModel(TestCase):

    def tearDown(self):
        for model in [Award, Hub, User]:
            model.objects.all().delete()

    def test_hub_award_creation_is_successful(self):
        user = get_user('us-ignite')
        hub = get_hub()
        award = fixtures.get_award(name='Gold star')
        data = {
            'hub': hub,
            'award': award,
        }
        instance = HubAward.objects.create(**data)
        ok_(instance.id)
        ok_(instance.created)
        eq_(instance.hub, hub)
        eq_(instance.award, award)

class TestUserAwardModel(TestCase):

    def tearDown(self):
        for model in [Award, User]:
            model.objects.all().delete()

    def test_hub_award_creation_is_successful(self):
        user = get_user('us-ignite')
        award = fixtures.get_award(name='Gold star')
        data = {
            'user': user,
            'award': award,
        }
        instance = UserAward.objects.create(**data)
        ok_(instance.id)
        ok_(instance.created)
        eq_(instance.user, user)
        eq_(instance.award, award)


text:
<?php

try {
    require_once('../includes/init.php');

    Logger::setProcess(ProcessTypes::GUI);

    try { // At that point we can render exceptions using nice html
        $pre_header_template_exception = null;
        try {
            Auth::isAuthenticated(); // Preload auth state
            // Security that applies to all page requests
            Security::addHTTPHeaders();

            // if configured, ensure no nasty CSRF is going on
            Security::validateAgainstCSRF();
        } catch (Exception $e) {
            // Catch any of these exceptions so we can still print
            // the page header template before throwing the exception
            $pre_header_template_exception = $e;
        }
        Template::display('!!header');

        if ($pre_header_template_exception !== null) {
            // Throw any exception that occurred before the page header
            throw $pre_header_template_exception;
        }

        $page = GUI::currentPage();
        $vars = array();

        if(!GUI::isUserAllowedToAccessPage($page)) {
            if(Auth::isAuthenticated())
                throw new GUIAccessForbiddenException($page);

            GUI::currentPage('logon');
            $vars['access_forbidden'] = true;

            if(Config::get('auth_sp_autotrigger')) AuthSP::trigger();
        }

        // Service level AUP
        if( Config::get('service_aup_min_required_version') > 0 ) {

            $principal = Auth::getPrincipal();

            // If the user just "got a link" they are neither a guest
            // or a user of the system so we can't really ask them to
            // accept a service wide AUP because they have no account
            // to record that information into.
            if( $principal &&
                $principal->service_aup_accepted_version < Config::get('service_aup_min_required_version'))
            {
                // new service wide AUP to accept for this user/guest
                GUI::currentPage('service_aup');
            }
        }

        if(!in_array($page, array('download', 'maintenance')))
            Template::display('menu');

        Template::display('page', array('vars' => $vars));

    } catch(Exception $e) {
        Template::display('exception', array('exception' => $e));
    }

    Template::display('!!footer');

} catch(Exception $e) {
    // If all exceptions are catched as expected we should not get there
    die('An exception happened : '.$e->getMessage());
}


text:
project_path: /web/_project.yaml
book_path: /web/shows/_book.yaml

{# wf_updated_on: 2015-02-23 #}
{# wf_published_on: 2015-02-23 #}
{# wf_youtube_id: JuO5AZBrpC8 #}

# Web Components and Polymer Panel {: .page-title }

<div class="video-wrapper">
  <iframe class="devsite-embedded-youtube-video" data-video-id="JuO5AZBrpC8"
          data-autohide="1" data-showinfo="0" frameborder="0" allowfullscreen>
  </iframe>
</div>


text:
using UnityEngine;
using System.Collections;

public class InversionTrigger : MonoBehaviour
{
	/// <summary>
	/// The invaders manager.
	/// </summary>
	private InvadersManager invadersManager;

	// Use this for initialization
	void Start ()
	{
		invadersManager = GameObject.Find("Invaders").GetComponent<InvadersManager>();
	}

	// Update is called once per frame
	void Update ()
	{

	}

	void OnTriggerEnter2D (Collider2D collider)
	{
		if (collider.CompareTag("Invader"))
		{

		}
	}
}


text:
package com.hkm.slider.GalleryWidget;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.hkm.slider.TouchView.FileTouchImageView;

import java.util.List;

/**
 * Class wraps file paths to adapter, then it instantiates {@link com.hkm.slider.TouchView.FileTouchImageView} objects to paging up through them.
 */
public class InfinityFilePagerAdapter extends BasePagerAdapter {

    private int TOTAL_PAGES = -1;
    private int MIN_LOOPS = 1000;
    // You can choose a bigger number for LOOPS, but you know, nobody will fling
    // more than 1000 times just in order to test your "infinite" ViewPager :D
    public int FIRST_PAGE = 1;

    private ImageView.ScaleType mScaleType = null;

    public InfinityFilePagerAdapter(Context context, List<String> resources) {
        super(context, resources);
        TOTAL_PAGES = resources.size();
        FIRST_PAGE = TOTAL_PAGES * MIN_LOOPS / 2;
    }

    @Override
    public void setPrimaryItem(ViewGroup container, int position, Object object) {
        super.setPrimaryItem(container, position, object);
        ((GalleryViewPager) container).mCurrentView = ((FileTouchImageView) object).getImageView();
    }

    @Override
    public Object instantiateItem(ViewGroup collection, int position) {
        final FileTouchImageView iv = new FileTouchImageView(mContext);

        position = position % TOTAL_PAGES;

        iv.setUrl(mResources.get(position));
        iv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

        if (mScaleType != null)
            iv.setScaleType(mScaleType);
        collection.addView(iv, 0);
        return iv;
    }

    /**
     * Set Scaletype for ImageView
     *
     * @param scaletype type
     */
    public void setScaleTypeForImageView(ImageView.ScaleType scaletype) {
        mScaleType = scaletype;
    }

    @Override
    public int getCount() {
        return TOTAL_PAGES * MIN_LOOPS;
    }

};


text:
var gulp = require('gulp'),
connect = require('gulp-connect'),
exit = require('gulp-exit'),
gutil = require("gulp-util"),
plumber = require('gulp-plumber'),
notify = require('gulp-notify'),
sass = require('gulp-sass'),
changed = require('gulp-changed'),
sourcemaps = require('gulp-sourcemaps'),
clean = require('gulp-clean'),
cleanCSS=require('gulp-clean-css'),
shell = require('gulp-shell'),
runSequence = require('run-sequence'),
watch = require('gulp-watch');

var folders={
	public:"public",
	assets:"assets",
	lib:"lib",
	css:"css"
}

var onError = notify.onError ({
   title: 'Error',
   message: '<%= error.message %>'
});

gulp.task("html", function() {
	return gulp.src('./src/*.html')
		.pipe(gulp.dest(folders.public))
		.pipe(connect.reload());
});

gulp.task("lib", function() {
	return gulp.src('./src/'+folders.lib+'/**/*')
		.pipe(gulp.dest(folders.public+'/'+folders.lib))
		.pipe(connect.reload());
});

gulp.task("assets", function(done) {
	runSequence("copyassets" , function() {
         watch('./src/'+folders.assets+'/**/*', function (files) {
         }).pipe(gulp.dest(folders.public+'/'+folders.assets));
        done();
    });
});

gulp.task("copyassets", function() {
	return gulp.src('./src/'+folders.assets+'/**')
		.pipe(gulp.dest(folders.public+'/'+folders.assets))
		.pipe(connect.reload());
});

gulp.task("connect", function() {
	connect.server({
		base: 'http://localhost',
		port: 8080,
		root: folders.public,
		livereload: true
	});
});

gulp.task('sass', function () {
  return gulp.src('./sass/**/*.scss')
	.pipe(plumber({ errorHandler: onError }))
	.pipe(changed(folders.public+'/'+folders.css))
    .pipe(sass().on('error', sass.logError))
    /*.pipe(cleanCSS({compatibility: 'ie8'}))*/
    .pipe(gulp.dest(folders.public+'/'+folders.css))
    .pipe(connect.reload());
});

gulp.task('buildsass', function () {
  return gulp.src('./sass/**/*.scss')
	.pipe(plumber({ errorHandler: onError }))
	.pipe(changed(folders.public+'/'+folders.css))
    .pipe(sass().on('error', sass.logError))
    .pipe(cleanCSS({compatibility: 'ie8'}))
    .pipe(gulp.dest(folders.public+'/'+folders.css))
});

gulp.task("clean", function() {
	return gulp.src(folders.public, {read: false})
		.pipe(clean());
});

gulp.task("watch", function(){
	gulp.watch('./src/*.html', ['html']);
	gulp.watch('./sass/**/*.scss', ['sass']);
});

gulp.task("npm:dev",  shell.task(['npm run dev']));
gulp.task("js:build",  shell.task(['npm run build']));

gulp.task("build", [], function(done) {
	return runSequence('clean', "copyassets", "lib", 'buildsass', "html" ,  "js:build", function() {
        console.log('Everything rebuilt');
        exit();
        done();
    });
});

gulp.task("js:dev",  ["assets", "lib", "sass", "html", "watch", "npm:dev" ]);
gulp.task("css:dev",  ["assets", "lib", "sass", "html", "watch", "js:build", "connect" ]);
gulp.task("default", ["js:dev"]);


text:
using log4net;
using NUnit.Framework;
using OpenSim.Framework;
using System;
using System.Data;
using System.Data.Common;
using System.IO;

namespace OpenSim.Data.Tests
{
    /// <summary>This is a base class for testing any Data service for any DBMS.
    /// Requires NUnit 2.5 or better (to support the generics).
    /// </summary>
    /// <remarks>
    /// FIXME: Should extend OpenSimTestCase but compile on mono 2.4.3 currently fails with
    /// AssetTests`2 : System.MemberAccessException : Cannot create an instance of OpenSim.Data.Tests.AssetTests`2[TConn,TAssetData] because Type.ContainsGenericParameters is true.
    /// and similar on EstateTests, InventoryTests and RegionTests.
    /// Runs fine with mono 2.10.8.1, so easiest thing is to wait until min Mono version uplifts.
    /// </remarks>
    /// <typeparam name="TConn"></typeparam>
    /// <typeparam name="TService"></typeparam>
    public class BasicDataServiceTest<TConn, TService>
        where TConn : DbConnection, new()
        where TService : class, new()
    {
        protected string m_connStr;
        private TService m_service;
        private string m_file;

        // TODO: Is this in the right place here?
        // Later:  apparently it's not, but does it matter here?
        //        protected static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        protected ILog m_log;  // doesn't matter here that it's not static, init to correct type in instance .ctor

        public BasicDataServiceTest()
            : this("")
        {
        }

        public BasicDataServiceTest(string conn)
        {
            m_connStr = !String.IsNullOrEmpty(conn) ? conn : DefaultTestConns.Get(typeof(TConn));

            m_log = LogManager.GetLogger(this.GetType());
            OpenSim.Tests.Common.TestLogging.LogToConsole();    // TODO: Is that right?
        }

        /// <summary>
        /// To be overridden in derived classes. Do whatever init with the m_service, like setting the conn string to it.
        /// You'd probably want to to cast the 'service' to a more specific type and store it in a member var.
        /// This framework takes care of disposing it, if it's disposable.
        /// </summary>
        /// <param name="service">The service being tested</param>
        protected virtual void InitService(object service)
        {
        }

        [TestFixtureSetUp]
        public void Init()
        {
            // Sorry, some SQLite-specific stuff goes here (not a big deal, as its just some file ops)
            if (typeof(TConn).Name.StartsWith("Sqlite"))
            {
                // SQLite doesn't work on power or z linux
                if (Directory.Exists("/proc/ppc64") || Directory.Exists("/proc/dasd"))
                    Assert.Ignore();

                if (Util.IsWindows())
                    Util.LoadArchSpecificWindowsDll("sqlite3.dll");

                // for SQLite, if no explicit conn string is specified, use a temp file
                if (String.IsNullOrEmpty(m_connStr))
                {
                    m_file = Path.GetTempFileName() + ".db";
                    m_connStr = "URI=file:" + m_file + ",version=3";
                }
            }

            if (String.IsNullOrEmpty(m_connStr))
            {
                string msg = String.Format("Connection string for {0} is not defined, ignoring tests", typeof(TConn).Name);
                m_log.Warn(msg);
                Assert.Ignore(msg);
            }

            // Try the connection, ignore tests if Open() fails
            using (TConn conn = new TConn())
            {
                conn.ConnectionString = m_connStr;
                try
                {
                    conn.Open();
                    conn.Close();
                }
                catch
                {
                    string msg = String.Format("{0} is unable to connect to the database, ignoring tests", typeof(TConn).Name);
                    m_log.Warn(msg);
                    Assert.Ignore(msg);
                }
            }

            // If we manage to connect to the database with the user
            // and password above it is our test database, and run
            // these tests.  If anything goes wrong, ignore these
            // tests.
            try
            {
                m_service = new TService();
                InitService(m_service);
            }
            catch (Exception e)
            {
                m_log.Error(e.ToString());
                Assert.Ignore();
            }
        }

        [TestFixtureTearDown]
        public void Cleanup()
        {
            if (m_service != null)
            {
                if (m_service is IDisposable)
                    ((IDisposable)m_service).Dispose();
                m_service = null;
            }

            if (!String.IsNullOrEmpty(m_file) && File.Exists(m_file))
                File.Delete(m_file);
        }

        protected virtual DbConnection Connect()
        {
            DbConnection cnn = new TConn();
            cnn.ConnectionString = m_connStr;
            cnn.Open();
            return cnn;
        }

        protected virtual void ExecuteSql(string sql)
        {
            using (DbConnection dbcon = Connect())
            {
                using (DbCommand cmd = dbcon.CreateCommand())
                {
                    cmd.CommandText = sql;
                    cmd.ExecuteNonQuery();
                }
            }
        }

        protected delegate bool ProcessRow(IDataReader reader);

        protected virtual int ExecQuery(string sql, bool bSingleRow, ProcessRow action)
        {
            int nRecs = 0;
            using (DbConnection dbcon = Connect())
            {
                using (DbCommand cmd = dbcon.CreateCommand())
                {
                    cmd.CommandText = sql;
                    CommandBehavior cb = bSingleRow ? CommandBehavior.SingleRow : CommandBehavior.Default;
                    using (DbDataReader rdr = cmd.ExecuteReader(cb))
                    {
                        while (rdr.Read())
                        {
                            nRecs++;
                            if (!action(rdr))
                                break;
                        }
                    }
                }
            }
            return nRecs;
        }

        /// <summary>Drop tables (listed as parameters). There is no "DROP IF EXISTS" syntax common for all
        /// databases, so we just DROP and ignore an exception.
        /// </summary>
        /// <param name="tables"></param>
        protected virtual void DropTables(params string[] tables)
        {
            foreach (string tbl in tables)
            {
                try
                {
                    ExecuteSql("DROP TABLE " + tbl + ";");
                }
                catch
                {
                }
            }
        }

        /// <summary>Clear tables listed as parameters (without dropping them).
        /// </summary>
        /// <param name="tables"></param>
        protected virtual void ResetMigrations(params string[] stores)
        {
            string lst = "";
            foreach (string store in stores)
            {
                string s = "'" + store + "'";
                if (lst == "")
                    lst = s;
                else
                    lst += ", " + s;
            }

            string sCond = stores.Length > 1 ? ("in (" + lst + ")") : ("=" + lst);
            try
            {
                ExecuteSql("DELETE FROM migrations where name " + sCond);
            }
            catch
            {
            }
        }

        /// <summary>Clear tables listed as parameters (without dropping them).
        /// </summary>
        /// <param name="tables"></param>
        protected virtual void ClearTables(params string[] tables)
        {
            foreach (string tbl in tables)
            {
                try
                {
                    ExecuteSql("DELETE FROM " + tbl + ";");
                }
                catch
                {
                }
            }
        }
    }
}


text:
/**
 * Created by tapes on 2016/10/16.
 */

"use strict";

const path = require('path');
const readFile = require('./processor/read-file');
const parseCsv = require('./processor/parse-csv');
const buildRelation = require('./processor/build-relation');

const orderNumberMap =
    buildRelation.process(
        parseCsv.process(
            readFile.process(path.join(__dirname, '../res/relation.csv'))));

module.exports = {
    deepCopy: function (obj) {
        return JSON.parse(JSON.stringify(obj));
    },

    parseNum: function (numStr) {
        return parseInt(numStr.split(',').join(''), 10);
    },

    isAmazon: function (order) {
        return order[2] == '注文' && order[8] == 'Amazon';
    },

    isXixijie: function (order) {
        return order[2] == '注文' && order[8] == '出品者';
    },

    isRefound: function (order) {
        return order[2] == '返金'
    },

    getRealOrderNumber: function (orderNumber) {
        return orderNumberMap[orderNumber] && orderNumberMap[orderNumber].code || orderNumber;
    },

    getRealOrderSales: function (orderNumber) {
        return orderNumberMap[orderNumber] && orderNumberMap[orderNumber].sales || '';
    }
};


text:
require 'digest/sha1'
class User < ActiveRecord::Base
  # Virtual attribute for the unencrypted password
  attr_accessor :password

  validates_presence_of     :login, :email
  validates_presence_of     :password,                   :if => :password_required?
  validates_presence_of     :password_confirmation,      :if => :password_required?
  validates_length_of       :password, :within => 4..40, :if => :password_required?
  validates_confirmation_of :password,                   :if => :password_required?
  validates_length_of       :login,    :within => 3..40
  validates_length_of       :email,    :within => 3..100
  validates_uniqueness_of   :login, :email, :case_sensitive => false
  before_save :encrypt_password

  # prevents a user from submitting a crafted form that bypasses activation
  # anything else you want your user to change should be added here.
  attr_accessible :login, :email, :password, :password_confirmation

  # Authenticates a user by their login name and unencrypted password.  Returns the user or nil.
  def self.authenticate(login, password)
    u = find_by_login(login) # need to get the salt
    u && u.authenticated?(password) ? u : nil
  end

  # Encrypts some data with the salt.
  def self.encrypt(password, salt)
    Digest::SHA1.hexdigest("--#{salt}--#{password}--")
  end

  # Encrypts the password with the user salt
  def encrypt(password)
    self.class.encrypt(password, salt)
  end

  def authenticated?(password)
    crypted_password == encrypt(password)
  end

protected
  # before filter
  def encrypt_password
    return if password.blank?
    self.salt = Digest::SHA1.hexdigest("--#{Time.now.to_s}--#{login}--") if new_record?
    self.crypted_password = encrypt(password)
  end

  def password_required?
    crypted_password.blank? || !password.blank?
  end

end


text:
/* eslint-disable */
import {
  createFileMap,
  readFileMap,
  encryptFileMap,
  decryptFileMap,
  getRemoteFileMap,
  fileToBuffer
} from './file';
import { generateFileMapKey, generateMasterKey}  from './keys_ids';
import crypto from 'crypto';
import request from 'request';
import { initHost, stopHost } from './peer';

var masterKey, userID, pin, fileMapKey, userName;

// Broker access point
import { brokerURL, myport, seed } from './ENV_variables';

function logoff(callback) {
  stopHost(callback);
}

function signup(userName, pin, callback) { // sign up request to get unique userID from broker

  // do magic to check userID is unique with the server
    const userID = crypto.createHash('sha1').update(new Buffer(userName)).digest('hex');
    console.log('userID: ' + userID);
    const requestURL = brokerURL + 'signup';
    setUserID(userID);
    setUserName(userName);
    createFileMap(()=>{
      generateFileMapKey(userID, pin, (fileMapKey) => {
        setFileMapKey(fileMapKey);
        encryptFileMap((fileMapBuffer)=>{
          console.log(fileMapBuffer);
            request.post(
              requestURL,
              { json:{username: userName, fileMap: fileMapBuffer }},
              (error, response, body) => {
                console.log(body);
                console.log(userID);
                //console.log(body);
                if (!error && response.statusCode == 200) {
                  console.log('Signup complete! Welcome '+userID);
                  return callback(userID, null);
                } else {
                  if (response.body.message == 'User already exists')return callback(null,'Username already exists!');
                  else return callback(null,'Problem reaching server!');
                }
              }
          );
      });
    });
  });
}

function login(userName, pin, callback) { // login request to get the fileMap from the broker
  console.log('Authenticating ...');
  const requestURL = brokerURL + 'signin';
  const userID = crypto.createHash('sha1').update(new Buffer(userName)).digest('hex');
  request.post(
    requestURL,
    {json: {username: userName}},
     (error, response, body) => {
        if (!error && response.statusCode == 200) {
          setUserName(userName);
          setUserID(userID);
          setPin(pin);
          generateFileMapKey(userID, pin, (fileMapKey) => { //generate the fileMapKey
            //.log('\tfile map key generated!\t'+fileMapKey);
            setFileMapKey(fileMapKey);
              const brokerFileMap = new Buffer(body.fileMap);
              //console.log('filemap: ' + brokerFileMap);
              // brokerFileMap = new Buffer(brokerFileMap);
              getRemoteFileMap(brokerFileMap, (updatedFileMap, error)=>{// generate the rest of keys using the remote fileMap
                if(error) {
                  console.log(error);
                  return callback(null, error);
                }
                //console.log('filemap: ' + updatedFileMap);
                generateMasterKey(fileMapKey, updatedFileMap['rnd'], (mKey) => {
                //  console.log('\tmaster key generated!\t'+mKey);
                  console.log('Authentication complete! Welcome back '+userID);
                  setMasterKey (mKey);
                  //console.log('received user ID: ' + userID);
                  initHost(myport, userID, seed, () => {
                    console.log('====== Host Initialized Successfuly =======');
                    return callback(userID, null);
                  });
                });
              });
          });
            //console.log(body);
        } else {
          if (response.body.message == 'User does not exist')return callback(null,'Username does not exist!');
          else return callback(null,'Problem reaching server!');
        }
    }
  );
}

function setUserName (uName) { // Sets the userID
  userName = uName;
}

function setUserID (uID) { // Sets the userID
  userID = uID;
}

function setPin (uPin) { // Sets the user's pin
   pin = uPin;
}

function setFileMapKey (filemapKey) { // Sets the MasterKey
  fileMapKey = filemapKey;
}

function setMasterKey (mKey) { // Sets the MasterKey
  masterKey = mKey;
}

function getUserName () { // Sets the userID
  return userName;
}
function getUserID () { // get the userID
  return userID;
}

function getPin () { // gets the user's pincode supplied at login
  return pin;
}

function getMasterKey () { // gets the MasterKey
  return masterKey;
}

function getFileMapKey () { // gets the MasterKey
  return fileMapKey;
}

export {
  login,
  signup,
  logoff,
  getUserID,
  getPin,
  getMasterKey,
  getFileMapKey,
  setUserID,
  setPin,
  setMasterKey,
  setUserName,
  getUserName
};


text:
package ch.jalu.configme.properties.types;

import ch.jalu.configme.properties.convertresult.ConvertErrorRecorder;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class EnumPropertyType<E extends Enum<E>> implements PropertyType<E> {

    private Class<E> enumType;

    public EnumPropertyType(@NotNull Class<E> enumType) {
        this.enumType = enumType;
    }

    public static <E extends Enum<E>> @NotNull EnumPropertyType<E> of(@NotNull Class<E> type) {
        return new EnumPropertyType<>(type);
    }

    @Override
    public @Nullable E convert(@Nullable Object object, @NotNull ConvertErrorRecorder errorRecorder) {
        // If object is enum, then return this object, casting to E
        if (enumType.isInstance(object)) {
            return (E) object;
        }

        // If object is not string, then we return null, because else we cant find an enum
        if (!(object instanceof String)) {
            return null;
        }

        String name = (String) object;
        for (E entry : enumType.getEnumConstants()) {
            if (entry.name().equalsIgnoreCase(name)) {
                return entry;
            }
        }

        return null;
    }

    @Override
    public @NotNull Object toExportValue(@NotNull E value) {
        return value.name();
    }
}


text:
@interface MenuTableViewCell : DCTableViewCell

@property(nonatomic,readonly) UILabel *titleLabel;

@end


text:
package com.google.cloud.dataplex.v1.samples;

// [START dataplex_v1_generated_DataplexService_CreateEnvironment_async]
import com.google.api.core.ApiFuture;
import com.google.cloud.dataplex.v1.CreateEnvironmentRequest;
import com.google.cloud.dataplex.v1.DataplexServiceClient;
import com.google.cloud.dataplex.v1.Environment;
import com.google.cloud.dataplex.v1.LakeName;
import com.google.longrunning.Operation;

public class AsyncCreateEnvironment {

  public static void main(String[] args) throws Exception {
    asyncCreateEnvironment();
  }

  public static void asyncCreateEnvironment() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (DataplexServiceClient dataplexServiceClient = DataplexServiceClient.create()) {
      CreateEnvironmentRequest request =
          CreateEnvironmentRequest.newBuilder()
              .setParent(LakeName.of("[PROJECT]", "[LOCATION]", "[LAKE]").toString())
              .setEnvironmentId("environmentId-950205810")
              .setEnvironment(Environment.newBuilder().build())
              .setValidateOnly(true)
              .build();
      ApiFuture<Operation> future =
          dataplexServiceClient.createEnvironmentCallable().futureCall(request);
      // Do something.
      Operation response = future.get();
    }
  }
}
// [END dataplex_v1_generated_DataplexService_CreateEnvironment_async]


text:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from functions import find_element
from functions import open_site
from elements import MainPage
import php4dvd_homework_3

class TestVideoSearch():
   def test_search_existing_video(self, open_site):
       #Перед запуском теста на удаление добавляем фильм, используя тест на добавление
       driver = open_site
       real_movie = 'Matrix'
       my_test = php4dvd_homework_3.TestVideoAdd()
       my_test.test_new_video_required_fields(driver, title=real_movie, year='1999')
       find_element(driver, MainPage.HOME_BUTTON).click()
       find_element(driver, MainPage.SEARCH_MOVIE).send_keys(real_movie)
       find_element(driver, MainPage.SEARCH_MOVIE).send_keys(Keys.ENTER)
       find_element(driver, (By.XPATH, '//div[@class="title"][contains(text(), %s)]' %real_movie))

   def test_search_no_existing_video(self, open_site):
       #Перед запуском теста на удаление добавляем фильм, используя тест на добавление
       driver = open_site
       unreal_movie = u'Груз 200'
       find_element(driver, MainPage.SEARCH_MOVIE).send_keys(unreal_movie)
       find_element(driver, MainPage.SEARCH_MOVIE).send_keys(Keys.ENTER)
       find_element(driver, (By.XPATH, '//*[contains(text(), "No movies where found.")]'))


text:
/**
 * Treat this as a JSON data object, fetched via a Settings model instead??
 */
(function(root, factory) {
  if(typeof define === 'function' && define.amd) {
    // AMD (Register as an anonymous module)
    define('settings',['jquery'], factory);
  } else if(typeof exports === 'object') {
    // Node/CommonJS
    module.exports = factory(require('jquery'));
  } else {
    // Browser globals
    root.Settings = factory($);
  }
}(this, function($) {
  // initialize with default settings
  var Settings =  {
    'tournament_year': 2017,

    // set this var to false when nav is invitees, true when it's players page
    'playersListNav': true,

    // set this var to false when nav is tournament LB, true when it's Par 3
    'leaderboardPar3': false,

    // set this to true to show the favorites filter on the home and watch pages
    'showFavorites': true,

    // uncomment this var only when round 1 pairings should be default on tee times
    // if commented out, tee times will default to latest round available in data feed
    'default_pairings_round': 1,

    // set this to enable/disable console output by default
    // - can be overridden with query param +debug+ set to "true|console"
    'enable_logging': true,

    'default_broadcast_channel': 'simul',

    'Scores': {
      'pre': false, // scoring has not yet begun, don't fetch score file
      'live': true, // scoring is active
      'post': false, // scoring has completed, only fetch score file once

      'stub_track': false // whether Track should be stubbed or not
    }
  };

  /**
   * Sample file contents of settings.json that match the defaults above.
   * Delete all comments from JSON file, else won't parse as valid JSON.
   *
   {
     "ty": 2016,    // tournament_year
     "pln": true,   // playersListNav
     "p3": false,   // leaderboardPar3
     "f": true,     // shotFavorites
     "pr": 1,       // default_pairings_round
     "el": true,    // enable_logging
     "ch": "simul", // default_broadcast_channel
     "s": {         // Scores
       "p": false,  //  pre
       "l": true,   //  live
       "t": false,  //  post
       "st": false  //  stub_track
     }
   }
   */

  // synchronously fetch updated settings
  $.ajax('/en_US/xml/man/settings.json', {
    async: false,
    dataType: 'json',
    success: function(data) {
      Settings = {
        tournament_year: data.ty,
        playersListNav: data.pln,
        leaderboardPar3: data.p3,
        showFavorites: data.f,
        default_pairings_round: data.pr,
        enable_logging: data.el,
        default_broadcast_channel: data.ch,
        Scores: {
          pre: data.s.p,
          live: data.s.l,
          post: data.s.t,
          stub_track: data.s.st
        }
      };
    }
  });

  return Settings;
}));


text:
import { registerTranslation } from '../utilities/localize';
import type { Translation } from '../utilities/localize';

const translation: Translation = {
  $code: 'nl',
  $name: 'Dutch',
  $dir: 'ltr',

  clearEntry: 'Invoer wissen',
  close: 'Sluiten',
  copy: 'Kopiëren',
  currentValue: 'Huidige waarde',
  hidePassword: 'Verberg wachtwoord',
  loading: 'Bezig met laden',
  progress: 'Voortgang',
  remove: 'Verwijderen',
  resize: 'Formaat wijzigen',
  scrollToEnd: 'Scroll naar einde',
  scrollToStart: 'Scroll naar begin',
  selectAColorFromTheScreen: 'Selecteer een kleur van het scherm',
  showPassword: 'Laat wachtwoord zien',
  toggleColorFormat: 'Wissel kleurnotatie'
};

registerTranslation(translation);

export default translation;


text:
GridcoinAutoNode
===============

A script that automatically sets up a Gridcoin full node as a daemon (`gridcoinresearchd`) under a new `gridcoin` user.

Tested on:

- Ubuntu Trusty (14.04)
- Ubuntu Xenial (16.04)
- Ubuntu Bionic (18.04)
- Debian Jessie (8)
- Debian Stretch (9)

One Liner - DO NOT run without reading code first!
--------------------------------------------------

    wget https://raw.githubusercontent.com/gridcoin-community/Autonode/master/GridcoinAutoNode.sh && sudo -E bash GridcoinAutoNode.sh && . .bashrc

Notes
-----

This script installs:
- unzip
- software-properties-common
- gridcoinresearchd (and dependencies)
- curl
- apt-transport-https

This script:
- Automatically figures out your distro and installs the daemon (`gridcoinresearchd`) for that specific distro.
- Creates a `gridcoin` user to run `gridcoinresearchd` (safer than running client as root).
- Downloads snapshot instead of syncing from block 0 (edit script if you don't want it to do this).
- Starts daemon on script completion.
- Creates a `grc` alias (for instance, you can run `grc getinfo`).


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

using Nucleo.Collections;

namespace Nucleo.Reflection
{
	public class ReflectMethodList : BaseReflectMemberList
	{
		#region " Constructors "

		public ReflectMethodList(object target, bool isPrivate)
			: base(target, isPrivate) { }

		#endregion

		#region " Methods "

		private MethodInfo[] GetMethods()
		{
			return this.Target.GetType().GetMethods(this.GetFlags());
		}

		public ReflectMethodCollection WithAttribute(Type attributeType)
		{
			MethodInfo[] methods = this.GetMethods();
			ReflectMethodCollection outputList = new ReflectMethodCollection();

			foreach (MethodInfo method in methods)
			{
				if (method.GetCustomAttributes(attributeType, true).Length > 0)
					outputList.Add(new ReflectMethod(method.Name, base.Target, base.IsPrivate));
			}

			return outputList;
		}

		#endregion
	}
}


text:
package sbahjsic.interpreter.compiler;

import sbahjsic.runtime.Block.BlockBuilder;
import sbahjsic.runtime.RuntimeContext;
import sbahjsic.runtime.Scope;
import sbahjsic.runtime.type.SNull;
import sbahjsic.runtime.type.SScope;

final class With extends Instruction {

	final static With INSTANCE = new With();

	@Override
	public void execute(RuntimeContext runtime) {
		if(!runtime.blockStack().top().isExecuted()) {
			runtime.blockStack().push(new BlockBuilder("with-indefinite")
					.setIsExecuted(false)
					.setPermittedInstructions(InstructionType.CONTROL_FLOW)
					.build());
			return;
		}

		Scope oldScope = runtime.scope();
		Scope with = ((SScope) runtime.pop().refersTo()).scope();

		runtime.replaceScope(with);

		runtime.blockStack().push(new BlockBuilder("with")
				.setIsExecuted(true)
				.setSaveInstructions(true) // Extremely dirty hack!
				.setInstructionsConsumer((con, ins) -> {
					runtime.replaceScope(oldScope);
					runtime.scope().set("scope", new SScope(oldScope));
					runtime.scope().set("super", oldScope.parent() == null ?
							SNull.NULL : new SScope(oldScope.parent()));
				})
				.build());
	}

	@Override
	public String toString() {
		return "with";
	}

	@Override
	public InstructionType type() {
		return InstructionType.WITH;
	}

}


text:
var wns = require('../lib/wns.js')
	, assert = require('assert')
	, templateSpecs = require('./templates.js').specs
	, recordLiveSession = false
	, createResults = recordLiveSession ? undefined : require('./createResults.js').results
	, createBindingResults = recordLiveSession ? undefined : require('./createBindingResults.js').results
	, fs = require('fs');

// normalize test APIs between TDD and BDD
if (!global.describe) {
	describe = suite;
	it = test;
}

testCreateMethods('', __dirname + '/createResults.js', createResults);
testCreateMethods('Binding', __dirname + '/createBindingResults.js', createBindingResults);

function testCreateMethods(methodSuffix, logFile, expected) {
	var count = 0;
	var total = Object.getOwnPropertyNames(templateSpecs).length;
	var options = {
		lang: 'en-us',
		audio: {
			src: 'Alarm',
			silent: false,
			loop: true
		}
	};

	if (recordLiveSession) {
		fs.writeFileSync(logFile, '// this file is auto-generated from apis.js\n\nexports.results = {\n');
	}

	for (var item in templateSpecs) {
		(function (item) {
			var template = templateSpecs[item];
			describe('wns.create' + item + methodSuffix, function () {
				it('succeeds', function (done) {
					// test passing string parameters in
					var params = [];
					for (var i = 0; i < ((template[0] * 2) + template[1]); i++)
						params.push('item' + i);

					params.push(options);
					var result = wns['create' + item + methodSuffix].apply(this, params);
					if (recordLiveSession) {
						fs.appendFileSync(logFile, '    ' + item + 'Plain: \'' + result + '\',\n');
					}
					else {
						assert.equal(result, expected[item + 'Plain']);
					}

					// test passing an object in
					var payload = { lang: 'en-gb' };
					var k = 0;
					for (var i = 0; i < template[0]; i++) {
						payload['image' + (i+1) + 'src'] = 'item' + k++;
						payload['image' + (i+1) + 'alt'] = 'item' + k++;
					}

					for (var i = 0; i < template[1]; i++) {
						payload['text' + (i+1)] = 'item' + k++;
					}

					result = wns['create' + item + methodSuffix].call(this, payload, options);
					if (recordLiveSession) {
						fs.appendFileSync(logFile, '    ' + item + 'Object: \'' + result + '\',\n');
						if (++count == total) {
							fs.appendFileSync(logFile, '};\n');
						}
					}
					else {
						assert.equal(result, expected[item + 'Object']);
					}

					done();
				});
			});
		})(item);
	}
}

describe('wns.createToast', function () {
	it('fails without parameters', function () {
		assert.throws(
			wns.createToast,
			/At least one binding must be specified/
		);
	});

	it('fails with wrong parameter types', function () {
		assert.throws(
			function () { wns.createToast(12); },
			/Unsuported type of argument: number/
		);
	});

	it('fails with non-binding string parameter', function () {
		assert.throws(
			function () { wns.createToast('foo'); },
			/Every string argument must be a WNS binding XML/
		);
	});

	it('succeeds with plain parameters', function () {
		var result = wns.createToast(
			wns.createToastText01Binding('foo'),
			wns.createToastText01Binding('bar'),
			{ lang: 'en-gb', audio: { src: 'Alarm', loop: true } }
		);
		assert.equal(result, '<toast><visual lang="en-gb"><binding template="ToastText01"><text id="1">foo</text></binding>' +
			'<binding template="ToastText01"><text id="1">bar</text></binding></visual>' +
			'<audio src="ms-winsoundevent:Notification.Alarm" loop="true"/></toast>');
	});

	it('succeeds with object parameters', function () {
		var result = wns.createToast(
			{ type: 'ToastText01', text1: 'foo', lang: 'pl' },
			{ type: 'ToastText01', text1: 'bar', lang: 'en-us' },
			{ lang: 'en-gb', audio: { src: 'Alarm', loop: true } }
		);
		assert.equal(result, '<toast><visual lang="en-gb"><binding template="ToastText01" lang="pl"><text id="1">foo</text></binding>' +
			'<binding template="ToastText01" lang="en-us"><text id="1">bar</text></binding></visual>' +
			'<audio src="ms-winsoundevent:Notification.Alarm" loop="true"/></toast>');
	});
});

describe('wns.createTile', function () {
	it('fails without parameters', function () {
		assert.throws(
			wns.createTile,
			/At least one binding must be specified/
		);
	});

	it('fails with wrong parameter types', function () {
		assert.throws(
			function () { wns.createTile(12); },
			/Unsuported type of argument: number/
		);
	});

	it('fails with non-binding string parameter', function () {
		assert.throws(
			function () { wns.createTile('foo'); },
			/Every string argument must be a WNS binding XML/
		);
	});

	it('succeeds with plain parameters', function () {
		var result = wns.createTile(
			wns.createTileSquareText04Binding('foo'),
			wns.createTileSquareText04Binding('bar'),
			{ lang: 'en-gb' }
		);
		assert.equal(result, '<tile><visual lang="en-gb"><binding template="TileSquareText04"><text id="1">foo</text></binding>' +
			'<binding template="TileSquareText04"><text id="1">bar</text></binding></visual></tile>');
	});

	it('succeeds with object parameters', function () {
		var result = wns.createTile(
			{ type: 'TileSquareText04', text1: 'foo', lang: 'pl' },
			{ type: 'TileSquareText04', text1: 'bar', lang: 'en-us' },
			{ lang: 'en-gb' }
		);
		assert.equal(result, '<tile><visual lang="en-gb"><binding template="TileSquareText04" lang="pl"><text id="1">foo</text></binding>' +
			'<binding template="TileSquareText04" lang="en-us"><text id="1">bar</text></binding></visual></tile>');
	});
});

describe('wns.send', function () {
	it('fails without parameters', function () {
		assert.throws(
			wns.send,
			/The channel parameter must be the channel URI string/
		);
	});

	it ('fails with wrong channel type', function () {
		assert.throws(
			function () { wns.send({}) },
			/The channel parameter must be the channel URI string/
		);
	});

	it ('fails without payload', function () {
		assert.throws(
			function () { wns.send('http://foo') },
			/The payload parameter must be the notification payload string/
		);
	});

	it ('fails with wrong payload type', function () {
		assert.throws(
			function () { wns.send('http://foo') },
			/The payload parameter must be the notification payload string/
		);
	});

	it ('fails without type', function () {
		assert.throws(
			function () { wns.send('http://foo', 'payload') },
			/The type parameter must specify the notification type/
		);
	});

	it ('fails with wrong payload type', function () {
		assert.throws(
			function () { wns.send('http://foo', 'payload') },
			/The type parameter must specify the notification type/
		);
	});

	it ('fails without credentials', function () {
		assert.throws(
			function () { wns.send('http://foo', 'payload', 'wns/tile'); },
			/The options.client_id and options.client_secret must be specified as strings/
		);
	});

	it ('fails with wrong callback type', function () {
		assert.throws(
			function () { wns.send('http://foo', 'payload', 'wns/tile', { client_id: 'foo', client_secret: 'bar' }, {}); },
			/The callback parameter, if specified, must be the callback function/
		);
	});
});

describe('wns.sendBadge', function () {
	it('fails without parameters', function () {
		assert.throws(
			wns.sendBadge,
			/The badge value must be a string or a number/
		);
	});

	it ('fails with wrong channel type', function () {
		assert.throws(
			function () { wns.sendBadge({}) },
			/The badge value must be a string or a number/
		);
	});

	it ('fails without value', function () {
		assert.throws(
			function () { wns.sendBadge('http://foo') },
			/The badge value must be a string or a number/
		);
	});

	it ('fails with too small integer value type', function () {
		assert.throws(
			function () { wns.sendBadge('http://foo', -1) },
			/The badge numeric value must be greater than or equal to 0/
		);
	});

	it ('fails with invalid string value type', function () {
		assert.throws(
			function () { wns.sendBadge('http://foo', 'foobar') },
			/The badge value must be either an integer greater than or equal to 0 or one of/
		);
	});

	it ('fails without credentials', function () {
		assert.throws(
			function () { wns.sendBadge('http://foo', 'alert'); },
			/The options.client_id and options.client_secret must be specified as strings/
		);
	});

	it ('fails with wrong callback type', function () {
		assert.throws(
			function () { wns.sendBadge('http://foo', 'alert', { client_id: 'foo', client_secret: 'bar' }, {}); },
			/The callback parameter, if specified, must be the callback function/
		);
	});
});

describe('wns.sendTileWideImageAndText01', function () {
	it('fails without parameters', function () {
		assert.throws(
			wns.sendTileWideImageAndText01,
			/The channel parameter must be the channel URI string/
		);
	});

	it ('fails with wrong channel type', function () {
		assert.throws(
			function () { wns.sendTileWideImageAndText01({}) },
			/The channel parameter must be the channel URI string/
		);
	});

	it ('fails without values', function () {
		assert.throws(
			function () { wns.sendTileWideImageAndText01('http://foo') },
			/The TileWideImageAndText01 WNS notification type requires 3 text parameters to be specified/
		);
	});

	it ('fails with too few values', function () {
		assert.throws(
			function () { wns.sendTileWideImageAndText01('http://foo', 'a', 'b') },
			/The TileWideImageAndText01 WNS notification type requires 3 text parameters to be specified/
		);
	});

	it ('fails with wrong value types', function () {
		assert.throws(
			function () { wns.sendTileWideImageAndText01('http://foo', 'a', {}) },
			/The TileWideImageAndText01 WNS notification type requires 3 text parameters to be specified/
		);
	});

	it ('fails without credentials', function () {
		assert.throws(
			function () { wns.sendTileWideImageAndText01('http://foo', {}); },
			/The options.client_id and options.client_secret must be specified as strings/
		);
	});

	it ('fails with wrong callback type', function () {
		assert.throws(
			function () { wns.sendTileWideImageAndText01('http://foo', {}, { client_id: 'foo', client_secret: 'bar' }, {}); },
			/The callback parameter, if specified, must be the callback function/
		);
	});
});


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Timelapse</string>
    <string name="action_settings">Settings</string>

    <string name="service_toggle_title">Start Timelapse</string>
    <string name="photo_time_title">Photo Time</string>
    <string name="photo_time_default">5</string>

    <string name="pause_before_photo_time_title">Pause Before Photo Time</string>
    <string name="pause_before_photo_time_default">1</string>

 	<string name="stepper_direction_title">Stepper Direction</string>
    <string name="stepper_direction_default">true</string>

    <string name="total_time_title">Total Time</string>
    <string name="total_time_default">0</string>

    <string name="steps_per_inch_title">Steps Per Inch</string>
    <string name="steps_per_inch_default">180</string>

    <string name="microsteps_title">Microsteps</string>
    <string name="microsteps_default">8</string>

    <string name="speed_title">Steeper Speed (Inches Per Second)</string>
    <string name="speed_default">1</string>

    <string name="dolly_length_title">Dolly Length</string>
    <string name="dolly_length_default">30</string>

    <string name="inches_per_pause_title">Inches Per Pause</string>
    <string name="inches_per_pause_default">1</string>

    <string name="canon_ticks_title">Canon Ticks</string>
    <string name="canon_ticks_default">14</string>
</resources>


text:
layout: post
published: true
link: http://www.nomachetejuggling.com/2011/11/11/the-star-wars-saga-suggested-viewing-order/
title: "Star Wars: Machete Order"
permalink: /2013/01/star-wars-machete-order/
---

I still remember watching the 1997 Special Edition releases at the cinema with my Dad and then dressing up as a jedi to go and see The Phantom Menace with my friends when I was 9.

Having recently watched Star Wars in the "machete order" I agree with much of this article and I think it'll be the way I introduce my kids to Star Wars one day.

It's worth mentioning that I also really enjoyed the 2008 Star Wars Clone Wars film and the CGI TV series; the most recent season was very political (and violent) and for a "kids" show I found myself looking forward to waiting for the next episode each week. That and the animation was some of the best I've ever seen.


text:
<?php
/**
 * This file belongs to the YIT Framework.
 *
 * This source file is subject to the GNU GENERAL PUBLIC LICENSE (GPL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl-3.0.txt
 */

if ( ! defined( 'YIT' ) ) {
    exit( 'Direct access forbidden.' );
}

extract( $args );

$id = empty( $id ) ? '' : " id=\"$id\"";
?>
<p<?php echo $id ?>><?php echo $desc ?></p>


text:
sudo apt-get purge \
apport apport-gtk python3-apport \
unity-webapps-common


text:
package org.fundaciobit.administraciodigital.helium.jbpm3.handlers;

import java.util.List;
import net.conselldemallorca.helium.jbpm3.api.HeliumActionHandler;
import net.conselldemallorca.helium.jbpm3.api.HeliumApi;
import net.conselldemallorca.helium.jbpm3.handlers.exception.HeliumHandlerException;
import org.jbpm.JbpmConfiguration;
import org.jbpm.JbpmContext;
import org.jbpm.graph.exe.ExecutionContext;
import org.jbpm.graph.exe.ProcessInstance;

/**
 *
 * @author gdeignacio
 */
public class ExpedientGeorefETRS89ModificarHandler extends HeliumActionHandler {

    String posETRS89x;
    String varPosETRS89x;
    String posETRS89y;
    String varPosETRS89y;
    String Referencia;
    String varReferencia;

    private static final long serialVersionUID = 3513847803530877133L;

    /**
     *
     * @param api
     * @throws HeliumHandlerException
     */
    @Override
    public void execute(HeliumApi api) throws HeliumHandlerException {

        JbpmContext context = JbpmConfiguration.getInstance().createJbpmContext();

        ExecutionContext executionContext = new ExecutionContext(context.getToken(api.getToken().getId()));

        ProcessInstance processInstance = context.getToken(api.getToken().getId()).getProcessInstance();

   }

    @Override
    public void retrocedir(HeliumApi api, List<String> list) throws Exception {
        return;
    }

    public void setPosETRS89x(String posETRS89x) {
        this.posETRS89x = posETRS89x;
    }

    public void setVarPosETRS89x(String varPosETRS89x) {
        this.varPosETRS89x = varPosETRS89x;
    }

    public void setPosETRS89y(String posETRS89y) {
        this.posETRS89y = posETRS89y;
    }

    public void setVarPosETRS89y(String varPosETRS89y) {
        this.varPosETRS89y = varPosETRS89y;
    }

    public void setReferencia(String Referencia) {
        this.Referencia = Referencia;
    }

    public void setVarReferencia(String varReferencia) {
        this.varReferencia = varReferencia;
    }

}


text:
import React, {Component} from 'react';
import {Textfield} from 'react-mdl';

export default class Search extends Component {

  render() {
    return (
      <div>
        <Textfield
          onChange={() => {}}
          label="Expandable Input"
          expandable
          expandableIcon="search"/>

      </div>
    );
  };

};