text:
package blog.model;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;

import blog.sample.EvalContext;

/**
 * Represents an equality test on 2 expressions, each of which is a
 * non-boolean-valued Term.
 *
 * @see blog.model.Formula
 */
public class EqualityFormula extends Formula {

  public EqualityFormula(Term eq1, Term eq2) {

    this.eq1 = eq1;
    this.eq2 = eq2;

  }

  public Term getTerm1() {

    return eq1;

  }

  public Term getTerm2() {

    return eq2;

  }

  public Object evaluate(EvalContext context) {
    Object t1Value = eq1.evaluate(context);
    if (t1Value == null) {
      return null;
    }

    Object t2Value = eq2.evaluate(context);
    if (t2Value == null) {
      return null;
    }

    if (t1Value == t2Value) {
      return Boolean.TRUE; // even if they're both a GenericObject
    }
    if ((t1Value instanceof GenericObject)
        || (t2Value instanceof GenericObject)) {
      // Can't tell what GenericObject is equal to, besides itself
      return null;
    }

    return Boolean.valueOf(t1Value.equals(t2Value));
  }

  public Collection getSubExprs() {
    List terms = new ArrayList();
    terms.add(eq1);
    terms.add(eq2);
    return Collections.unmodifiableList(terms);
  }

  /**
   * Returns true.
   */
  public boolean isLiteral() {
    return true;
  }

  public List getTopLevelTerms() {
    List terms = new ArrayList();
    terms.add(eq1);
    terms.add(eq2);
    return Collections.unmodifiableList(terms);
  }

  /**
   * Returns the term that, according to this equality formula, has the same
   * denotation as subject. Returns null if subject is
   * not one of the terms in this equality.
   */
  public Term getEqualTerm(Term subject) {
    if (eq1.equals(subject)) {
      return eq2;
    }
    if (eq2.equals(subject)) {
      return eq1;
    }
    return null;
  }

  /**
   * Returns true if this equality formula asserts that subject has
   * the same denotation as the constant "null".
   */
  public boolean assertsNull(Term subject) {
    return ((eq1.equals(subject) && eq2.isConstantNull()) || (eq2
        .equals(subject) && eq1.isConstantNull()));
  }

  public Set getSatisfiersIfExplicit(EvalContext context, LogicalVar subject,
      GenericObject genericObj) {
    Set result = null;
    context.assign(subject, genericObj);

    Term other = getEqualTerm(subject);
    if (other != null) {
      // Subject is one of the terms in this formula. If the
      // other term can be evaluated for genericObj, then the
      // only possible satisifer is the value of that other term.
      Object otherValue = other.evaluate(context);
      if (otherValue != null) {
        if (genericObj.isConsistentInContext(context, otherValue)) {
          result = Collections.singleton(otherValue);
        } else {
          result = Collections.EMPTY_SET;
        }
      }
    } else {
      // If this formula can be evaluated for genericObj, we can still
      // determine the satisfier set.
      Boolean value = (Boolean) evaluate(context);
      if (value != null) {
        result = (value.booleanValue() == true ? Formula.ALL_OBJECTS
            : Collections.EMPTY_SET);
      }
    }

    context.unassign(subject);
    return result;
  }

  public Set getNonSatisfiersIfExplicit(EvalContext context,
      LogicalVar subject, GenericObject genericObj) {
    Set result = null;
    context.assign(subject, genericObj);

    // If this formula can be evaluated for genericObj, we can determine
    // the non-satisfier set.
    Boolean value = (Boolean) evaluate(context);
    if (value != null) {
      result = (value.booleanValue() == false ? Formula.ALL_OBJECTS
          : Collections.EMPTY_SET);
    }
    // Otherwise, nothing we can do

    context.unassign(subject);
    return result;
  }

  /**
   * Two EqualityFormulas are equal if they have the same pair of terms.
   */
  public boolean equals(Object o) {
    if (o instanceof EqualityFormula) {
      EqualityFormula other = (EqualityFormula) o;
      return (eq1.equals(other.getTerm1()) && eq2.equals(other.getTerm2()));
    }
    return false;
  }

  public int hashCode() {
    return (getClass().hashCode() ^ eq1.hashCode() ^ eq2.hashCode());
  }

  /**
   * Returns a string of the form (t1 = t2) where t1 and t2 are the terms being
   * compared in this EqualityFormula.
   */
  public String toString() {
    return ("(" + eq1 + " = " + eq2 + ")");
  }

  /**
   * An equality formula is properly typed if the type of one term is a subtype
   * of the type of the other term.
   */
  public boolean checkTypesAndScope(Model model, Map scope, Type childType) {

    if ((eq1 == null) || (eq2 == null)) {
      return false;
    }

    Term eq1InScope = eq1.getTermInScope(model, scope);
    Term eq2InScope = eq2.getTermInScope(model, scope);
    if ((eq1InScope == null) || (eq2InScope == null)) {
      return false;
    }
    eq1 = eq1InScope;
    eq2 = eq2InScope;

    Type t1 = eq1.getType();
    Type t2 = eq2.getType();
    if ((t1 == null) || (t2 == null) || t1.isSubtypeOf(t2)
        || t2.isSubtypeOf(t1)) {
      return true;
    } else {
      System.err.println(getLocation() + ": Terms in equality/inequality "
          + "formula are of disjoint types " + t1.toString() + " and "
          + t2.toString());
      return false;
    }
  }

  public ArgSpec replace(Term t, ArgSpec another) {
    Term newEq1 = (Term) eq1.replace(t, another);
    Term newEq2 = (Term) eq2.replace(t, another);
    if (newEq1 != eq1 || newEq2 != eq2)
      return compileAnotherIfCompiled(new EqualityFormula(newEq1, newEq2));
    return this;
  }

  public ArgSpec getSubstResult(Substitution subst, Set<LogicalVar> boundVars) {
    return new EqualityFormula((Term) eq1.getSubstResult(subst, boundVars),
        (Term) eq2.getSubstResult(subst, boundVars));
  }

  private Term eq1;
  private Term eq2;
}


text:
const getMidnight = date => {
  const resultDate = date ? new Date(date.getTime()) : new Date()
  resultDate.setHours(0, 0, 0, 0)
  return resultDate
}

export default getMidnight

redpajama_set_name: RedPajamaGithub


text:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-comp-2250',
  templateUrl: './comp-2250.component.html',
  styleUrls: ['./comp-2250.component.css']
})
export class Comp2250Component implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}


text:
usage="$(basename "$0") [-h] [-v <number>] [-s <number>] [-t <text>] -- program to generate Webdriver Torso-esque video clips

where:
    -h  show this help text
    -v  set the number of videos to generate (default: 1)
    -s  set the number of slides to generate for each video (default: 10)
    -t  set the text that appears before each slide number (default: aqua.flv)"

while getopts ':hv:s:t:' option; do
  case "$option" in
    h) echo "$usage"
       exit
       ;;
    v) VIDEOS=$OPTARG
       ;;
	s) SLIDES=$OPTARG
       ;;
	t) TEXT=$OPTARG
       ;;
    :) printf "missing argument for -%s\n" "$OPTARG" >&2
       echo "$usage" >&2
       exit 1
       ;;
   \?) printf "illegal option: -%s\n" "$OPTARG" >&2
       echo "$usage" >&2
       exit 1
       ;;
  esac
done
shift $((OPTIND - 1))

C1=0

while [ ${C1:-0} -lt ${VIDEOS:-1} ]; do

	C2=0

	# Generate random 6 digit video ID and delete tmp file
	VIDEO=$(mktemp XXXXXX)
	rm $VIDEO

	# Generate slide audio and video in loop
	while [ ${C2:-0} -lt ${SLIDES:-10} ]; do
		# Generate random numbers in range for SINE wave frequency and rectangle coordinates
		SINE=$((RANDOM%3300+300))
		rec1_x1=$((RANDOM%640+0))
		rec1_x2=$((RANDOM%640+0))
		rec1_y1=$((RANDOM%330+0))
		rec1_y2=$((RANDOM%330+0))
		rec2_x1=$((RANDOM%640+0))
		rec2_x2=$((RANDOM%640+0))
		rec2_y1=$((RANDOM%330+0))
		rec2_y2=$((RANDOM%330+0))

		# Uses ImageMagick library to generate slide pictures (http://imagemagick.org/)
		convert -size '640x360' xc:white -fill blue -draw "rectangle ${rec1_x1},${rec1_y1},${rec1_x2},${rec1_y2}" -fill red -draw "rectangle ${rec2_x1},${rec2_y1},${rec2_x2},${rec2_y2}" -font 'Noto-Mono' -fill black -draw "text 10,340 '${TEXT-aqua.flv} - Slide 000${C2}'" ./process/${C2}.png

		# Uses sox library to generate a sine wave (http://sox.sourceforge.net/)
		sox -n ./process/${C2}.wav synth 1 sine $SINE
		let C2=C2+1
	done

	# Combine all individual sine waves into a single audio file
	sox ./process/*.wav ./process/tone.wav

	# Uses ffmpeg to combine each PNG file into a single mp4 video (https://www.ffmpeg.org/)
	# FYI: The settings here are Youtube's recomendation for prepping video with ffmpeg for upload, so trust me that this is *probably* a best practice.
	ffmpeg -framerate 1 -i ./process/%d.png -vf fps=10 -s:v 1280x720 -c:v libx264 -profile:v high -crf 20 -pix_fmt yuv420p ./process/video.mp4

	# Finally combine the video and audio files together
	ffmpeg -i ./process/video.mp4 -i ./process/tone.wav -c:v copy -c:a aac -strict experimental ./videos/tmp${VIDEO}.mp4

	# Remove all the source files generated along the way
	rm ./process/*.*
	let C1=C1+1
done


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

	<title>Aucun résultat pour  Demo Developr Template Ajax-demo Img Demo Gallery Picture-1 Jpg</title>

	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<meta name="generator" content="WordPress 3.4.2" />
	<link rel="stylesheet" href="http://www.display-inline.fr/wp-content/themes/wicked/style.css" type="text/css" media="screen" />

	<link rel="alternate" type="application/rss+xml" title="RSS 2.0" href="http://feeds.feedburner.com/display-inline/blog" />
	<link rel="alternate" type="text/xml" title="RSS .92" href="http://www.display-inline.fr/feed/rss/" />
	<link rel="alternate" type="application/atom+xml" title="Atom 0.3" href="http://www.display-inline.fr/feed/atom/" />
	<link rel="pingback" href="http://www.display-inline.fr/xmlrpc.php" />

		<link rel='archives' title='mai 2010' href='http://www.display-inline.fr/2010/05/' />
	<link rel='archives' title='avril 2010' href='http://www.display-inline.fr/2010/04/' />
	<link rel='archives' title='mars 2010' href='http://www.display-inline.fr/2010/03/' />
	<link rel='archives' title='février 2010' href='http://www.display-inline.fr/2010/02/' />
	<link rel='archives' title='janvier 2010' href='http://www.display-inline.fr/2010/01/' />
	<link rel='archives' title='octobre 2009' href='http://www.display-inline.fr/2009/10/' />
	<link rel='archives' title='septembre 2009' href='http://www.display-inline.fr/2009/09/' />
	<link rel='stylesheet' id='sociablecss-css'  href='http://www.display-inline.fr/wp-content/plugins/sociable/css/sociable.css?ver=3.4.2' type='text/css' media='all' />
<link rel='stylesheet' id='envato-marketplace-items-css'  href='http://www.display-inline.fr/wp-content/plugins/envato-marketplace-items/marketplace.css?ver=1.0.3' type='text/css' media='all' />

<link rel="EditURI" type="application/rsd+xml" title="RSD" href="http://www.display-inline.fr/xmlrpc.php?rsd" />
<link rel="wlwmanifest" type="application/wlwmanifest+xml" href="http://www.display-inline.fr/wp-includes/wlwmanifest.xml" />
<meta name="generator" content="WordPress 3.4.2" />

	<link type="text/css" rel="stylesheet" href="http://www.display-inline.fr/wp-content/plugins/syntaxhighlighter-plus/syntaxhighlighter/styles/shCore.css"></link>
	<link type="text/css" rel="stylesheet" href="http://www.display-inline.fr/wp-content/plugins/syntaxhighlighter-plus/syntaxhighlighter/styles/shThemeDefault.css"></link>

Display:inline

            RSS

jQuery HoverAttribute : révélez-en plus sur vos liens

Utiliser @font-face pour vos icones

Le flexible box model en CSS3

Un générateur de dégradés CSS 3

Plupload : un puissant gestionnaire d’upload

Lire

À propos

RSS via Feedburner

                						<form method="get" class="searchform" action="http://www.display-inline.fr">
    					<input type="text" name="s" class="search_s" value="" />
                        <input type="submit" class="search_submit" value="Chercher !" title="Lancer la recherche" />
                    </form>

Sur ThemeForest

Derniers articles

jQuery HoverAttribute : révélez-en plus sur vos liens

Utiliser @font-face pour vos icones

Le flexible box model en CSS3

Un générateur de dégradés CSS 3

Plupload : un puissant gestionnaire d’upload

Le code d’inclusion vidéo ultime

FontFriend : éditer vos polices en temps réel

Les rubriques

Bookmarklets

Html/CSS

humeur

Javascript

php

php 5.3

Références

Ressources

Sites

Amis

Washaweb

                	Display:inline
                    Web, CSS, Php, Js & autres

Infos

Lire

À propos

Catégories

Bookmarklets (2)

Html/CSS (14)

humeur (5)

Javascript (3)

php (3)

php 5.3 (2)

Références (1)

Ressources (4)

Sites (1)


text:
import struct

varint_types = [
    'int32',
    'int64',
    'uint32',
    'uint64',
    'sint32',
    'sint64',
    'bool',
    'enum',
]
unsigned_varint_types = [
    'uint32',
    'uint64',
]
_64bit_types = ['fixed64', 'sfixed64', 'double']
delimited_types = ['string', 'bytes', 'embedded', 'packed']
_32bit_types = ['fixed32', 'sfixed32', 'float']
struct_formats = dict([
    ('fixed64', '<Q'),
    ('sfixed64', '<q'),
    ('double', '<d'),
    ('fixed32', '<I'),
    ('sfixed32', '<i'),
    ('float', '<f'),
])
joinstr = ''.join

def decode(proto, data):
    data = [ord(d) for d in data]
    return _decode(proto, data)

def _decode(proto, data):
    index = 0
    length = len(data)
    msg = dict()
    while index < length:
        # optimization: avoid function calls to decode_varint, decode_key
        item = 128
        key = 0
        left = 0
        while item & 128:
            item = data[index]
            index += 1
            value = (item & 127) << left
            key += value
            left += 7
        field = key >> 3
        wire = key & 7
        # end optimization
        if field not in proto:
            continue
        info = proto[field]
        _type = info['type']
        repeated = info['scope'] == 'repeated'
        name = info['name']
        if repeated and name not in msg:
            msg[name] = list()
        if wire == 0:
            # TODO support int32, int64, uint32, sint32, sint64
            # optimization: avoid function call to decode_varint
            item = 128
            num = 0
            left = 0
            while item & 128:
                item = data[index]
                index += 1
                value = (item & 127) << left
                num += value
                left += 7
            # end optimization
            if _type == 'bool':
                num = bool(num)
            if repeated:
                msg[name].append(num)
                continue
            msg[name] = num
            continue
        if wire == 1:
            fmt = struct_formats[_type]
            # optimization: avoid function call to decode_struct
            last = index
            index += 8
            values = [chr(i) for i in data[last:index]]
            values = joinstr(values)
            num = struct.unpack(fmt, values)
            # end optimization
            if repeated:
                msg[name].append(num[0])
                continue
            msg[name] = num[0]
            continue
        if wire == 2:
            # TODO support bytes and packed repeated fields
            # optimization: avoid function call to decode_delimited
            item = 128
            _length = 0
            left = 0
            while item & 128:
                item = data[index]
                index += 1
                value = (item & 127) << left
                _length += value
                left += 7
            last = index
            index += _length
            item = data[last:index]
            # end optimization
            if _type == 'embedded':
                item = _decode(info['message'], item)
                if repeated:
                    msg[name].append(item)
                    continue
                msg[name] = item
            if _type == 'string':
                item = joinstr([chr(i) for i in item])
                # TODO: need to think through unicode more completely
                item = item.decode('utf8')
                if repeated:
                    msg[name].append(item)
                    continue
                msg[name] = item
            continue
        if wire == 5:
            fmt = struct_formats[_type]
            # optimization: avoid function call to decode_struct
            last = index
            index += 4
            values = [chr(i) for i in data[last:index]]
            values = ''.join(values)
            num = struct.unpack(fmt, values)
            # end optimization
            if repeated:
                msg[name].append(num[0])
                continue
            msg[name] = num[0]
            continue
        raise ValueError(
            'invalid wire type: {wire}'.format(wire=wire)
        )
    return msg

def encode(proto, msg):
    data = _encode(proto, msg)
    data = [chr(d) for d in data]
    return ''.join(data)

def _encode(proto, msg):
    data = []
    for k, values in msg.items():
        info = proto[k]
        field = info['field']
        _type = info['type']
        repeated = info['scope'] == 'repeated'
        if _type in varint_types:
            if repeated:
                for v in values:
                    if _type in unsigned_varint_types and v < 0:
                        raise ValueError(
                            '{_type} value cannot be negative: {v}'.format(
                                _type=_type,
                                v=v,
                            )
                        )
                    # TODO support int32, int64, uint32, sint32, sint64
                    # optimization: avoid function calls to encode_key
                    key = (field << 3) | 0
                    # end optimization
                    # optimization: avoid function calls to encode_varint
                    _next = 1
                    _value = key
                    key = []
                    while _next:
                        _next = _value >> 7
                        shift = 128 if _next else 0
                        part = (_value & 127) | shift
                        key.append(part)
                        _value = _next
                    # end optimization
                    if _type == 'bool':
                        v = int(v)
                    # optimization: avoid function calls to encode_varint
                    _next = 1
                    _value = v
                    values = []
                    while _next:
                        _next = _value >> 7
                        shift = 128 if _next else 0
                        part = (_value & 127) | shift
                        values.append(part)
                        _value = _next
                    data += key + values
                continue
            v = values
            if _type in unsigned_varint_types and v < 0:
                raise ValueError(
                    '{_type} value cannot be negative: {v}'.format(
                        _type=_type,
                        v=v,
                    )
                )
            # TODO support int32, int64, uint32, sint32, sint64
            # optimization: avoid function calls to encode_key
            key = (field << 3) | 0
            # end optimization
            # optimization: avoid function calls to encode_varint
            _next = 1
            _value = key
            key = []
            while _next:
                _next = _value >> 7
                shift = 128 if _next else 0
                part = (_value & 127) | shift
                key.append(part)
                _value = _next
            # end optimization
            if _type == 'bool':
                v = int(v)
            # optimization: avoid function calls to encode_varint
            _next = 1
            _value = v
            values = []
            while _next:
                _next = _value >> 7
                shift = 128 if _next else 0
                part = (_value & 127) | shift
                values.append(part)
                _value = _next
            data += key + values
            continue
        if _type in _64bit_types:
            if repeated:
                for v in values:
                    # optimization: avoid function calls to encode_key
                    key = (field << 3) | 1
                    # end optimization
                    # optimization: avoid function calls to encode_varint
                    _next = 1
                    _value = key
                    key = []
                    while _next:
                        _next = _value >> 7
                        shift = 128 if _next else 0
                        part = (_value & 127) | shift
                        key.append(part)
                        _value = _next
                    # end optimization
                    fmt = struct_formats[_type]
                    # optimization: avoid function call to encode_struct
                    value = [ord(b) for b in struct.pack(fmt, v)]
                    # end optimization
                    data += key + value
                continue
            v = values
            # optimization: avoid function calls to encode_key
            key = (field << 3) | 1
            # end optimization
            # optimization: avoid function calls to encode_varint
            _next = 1
            _value = key
            key = []
            while _next:
                _next = _value >> 7
                shift = 128 if _next else 0
                part = (_value & 127) | shift
                key.append(part)
                _value = _next
            # end optimization
            fmt = struct_formats[_type]
            # optimization: avoid function call to encode_struct
            value = [ord(b) for b in struct.pack(fmt, v)]
            # end optimization
            data += key + value
            continue
        if _type in delimited_types:
            if repeated:
                for v in values:
                    # TODO support bytes and packed repeated fields
                    # optimization: avoid function calls to encode_key
                    key = (field << 3) | 2
                    # end optimization
                    # optimization: avoid function calls to encode_varint
                    _next = 1
                    _value = key
                    key = []
                    while _next:
                        _next = _value >> 7
                        shift = 128 if _next else 0
                        part = (_value & 127) | shift
                        key.append(part)
                        _value = _next
                    # end optimization
                    if _type == 'embedded':
                        value = _encode(info['message'], v)
                        length = len(value)
                        # optimization: avoid function calls to encode_varint
                        _next = 1
                        _value = length
                        length = []
                        while _next:
                            _next = _value >> 7
                            shift = 128 if _next else 0
                            part = (_value & 127) | shift
                            length.append(part)
                            _value = _next
                        # end optimization
                        data += key + length + value
                    if _type == 'string':
                        # optimization: avoid function calls to
                        # encode_delimited
                        length = len(v)
                        # optimization: avoid function calls to encode_varint
                        _next = 1
                        _value = length
                        length = []
                        while _next:
                            _next = _value >> 7
                            shift = 128 if _next else 0
                            part = (_value & 127) | shift
                            length.append(part)
                            _value = _next
                        # end optimization
                        value = [ord(i) for i in v]
                        data += key + length + value
                        # end optimization
                continue

            # TODO: need to handle unicode more completely
            if isinstance(values, unicode):
                values = values.encode('utf8')

            v = values
            # TODO support bytes and packed repeated fields
            # optimization: avoid function calls to encode_key
            key = (field << 3) | 2
            # end optimization
            # optimization: avoid function calls to encode_varint
            _next = 1
            _value = key
            key = []
            while _next:
                _next = _value >> 7
                shift = 128 if _next else 0
                part = (_value & 127) | shift
                key.append(part)
                _value = _next
            # end optimization
            if _type == 'embedded':
                value = _encode(info['message'], v)
                length = len(value)
                # optimization: avoid function calls to encode_varint
                _next = 1
                _value = length
                length = []
                while _next:
                    _next = _value >> 7
                    shift = 128 if _next else 0
                    part = (_value & 127) | shift
                    length.append(part)
                    _value = _next
                # end optimization
                data += key + length + value
            if _type == 'string':
                # optimization: avoid function calls to encode_delimited
                length = len(v)
                # optimization: avoid function calls to encode_varint
                _next = 1
                _value = length
                length = []
                while _next:
                    _next = _value >> 7
                    shift = 128 if _next else 0
                    part = (_value & 127) | shift
                    length.append(part)
                    _value = _next
                # end optimization
                value = [ord(i) for i in v]
                data += key + length + value
                # end optimization
            continue
        if _type in _32bit_types:
            if repeated:
                for v in values:
                    # optimization: avoid function calls to encode_key
                    key = (field << 3) | 5
                    # end optimization
                    # optimization: avoid function calls to encode_varint
                    _next = 1
                    _value = key
                    key = []
                    while _next:
                        _next = _value >> 7
                        shift = 128 if _next else 0
                        part = (_value & 127) | shift
                        key.append(part)
                        _value = _next
                    # end optimization
                    fmt = struct_formats[_type]
                    # optimization: avoid function call to encode_struct
                    value = [ord(b) for b in struct.pack(fmt, v)]
                    # end optimization
                    data += key + value
                continue
            v = values
            # optimization: avoid function calls to encode_key
            key = (field << 3) | 5
            # end optimization
            # optimization: avoid function calls to encode_varint
            _next = 1
            _value = key
            key = []
            while _next:
                _next = _value >> 7
                shift = 128 if _next else 0
                part = (_value & 127) | shift
                key.append(part)
                _value = _next
            # end optimization
            fmt = struct_formats[_type]
            # optimization: avoid function call to encode_struct
            value = [ord(b) for b in struct.pack(fmt, v)]
            # end optimization
            data += key + value
            continue
    return data


text:
package server

import (
	"google.golang.org/grpc"
	sdkgrpc "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/apikeys/beta/apikeys_beta_go_proto"
)

// RegisterServers registers each resource with the gRPC server.
func RegisterServers(s *grpc.Server) {
	sdkgrpc.RegisterApikeysBetaKeyServiceServer(s, &KeyServer{})
}


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\core\record\Node */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'title')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'content')->textarea(['rows' => 6]) ?>

    <?= $form->field($model, 'excerpt')->textarea(['rows' => 6]) ?>

    <?= $form->field($model, 'menu_order')->textInput() ?>

    <?= $form->field($model, 'status')->textInput() ?>

        <?= Html::submitButton($model->isNewRecord ? Yii::t('juva', 'Create') : Yii::t('juva', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
namespace media {

AsyncDataSourceFactoryBase::AsyncDataSourceFactoryBase() {}

AsyncDataSourceFactoryBase::~AsyncDataSourceFactoryBase() {
  base::AutoLock auto_lock(lock_);
  STLDeleteElements(&outstanding_requests_);
}

void AsyncDataSourceFactoryBase::Build(const std::string& url,
                                       BuildCallback* callback) {
  DCHECK(callback);
  BuildRequest* request = NULL;
  {
    base::AutoLock auto_lock(lock_);

    if (url.empty()) {
      RunAndDestroyCallback(PIPELINE_ERROR_URL_NOT_FOUND, callback);
      return;
    }

    if (!AllowRequests()) {
      RunAndDestroyCallback(DATASOURCE_ERROR_URL_NOT_SUPPORTED, callback);
      return;
    }

    request = CreateRequest(url, callback);

    if (!request) {
      RunAndDestroyCallback(DATASOURCE_ERROR_URL_NOT_SUPPORTED, callback);
      return;
    }

    outstanding_requests_.insert(request);
  }

  request->Start(NewCallback(this,
                             &AsyncDataSourceFactoryBase::BuildRequestDone));
}

void AsyncDataSourceFactoryBase::RunAndDestroyCallback(
    PipelineStatus error,
    BuildCallback* callback) const {
  DCHECK_NE(error, PIPELINE_OK);
  DCHECK(callback);

  callback->Run(error, static_cast<DataSource*>(NULL));
  delete callback;
}

void AsyncDataSourceFactoryBase::BuildRequestDone(BuildRequest* request) {
  base::AutoLock auto_lock(lock_);
  outstanding_requests_.erase(request);
  delete request;
}

AsyncDataSourceFactoryBase::BuildRequest::BuildRequest(const std::string& url,
                                                       BuildCallback* callback)
    : url_(url),
      callback_(callback) {
}

AsyncDataSourceFactoryBase::BuildRequest::~BuildRequest() {}

void AsyncDataSourceFactoryBase::BuildRequest::Start(
    RequestDoneCallback* done_callback) {
  DCHECK(done_callback);
  DCHECK(!done_callback_.get());

  done_callback_.reset(done_callback);
  DoStart();
  // Don't do anything after this line since the object could
  // have been deleted at this point if the request was completed
  // inside the call.
}

void AsyncDataSourceFactoryBase::BuildRequest::RequestComplete(
    PipelineStatus status,
    DataSource* data_source) {
  DCHECK(callback_.get());
  DCHECK(done_callback_.get());

  // Transfer ownership to local variables just in case the
  // request object gets deleted by one of the callbacks.
  scoped_ptr<RequestDoneCallback> done_callback(done_callback_.release());
  scoped_ptr<BuildCallback> callback(callback_.release());

  // Notify factory that this request has completed. We do this before
  // calling |callback| so the factory doesn't consider this request
  // pending if |callback| happens to destroy the factory.
  //
  // NOTE: This BuildRequest object is destroyed inside this callback so
  //       no modifications should be made to this object after this call.
  done_callback->Run(this);

  callback->Run(status, data_source);
}

const std::string& AsyncDataSourceFactoryBase::BuildRequest::url() const {
  return url_;
}

}  // namespace media


text:
package com.jmelzer.myttr.model;

import com.jmelzer.myttr.Club;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.Date;

import static org.apache.commons.lang3.StringUtils.isNoneEmpty;

/**
 * Created by J. Melzer on 28.09.2017.
 * Object for storing infos about player to search fpr mytt
 */

public class SearchPlayer implements Serializable, Favorite {
    private static final long serialVersionUID = 3253568223402780761L;
    String lastname;
    String firstname;
    Club club;
    String gender;
    int yearFrom = -1;
    int yearTo = -1;
    int ttrFrom = -1;
    int ttrTo = -1;
    //name of the search for persistence
    private String name;
    //url of the search for persistence
    private String url;
    private Date changedAt;
    boolean actual = true;

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public Club getClub() {
        return club;
    }

    public void setClub(Club club) {
        this.club = club;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public int getYearFrom() {
        return yearFrom;
    }

    public void setYearFrom(int yearFrom) {
        this.yearFrom = yearFrom;
    }

    public int getYearTo() {
        return yearTo;
    }

    public void setYearTo(int yearTo) {
        this.yearTo = yearTo;
    }

    public int getTtrFrom() {
        return ttrFrom;
    }

    public void setTtrFrom(int ttrFrom) {
        this.ttrFrom = ttrFrom;
    }

    public int getTtrTo() {
        return ttrTo;
    }

    public void setTtrTo(int ttrTo) {
        this.ttrTo = ttrTo;
    }

    public String getClubName() {
        if (club != null)
            return club.getName();
        return null;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public void setName(String name) {
        this.name = name;
    }

    @Override
    public void setUrl(String url) {
        this.url = url;
    }

    @Override
    public void setChangedAt(Date d) {
        this.changedAt = d;
    }

    @Override
    public String getUrl() {
        return url;
    }

    @Override
    public String typeForMenu() {
        return "Suche";
    }

    public String createName() {
        String name = "";
        if (isNoneEmpty(firstname, lastname)) {
            name = add(name, firstname);
            name = add(name, lastname);
        }
        if (club != null) {
            name = add(name, club.getName());
        }

        if (ttrFrom > 0 && ttrTo > 0) {
            name += " (" + ttrFrom + "-" + ttrTo + ")";
        } else {
            if (ttrFrom > 0) {
                name += " (" + ttrFrom + "-∞)";
            }
            if (ttrTo > 0) {
                name += " (0-" + ttrTo + ")";
            }
        }
        if (name.isEmpty()) {
            return "Alle Spieler";
        }
        return name;
    }

    public boolean isActual() {
        return actual;
    }

    public void setActual(boolean actual) {
        this.actual = actual;
    }

    public String convertToJson() throws JSONException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("firstname", firstname);
        jsonObject.put("lastname", lastname);
        if (club != null) {
            jsonObject.put("clubname", club.getName());
            jsonObject.put("clubid", club.getId());
            jsonObject.put("clubverband", club.getVerband());
        } else {
            jsonObject.put("clubname", "");
            jsonObject.put("clubid", "");
            jsonObject.put("clubverband", "");
        }
        jsonObject.put("ttrFrom", ttrFrom);
        jsonObject.put("ttrTo", ttrTo);
        return jsonObject.toString();
    }

    public static SearchPlayer convertFromJson(String jsonData) throws JSONException {
        JSONObject jsonObject = new JSONObject(jsonData);
        SearchPlayer sp = new SearchPlayer();
        sp.setFirstname(jsonObject.getString("firstname"));
        sp.setLastname(jsonObject.getString("lastname"));

        if (StringUtils.isNoneEmpty(jsonObject.getString("clubname"),
                jsonObject.getString("clubid"),
                jsonObject.getString("clubverband"))) {

            Club c = new Club(jsonObject.getString("clubname"),
                    jsonObject.getString("clubid"),
                    jsonObject.getString("clubverband"));
            sp.setClub(c);
        }
        sp.setTtrFrom(jsonObject.getInt("ttrFrom"));
        sp.setTtrTo(jsonObject.getInt("ttrTo"));
        return sp;
    }

    private String add(String str, String name) {
        if (str.isEmpty())
            return name;
        else
            return str + "-" + name;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;

        if (o == null || getClass() != o.getClass()) return false;

        SearchPlayer that = (SearchPlayer) o;

        return new EqualsBuilder()
                .append(yearFrom, that.yearFrom)
                .append(yearTo, that.yearTo)
                .append(ttrFrom, that.ttrFrom)
                .append(ttrTo, that.ttrTo)
                .append(lastname, that.lastname)
                .append(firstname, that.firstname)
                .append(club.getName(), that.club.getName())
                .append(gender, that.gender)
                .isEquals();
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder(17, 37)
                .append(lastname)
                .append(firstname)
                .append(club)
                .append(gender)
                .append(yearFrom)
                .append(yearTo)
                .append(ttrFrom)
                .append(ttrTo)
                .toHashCode();
    }
}


text:
using Microsoft.Azure.Commands.Compute.Automation.Models;
using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;
using Microsoft.Azure.Management.Compute.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;

namespace Microsoft.Azure.Commands.Compute.Automation
{
    [Cmdlet(VerbsCommon.New, ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "ImageConfig", SupportsShouldProcess = true)]
    [OutputType(typeof(PSImage))]
    public partial class NewAzureRmImageConfigCommand : Microsoft.Azure.Commands.ResourceManager.Common.AzureRMCmdlet
    {
        [Parameter(
            Mandatory = false,
            Position = 0,
            ValueFromPipelineByPropertyName = true)]
        [LocationCompleter("Microsoft.Compute/images")]
        public string Location { get; set; }

        [Parameter(
            Mandatory = false,
            Position = 1,
            ValueFromPipelineByPropertyName = true)]
        public Hashtable Tag { get; set; }

        [Parameter(
            Mandatory = false,
            Position = 2,
            ValueFromPipelineByPropertyName = true)]
        public string SourceVirtualMachineId { get; set; }

        [Parameter(
            Mandatory = false,
            Position = 3,
            ValueFromPipelineByPropertyName = true)]
        public ImageOSDisk OsDisk { get; set; }

        [Parameter(
            Mandatory = false,
            ValueFromPipelineByPropertyName = true)]
        public ImageDataDisk[] DataDisk { get; set; }

        [Parameter(
            Mandatory = false)]
        public SwitchParameter ZoneResilient { get; set; }

        protected override void ProcessRecord()
        {
            if (ShouldProcess("Image", "New"))
            {
                Run();
            }
        }

        private void Run()
        {
            // SourceVirtualMachine
            Microsoft.Azure.Management.Compute.Models.SubResource vSourceVirtualMachine = null;

            // StorageProfile
            Microsoft.Azure.Management.Compute.Models.ImageStorageProfile vStorageProfile = null;

            if (this.MyInvocation.BoundParameters.ContainsKey("SourceVirtualMachineId"))
            {
                if (vSourceVirtualMachine == null)
                {
                    vSourceVirtualMachine = new Microsoft.Azure.Management.Compute.Models.SubResource();
                }
                vSourceVirtualMachine.Id = this.SourceVirtualMachineId;
            }

            if (this.MyInvocation.BoundParameters.ContainsKey("OsDisk"))
            {
                if (vStorageProfile == null)
                {
                    vStorageProfile = new Microsoft.Azure.Management.Compute.Models.ImageStorageProfile();
                }
                vStorageProfile.OsDisk = this.OsDisk;
            }

            if (this.MyInvocation.BoundParameters.ContainsKey("DataDisk"))
            {
                if (vStorageProfile == null)
                {
                    vStorageProfile = new Microsoft.Azure.Management.Compute.Models.ImageStorageProfile();
                }
                vStorageProfile.DataDisks = this.DataDisk;
            }

            if (vStorageProfile == null)
            {
                vStorageProfile = new Microsoft.Azure.Management.Compute.Models.ImageStorageProfile();
            }
            vStorageProfile.ZoneResilient = this.ZoneResilient.IsPresent;

            var vImage = new PSImage
            {
                Location = this.MyInvocation.BoundParameters.ContainsKey("Location") ? this.Location : null,
                Tags = this.MyInvocation.BoundParameters.ContainsKey("Tag") ? this.Tag.Cast<DictionaryEntry>().ToDictionary(ht => (string)ht.Key, ht => (string)ht.Value) : null,
                SourceVirtualMachine = vSourceVirtualMachine,
                StorageProfile = vStorageProfile,
            };

            WriteObject(vImage);
        }
    }
}


text:
======
Tools
======

`doit.tools` includes some commonly used code. This are not used by the `doit`
core, you can see it as a "standard library".
The functions/class used with `uptodate` were already introduced in the previous
section.

create_folder (action)
-------------------------

Creates a folder if it does not exist yet.

.. literalinclude:: tutorial/folder.py

title_with_actions (title)
----------------------------

Return task name task actions from a task. This function can be used as 'title' attribute of a task dictionary to provide more detailed information of the action being executed.

.. literalinclude:: tutorial/titlewithactions.py

InteractiveAction (action)
-----------------------------

An IteractiveAction is like a CmdAction but with the following differences:

  * the output is never captured
  * it is always successful (return code is not used)
  * "swallow" KeyboardInterrupt

This is useful for executing long running process like a web-server.

.. literalinclude:: tutorial/interactiveaction.py

PythonInteractiveAction (action)
----------------------------------

Similar to IteractiveAction but for PythonAction.

set_trace
-----------

`doit` by default redirects stdout and stderr. Because of this when you try to use the python debugger with ``pdb.set_trace``, it does not work propoerly. To make sure you get a propper PDB shell you should use doit.tools.set_trace instead of ``pdb.set_trace``.

.. literalinclude:: tutorial/settrace.py


text:
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using Alachisoft.NCache.Common.Net;
using Alachisoft.NCache.Serialization.Formatters;
#if NETCORE
using System.Runtime.InteropServices;
#endif

namespace Alachisoft.NGroups.Protocols
{
    internal class MPingReceiver : IThreadRunnable
    {
        private TCPPING enclosingInstance;
        private System.Net.Sockets.Socket mcast_recv_sock;
        internal int ip_ttl = 32;
        private Address mcast_addr;
        int buff_size = 64000;
        bool discard_incompatible_packets = true;
        internal ThreadClass mcast_receiver = null;

        public MPingReceiver(TCPPING enclosingInstance)
        {
            this.enclosingInstance = enclosingInstance;
        }
        public TCPPING Enclosing_Instance
        {
            get { return enclosingInstance; }
        }

        private void createSockets()
        {
            IPAddress tmp_addr = null;
            tmp_addr = Address.Resolve(Enclosing_Instance.discovery_addr);
            mcast_addr = new Address(tmp_addr, Enclosing_Instance.discovery_port);

            try
            {
                IPEndPoint recvEndPoint = new IPEndPoint(IPAddress.Any, mcast_addr.Port);
                mcast_recv_sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                mcast_recv_sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
                mcast_recv_sock.Bind(recvEndPoint);
                mcast_recv_sock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(mcast_addr.IpAddress, IPAddress.Any));
            }
            catch (Exception ex)
            {
                throw ex;
            }
            setBufferSizes();
        }
        private void setBufferSizes()
        {
            if (mcast_recv_sock != null)
            {
                try
                {
                    mcast_recv_sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, buff_size);
                }
                catch (System.Exception ex)
                {
                    enclosingInstance.Stack.NCacheLog.Warn("failed setting mcast_send_buf_size in mcast_recv_sock: " + ex);
                }

                try
                {
                    mcast_recv_sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, buff_size);
                }
                catch (System.Exception ex)
                {
                    enclosingInstance.Stack.NCacheLog.Warn("failed setting mcast_recv_buf_size in mcast_recv_sock: " + ex);
                }
            }
        }

#region IThreadRunnable Members

        public void Run()
        {
            int len;
            byte[] packet = new byte[buff_size];
            EndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);

            while (mcast_receiver != null && mcast_recv_sock != null)
            {
                try
                {
                    len = mcast_recv_sock.ReceiveFrom(packet, ref remoteIpEndPoint);

                    if (len == 1 && packet[0] == 0)
                    {
                        if (enclosingInstance.Stack.NCacheLog.IsInfoEnabled) enclosingInstance.Stack.NCacheLog.Info("UDP.Run()", "received dummy packet");
                        continue;
                    }

                    if (len > packet.Length)
                    {
                        enclosingInstance.Stack.NCacheLog.Error("UDP.Run()", "size of the received packet (" + len + ") is bigger than " + "allocated buffer (" + packet.Length + "): will not be able to handle packet. " + "Use the FRAG protocol and make its frag_size lower than " + packet.Length);
                    }

                    if (Version.CompareTo(packet) == false)
                    {
                        if (discard_incompatible_packets)
                            continue;
                    }

                    handleIncomingPacket(packet, len);
                }
                catch (SocketException sock_ex)
                {
                    enclosingInstance.Stack.NCacheLog.Error("MPingReceiver.Run()", "multicast socket is closed, exception=" + sock_ex);
                    break;
                }
                catch (IOException ex)
                {
                    enclosingInstance.Stack.NCacheLog.Error("MPingReceiver.Run()", "exception=" + ex);
                    // thread was interrupted
                    ; // go back to top of loop, where we will terminate loop
                }
                catch (System.Exception ex)
                {
                    enclosingInstance.Stack.NCacheLog.Error("MPingReceiver.Run()", "exception=" + ex + ", stack trace=" + ex.StackTrace);
                    Util.Util.sleep(200); // so we don't get into 100% cpu spinning (should NEVER happen !)
                }
            }
        }

#endregion
        internal bool start()
        {
            try
            {
                createSockets();
                if (mcast_receiver == null)
                {
                    mcast_receiver = new ThreadClass(new System.Threading.ThreadStart(this.Run), "MPingReceiver thread");
                    mcast_receiver.IsBackground = true;
                    mcast_receiver.Start();
                }
            }
            catch (Exception e)
            {
                enclosingInstance.Stack.NCacheLog.Error("MPingReceiver.start()", e.ToString());
                return (false);
            }
            return (true);
        }

        internal void stop()
        {
            mcast_receiver = null;
#if NETCORE
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                mcast_recv_sock.Shutdown(SocketShutdown.Both);
            }
#endif
            mcast_recv_sock.Close();
            mcast_recv_sock = null;
        }
        private void handleIncomingPacket(byte[] data, int dataLen)
        {
            MemoryStream inp_stream;
            Message msg = null;

            try
            {
                inp_stream = new MemoryStream(data, Version.Length, dataLen - Version.Length);
                msg = CompactBinaryFormatter.Deserialize(inp_stream, null) as Message;
                if (msg != null)
                    this.Enclosing_Instance.up(new Event(Event.MSG, (object)msg));
            }
            catch (System.Exception e)
            {
                enclosingInstance.Stack.NCacheLog.Error("MpingReceiver.handleIncomingPacket()", "exception=" + e.ToString() + "\n");
            }
        }
    }
}


text:
// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com)
// This file is part of the "Nazara Engine - Physics2D module"
// For conditions of distribution and use, see copyright notice in Config.hpp

#include <Nazara/Physics2D/Collider2D.hpp>
#include <Nazara/Math/Quaternion.hpp>
#include <Nazara/Physics2D/PhysWorld2D.hpp>
#include <Nazara/Physics2D/RigidBody2D.hpp>
#include <Nazara/Utils/CallOnExit.hpp>
#include <Nazara/Utils/StackArray.hpp>
#include <chipmunk/chipmunk.h>
#include <chipmunk/chipmunk_structs.h>
#include <array>
#include <Nazara/Physics2D/Debug.hpp>

namespace Nz
{
	namespace
	{
		constexpr cpSpaceDebugColor s_chipmunkWhite = { 1.f, 1.f, 1.f, 1.f };

		Vector2f FromChipmunk(const cpVect& v)
		{
			return Vector2f(float(v.x), float(v.y));
		}
	}

	Collider2D::~Collider2D() = default;

	void Collider2D::ForEachPolygon(const std::function<void(const Vector2f* vertices, std::size_t vertexCount)>& callback) const
	{
		// Currently, the only way to get only the polygons of a shape is to create a temporary cpSpace containing only this shape
		// A better way to do this would be to reimplement this function in every subclass type in the very same way chipmunk does

		cpSpace* space = cpSpaceNew();
		if (!space)
			throw std::runtime_error("failed to create chipmunk space");

		CallOnExit spaceRRID([&] { cpSpaceFree(space); });

		cpBody* body = cpSpaceGetStaticBody(space);

		std::vector<cpShape*> shapes;
		CreateShapes(body, &shapes);
		CallOnExit shapeRRID([&]
		{
			for (cpShape* shape : shapes)
				cpShapeDestroy(shape);
		});

		for (cpShape* shape : shapes)
			cpSpaceAddShape(space, shape);

		using CallbackType = std::decay_t<decltype(callback)>;

		cpSpaceDebugDrawOptions drawOptions;
		drawOptions.collisionPointColor = s_chipmunkWhite;
		drawOptions.constraintColor = s_chipmunkWhite;
		drawOptions.shapeOutlineColor = s_chipmunkWhite;
		drawOptions.data = const_cast<void*>(static_cast<const void*>(&callback));
		drawOptions.flags = CP_SPACE_DEBUG_DRAW_SHAPES;

		// Callback trampoline
		drawOptions.colorForShape = [](cpShape* /*shape*/, cpDataPointer /*userdata*/) { return s_chipmunkWhite; };
		drawOptions.drawCircle = [](cpVect pos, cpFloat /*angle*/, cpFloat radius, cpSpaceDebugColor /*outlineColor*/, cpSpaceDebugColor /*fillColor*/, cpDataPointer userdata)
		{
			const auto& callback = *static_cast<const CallbackType*>(userdata);

			constexpr std::size_t circleVerticesCount = 20;

			std::array<Vector2f, circleVerticesCount> vertices;

			Vector2f origin = FromChipmunk(pos);
			float r = SafeCast<float>(radius);

			RadianAnglef angleBetweenVertices = 2.f * Pi<float> / vertices.size();
			for (std::size_t i = 0; i < vertices.size(); ++i)
			{
				RadianAnglef angle = float(i) * angleBetweenVertices;
				std::pair<float, float> sincos = angle.GetSinCos();

				vertices[i] = origin + Vector2f(r * sincos.first, r * sincos.second);
			}

			callback(vertices.data(), vertices.size());
		};

		drawOptions.drawDot = [](cpFloat /*size*/, cpVect /*pos*/, cpSpaceDebugColor /*color*/, cpDataPointer /*userdata*/) {}; //< Dummy

		drawOptions.drawFatSegment = [](cpVect a, cpVect b, cpFloat radius, cpSpaceDebugColor /*outlineColor*/, cpSpaceDebugColor /*fillColor*/, cpDataPointer userdata)
		{
			const auto& callback = *static_cast<const CallbackType*>(userdata);

			static std::pair<float, float> sincos = DegreeAnglef(90.f).GetSinCos();

			Vector2f from = FromChipmunk(a);
			Vector2f to = FromChipmunk(b);

			Vector2f normal = Vector2f::Normalize(to - from);
			Vector2f thicknessNormal(sincos.second * normal.x - sincos.first * normal.y,
			                         sincos.first * normal.x + sincos.second * normal.y);

			float thickness = SafeCast<float>(radius);

			std::array<Vector2f, 4> vertices;
			vertices[0] = from + thickness * thicknessNormal;
			vertices[1] = from - thickness * thicknessNormal;
			vertices[2] = to - thickness * thicknessNormal;
			vertices[3] = to + thickness * thicknessNormal;

			callback(vertices.data(), vertices.size());
		};

		drawOptions.drawPolygon = [](int vertexCount, const cpVect* vertices, cpFloat /*radius*/, cpSpaceDebugColor /*outlineColor*/, cpSpaceDebugColor /*fillColor*/, cpDataPointer userdata)
		{
			const auto& callback = *static_cast<const CallbackType*>(userdata);

			StackArray<Vector2f> nVertices = NazaraStackArray(Vector2f, vertexCount);
			for (int i = 0; i < vertexCount; ++i)
				nVertices[i].Set(float(vertices[i].x), float(vertices[i].y));

			callback(nVertices.data(), nVertices.size());
		};

		drawOptions.drawSegment = [](cpVect a, cpVect b, cpSpaceDebugColor /*fillColor*/, cpDataPointer userdata)
		{
			const auto& callback = *static_cast<const CallbackType*>(userdata);

			std::array<Vector2f, 2> vertices = { FromChipmunk(a), FromChipmunk(b) };
			callback(vertices.data(), vertices.size());
		};

		cpSpaceDebugDraw(space, &drawOptions);
	}

	std::size_t Collider2D::GenerateShapes(cpBody* body, std::vector<cpShape*>* shapes) const
	{
		std::size_t shapeCount = CreateShapes(body, shapes);

		cpShapeFilter filter = cpShapeFilterNew(m_collisionGroup, m_categoryMask, m_collisionMask);
		for (std::size_t i = shapes->size() - shapeCount; i < shapes->size(); ++i)
		{
			cpShape* shape = (*shapes)[i];

			cpShapeSetCollisionType(shape, m_collisionId);
			cpShapeSetElasticity(shape, cpFloat(m_elasticity));
			cpShapeSetFilter(shape, filter);
			cpShapeSetFriction(shape, cpFloat(m_friction));
			cpShapeSetSensor(shape, (m_trigger) ? cpTrue : cpFalse);
			cpShapeSetSurfaceVelocity(shape, cpv(cpFloat(m_surfaceVelocity.x), cpFloat(m_surfaceVelocity.y)));
		}

		return shapeCount;
	}

	/******************************** BoxCollider2D *********************************/

	BoxCollider2D::BoxCollider2D(const Vector2f& size, float radius) :
	BoxCollider2D(Rectf(-size.x / 2.f, -size.y / 2.f, size.x, size.y), radius)
	{
	}

	BoxCollider2D::BoxCollider2D(const Rectf& rect, float radius) :
	m_rect(rect),
	m_radius(radius)
	{
	}

	Vector2f BoxCollider2D::ComputeCenterOfMass() const
	{
		return m_rect.GetCenter();
	}

	float BoxCollider2D::ComputeMomentOfInertia(float mass) const
	{
		return SafeCast<float>(cpMomentForBox2(mass, cpBBNew(m_rect.x, m_rect.y, m_rect.x + m_rect.width, m_rect.y + m_rect.height)));
	}

	ColliderType2D BoxCollider2D::GetType() const
	{
		return ColliderType2D::Box;
	}

	std::size_t BoxCollider2D::CreateShapes(cpBody* body, std::vector<cpShape*>* shapes) const
	{
		shapes->push_back(cpBoxShapeNew2(body, cpBBNew(m_rect.x, m_rect.y, m_rect.x + m_rect.width, m_rect.y + m_rect.height), m_radius));
		return 1;
	}

	/******************************** CircleCollider2D *********************************/

	CircleCollider2D::CircleCollider2D(float radius, const Vector2f& offset) :
	m_offset(offset),
	m_radius(radius)
	{
	}

	Vector2f CircleCollider2D::ComputeCenterOfMass() const
	{
		return m_offset;
	}

	float CircleCollider2D::ComputeMomentOfInertia(float mass) const
	{
		return SafeCast<float>(cpMomentForCircle(mass, 0.f, m_radius, cpv(m_offset.x, m_offset.y)));
	}

	ColliderType2D CircleCollider2D::GetType() const
	{
		return ColliderType2D::Circle;
	}

	std::size_t CircleCollider2D::CreateShapes(cpBody* body, std::vector<cpShape*>* shapes) const
	{
		shapes->push_back(cpCircleShapeNew(body, m_radius, cpv(m_offset.x, m_offset.y)));
		return 1;
	}

	/******************************** CompoundCollider2D *********************************/

	CompoundCollider2D::CompoundCollider2D(std::vector<std::shared_ptr<Collider2D>> geoms) :
	m_geoms(std::move(geoms)),
	m_doesOverrideCollisionProperties(true)
	{
	}

	Vector2f CompoundCollider2D::ComputeCenterOfMass() const
	{
		Vector2f centerOfMass = Vector2f::Zero();
		for (const auto& geom : m_geoms)
			centerOfMass += geom->ComputeCenterOfMass();

		return centerOfMass / float(m_geoms.size());
	}

	float CompoundCollider2D::ComputeMomentOfInertia(float mass) const
	{
		///TODO: Correctly compute moment using parallel axis theorem:
		/// https://chipmunk-physics.net/forum/viewtopic.php?t=1056
		float momentOfInertia = 0.f;
		for (const auto& geom : m_geoms)
			momentOfInertia += geom->ComputeMomentOfInertia(mass); //< Eeeer

		return momentOfInertia;
	}

	ColliderType2D CompoundCollider2D::GetType() const
	{
		return ColliderType2D::Compound;
	}

	std::size_t CompoundCollider2D::CreateShapes(cpBody* body, std::vector<cpShape*>* shapes) const
	{
		// Since C++ does not allow protected call from other objects, we have to be a friend of Collider2D, yay

		std::size_t shapeCount = 0;
		for (const auto& geom : m_geoms)
			shapeCount += geom->CreateShapes(body, shapes);

		return shapeCount;
	}

	std::size_t CompoundCollider2D::GenerateShapes(cpBody* body, std::vector<cpShape*>* shapes) const
	{
		// This is our parent's default behavior
		if (m_doesOverrideCollisionProperties)
			return Collider2D::GenerateShapes(body, shapes);
		else
		{
			std::size_t shapeCount = 0;
			for (const auto& geom : m_geoms)
				shapeCount += geom->GenerateShapes(body, shapes);

			return shapeCount;
		}
	}

	/******************************** ConvexCollider2D *********************************/

	ConvexCollider2D::ConvexCollider2D(SparsePtr<const Vector2f> vertices, std::size_t vertexCount, float radius) :
	m_radius(radius)
	{
		m_vertices.resize(vertexCount);
		for (std::size_t i = 0; i < vertexCount; ++i)
			m_vertices[i].Set(*vertices++);
	}

	Vector2f ConvexCollider2D::ComputeCenterOfMass() const
	{
		static_assert(sizeof(cpVect) == sizeof(Vector2d), "Chipmunk vector is not equivalent to Vector2d");

		cpVect center = cpCentroidForPoly(int(m_vertices.size()), reinterpret_cast<const cpVect*>(m_vertices.data()));

		return Vector2f(float(center.x), float(center.y));
	}

	float ConvexCollider2D::ComputeMomentOfInertia(float mass) const
	{
		static_assert(sizeof(cpVect) == sizeof(Vector2d), "Chipmunk vector is not equivalent to Vector2d");

		return SafeCast<float>(cpMomentForPoly(mass, int(m_vertices.size()), reinterpret_cast<const cpVect*>(m_vertices.data()), cpv(0.0, 0.0), m_radius));
	}

	ColliderType2D ConvexCollider2D::GetType() const
	{
		return ColliderType2D::Convex;
	}

	std::size_t ConvexCollider2D::CreateShapes(cpBody* body, std::vector<cpShape*>* shapes) const
	{
		shapes->push_back(cpPolyShapeNew(body, int(m_vertices.size()), reinterpret_cast<const cpVect*>(m_vertices.data()), cpTransformIdentity, m_radius));
		return 1;
	}

	/********************************* NullCollider2D **********************************/

	ColliderType2D NullCollider2D::GetType() const
	{
		return ColliderType2D::Null;
	}

	Vector2f NullCollider2D::ComputeCenterOfMass() const
	{
		return Vector2f::Zero();
	}

	float NullCollider2D::ComputeMomentOfInertia(float mass) const
	{
		return (mass > 0.f) ? 1.f : 0.f; //< Null inertia is only possible for static/kinematic objects
	}

	std::size_t NullCollider2D::CreateShapes(cpBody* /*body*/, std::vector<cpShape*>* /*shapes*/) const
	{
		return 0;
	}

	/******************************** SegmentCollider2D *********************************/

	Vector2f SegmentCollider2D::ComputeCenterOfMass() const
	{
		return (m_first + m_second) / 2.f;
	}

	float SegmentCollider2D::ComputeMomentOfInertia(float mass) const
	{
		return SafeCast<float>(cpMomentForSegment(mass, cpv(m_first.x, m_first.y), cpv(m_second.x, m_second.y), m_thickness));
	}

	ColliderType2D SegmentCollider2D::GetType() const
	{
		return ColliderType2D::Segment;
	}

	std::size_t SegmentCollider2D::CreateShapes(cpBody* body, std::vector<cpShape*>* shapes) const
	{
		cpShape* segment = cpSegmentShapeNew(body, cpv(m_first.x, m_first.y), cpv(m_second.x, m_second.y), m_thickness);
		cpSegmentShapeSetNeighbors(segment, cpv(m_firstNeighbor.x, m_firstNeighbor.y), cpv(m_secondNeighbor.x, m_secondNeighbor.y));

		shapes->push_back(segment);
		return 1;
	}
}


text:
import yaml
import importlib
from functools import partial
from models.guassian_vae import VAE
from models.two_stage_vae import Stage2VAE
from models.vq_vae import VQVAE
from models.pixel_cnn import PixelCNN
from experiment import VAEModule, VAE2stageModule, VQVAEModule, PixelCNNModule

def get_config(fpath):
    with open(fpath, "r") as file:
        try:
            config = yaml.safe_load(file)
        except yaml.YAMLError as exc:
            print(exc)
        return config

def is_vq_vae(config):
    return config["exp_params"]["template"] == "vq vae"

def is_two_stage(config):
    return config["exp_params"]["template"] == "2 stage vae"

def is_default_vae(config):
    return config["exp_params"]["template"] == "default vae"

def is_config_valid(config):
    # Check config is valid
    assert type(config["exp_params"]["model_name"]) == str
    assert type(config["exp_params"]["template"]) == str
    assert config["encoder_params"]["latent_dim"] == config["decoder_params"]["latent_dim"]
    if is_two_stage(config):
        assert type(config["stage1_params"]["model"]) == str
        model_name = config["stage1_params"]["model"]
        fpath = f"./configs/{model_name}.yaml"
        config_stage_one = get_config(fpath)
        is_config_valid(config_stage_one)
        assert config_stage_one["encoder_params"]["latent_dim"] == config["encoder_params"]["input_dim"]
        assert config["decoder_params"]["output_dim"] == config["encoder_params"]["input_dim"]
    elif is_vq_vae(config):
        assert config["encoder_params"]["latent_dim"] == config["vq_params"]["embedding_dim"]

def is_mode_training(mode):
    return mode == "training"

def is_mode_inference(mode):
    return mode == "inference"

def get_first_stage_vae(config):
    model_name = config["stage1_params"]["model"]
    config = get_config(f"./configs/{model_name}.yaml")
    vae = assembler(config, "inference")
    vae.load_model()
    return vae

def compose_for_inference(models):
    if len(models) == 0:
        raise "empty model list"
    elif len(models) == 1:
        return models[0]
    elif len(models) == 2:
        return VAE2stageModule(models[0], models[1])
    else:
        vae = compose_for_inference(models[:-1])
        return VAE2stageModule(vae, models[-1])

def assembler(config, mode):
    # Get model name
    is_config_valid(config)

    # Get model components
    vae_name = config["exp_params"]["model_name"]
    componets = importlib.import_module(f"models.{vae_name}")
    encoder = componets.Encoder(**config["encoder_params"])
    decoder = componets.Decoder(**config["decoder_params"])
    loss = partial(componets.loss, config["loss_params"])

    # Assemble my model
    if is_default_vae(config):
        vae = VAE(vae_name, loss, encoder, decoder)
        vae = VAEModule(vae, config["exp_params"]["LR"], config["encoder_params"]["latent_dim"])
        vaes = [vae]
    elif is_two_stage(config):
        vae_first_stage = get_first_stage_vae(config)
        vae = Stage2VAE(vae_name, loss, encoder, decoder, vae_first_stage)
        vae = VAEModule(vae, config["exp_params"]["LR"], config["encoder_params"]["latent_dim"])
        vaes = [vae_first_stage, vae]
    elif is_vq_vae(config):
        vae = VQVAE(vae_name, loss, encoder, decoder, config["vq_params"])
        vae = VQVAEModule(vae, config)
        vaes = [vae]

    # training vs inference time model
    if is_mode_training(mode):
        vae = vaes[-1]
    elif is_mode_inference(mode):
        if is_two_stage(config):
            vae = compose_for_inference(vaes)

    return vae

if __name__ == "__main__":
    model_names = ["hinge_vae", "two_stage_vae"]
    for model_name in model_names:
        fpath = f"./configs/{model_name}.yaml"
        config = get_config(fpath)
        vae = assembler(config, "training")
        vae = assembler(config, "inference")


text:
<!DOCTYPE html>

<meta charset="utf-8">
</meta>
<meta content="width=device-width, initial-scale=1" name="viewport">
</meta>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
</link>
<link href="../resources/stof-style.css" rel="stylesheet">
</link>

<button aria-expanded="false" class="navbar-toggle collapsed" data-target="#bs-example-navbar-collapse-1" data-toggle="collapse" type="button">

       Toggle navigation

</button>

      Bob Dylan Lyrics

        Downloads

        All Songs

        All Albums

        1960s

          Bob Dylan (1962)

          The Freewheelin' Bob Dylan (1963)

          The Times They Are A-Changin' (1964)

          Another Side of Bob Dylan (1964)

          Bringing It All Back Home (1965)

          Highway 61 Revisited (1965)

          Blonde on Blonde (1966))

          Bob Dylan's Greatest Hits (1967)

          John Wesley Harding (1967)

          Nashville Skyline (1969)

        1970s

          Self Portrait (1970)

          New Morning (1970)

          Bob Dylan's Greatest Hits, Vol. II (1971)

          Pat Garrett & Billy the Kid (1973)

          Dylan (1973)

          Planet Waves (1974)

          Before the Flood (1974)

          Blood on the Tracks (1975)

          The Basement Tapes (1975)

          Desire (1976)

          Hard Rain (1976)

          Street-Legal (1978)

          Bob Dylan at Budokan (1979)

          Slow Train Coming (1979)

        1980s

          Saved (1980)

          Shot of Love (1981)

          Infidels (1983)

          Real Live (1984)

          Empire Burlesque (1985)

          Biograph (1985)

          Knocked Out Loaded (1986)

          Down in the Groove (1988)

          Dylan & the Dead (1989)

          Oh Mercy (1989)

        1990s

          Under the Red Sky (1990)

          The Bootleg Series Volumes 1-3 (Rare & Unreleased) 1961-1991 (1991)

          Good As I Been to You (1992)

          World Gone Wrong (1993)

          Bob Dylan's Greatest Hits Volume 3 (1994)

          MTV Unplugged (1995)

          Time Out of Mind (1997)

          The Bootleg Series Vol. 4: Bob Dylan Live 1966, The "Royal Albert Hall" Concert (1998)

        2000s

          The Essential Bob Dylan (2000)

          Love and Theft (2001)

          The Bootleg Series Vol. 5: Bob Dylan Live 1975, The Rolling Thunder Revue (2002)

          The Bootleg Series Vol. 6: Bob Dylan Live 1964, Concert at Philharmonic Hall (2004)

          The Best of Bob Dylan (2005)

          Modern Times (2006)

          Together through Life (2009)

        2010s

          Tempest (2012)

<gcse:search>
<form class="navbar-form navbar-right" role="search">
</form>
</gcse:search>

      The Bootleg Series Vol. 5: Bob Dylan Live 1975, The Rolling Thunder Revue

<comment>
        Released: November 26, 2002
       </comment>

<comment>
        Length: 102:00
       </comment>

<comment>
        Producer: Steve Berkowitz and Jeff Rosen
       </comment>

<comment>
        Label: Columbia
       </comment>

<comment>
        By Bob Dylan
       </comment>

       Disc 1

         Tonight I'll Be Staying Here with You

<comment>
         (recorded live on December 4, 1975 Montreal Forum in Montreal, Canada)
        </comment>

         It Ain't Me, Babe

<comment>
         (recorded live on November 20, 1975 Harvard Square Theatre in Cambridge, Massachusetts)
        </comment>

         A Hard Rain's A-Gonna Fall

<comment>
         (recorded live on December 4, 1975 Montreal Forum in Montreal, Canada)
        </comment>

         The Lonesome Death of Hattie Carroll

<comment>
         (recorded live on November 21, 1975 (late show) Boston Music Hall in Boston, Massachusetts)
        </comment>

         Romance in Durango

<comment>
         (original authors: Bob Dylan and Jacques Levy) (recorded live on November 20, 1975 Harvard Square Theatre in Cambridge, Massachusetts)
        </comment>

         Isis

<comment>
         (original authors: Bob Dylan and Jacques Levy) (recorded live on November 21, 1975 (late show) Boston Music Hall in Boston, Massachusetts)
        </comment>

         Mr. Tambourine Man

<comment>
         (recorded live on November 21, 1975 (early show) Boston Music Hall in Boston, Massachusetts)
        </comment>

         Simple Twist of Fate

<comment>
         (recorded live on November 20, 1975 Harvard Square Theatre in Cambridge, Massachusetts)
        </comment>

         Blowin' in the Wind

<comment>
         (recorded live on November 21, 1975 (late show) Boston Music Hall in Boston, Massachusetts)
        </comment>

         Mama, You Been on My Mind

<comment>
         (recorded live on November 20, 1975 Harvard Square Theatre in Cambridge, Massachusetts)
        </comment>

         I Shall Be Released

<comment>
         (recorded live on November 21, 1975 (early show) Boston Music Hall in Boston, Massachusetts)
        </comment>

       Disc 2

         It's All Over Now, Baby Blue

<comment>
         (recorded live on December 4, 1975 Montreal Forum in Montreal, Canada)
        </comment>

         Love Minus Zero/No Limit

<comment>
         (recorded live on December 4, 1975 Montreal Forum in Montreal, Canada)
        </comment>

         Tangled Up in Blue

<comment>
         (recorded live on November 21, 1975 (late show) Boston Music Hall in Boston, Massachusetts)
        </comment>

         The Water Is Wide

<comment>
         (Traditional) (recorded live on November 21, 1975 (late show) Boston Music Hall in Boston, Massachusetts)
        </comment>

         It Takes a Lot to Laugh, It Takes a Train to Cry

<comment>
         (recorded live on November 21, 1975 (late show) Boston Music Hall in Boston, Massachusetts)
        </comment>

         Oh, Sister

<comment>
         (original authors: Bob Dylan and Jacques Levy) (recorded live on November 21, 1975 (late show) Boston Music Hall in Boston, Massachusetts)
        </comment>

         Hurricane

<comment>
         (original authors: Bob Dylan and Jacques Levy) (recorded live on November 19, 1975 Worcester Memorial Auditorium in Worcester, Massachusetts)
        </comment>

         One More Cup of Coffee (Valley Below)

<comment>
         (recorded live on November 21, 1975 (late show) Boston Music Hall in Boston, Massachusetts)
        </comment>

         Sara

<comment>
         (recorded live on November 21, 1975 (late show) Boston Music Hall in Boston, Massachusetts)
        </comment>

         Just Like a Woman

<comment>
         (recorded live on November 21, 1975 (late show) Boston Music Hall in Boston, Massachusetts)
        </comment>

         Knockin' on Heaven's Door

<comment>
         (recorded live on November 20, 1975 Harvard Square Theatre in Cambridge, Massachusetts)
        </comment>


text:
var app = angular.module('TinkerApp',['ngRoute','ngMaterial'])
    app.value('baseUrl','../../TinkerCake/api/');
    app.config(['$routeProvider','$mdThemingProvider', '$mdIconProvider',function($routeProvider,$mdThemingProvider, $mdIconProvider){
        $routeProvider
        .when('/',      { title:"Login", controller:'LoginCtrl', templateUrl:'./views/login.html' })
        .when('/login', { title:"Login", controller:'LoginCtrl', templateUrl:'./views/login.html' })
        .when('/logout', { title:"Logout", controller:'LogoutCtrl', templateUrl:'./views/logout.html' })
        .when('/create-team', { title:"Create Team", controller:'CreateTeamCtrl', templateUrl:'./views/create-team.html' })
        .when('/add-team-members', { title:"Add Team Members", controller:'AddTeamMemberCtrl', templateUrl:'./views/add-team-member.html' })
        .when('/signup-to-team/team/:teamId/member/:memberId', { title:"Signup to team", controller:'SignupToTeamCtrl', templateUrl:'./views/signup-to-team.html' })
        .when('/home',{ title:"Home", controller:'HomeCtrl', templateUrl:'./views/home.html' })
        .when('/recent-feedback',{ title:"Recent Feedback", controller:'RecentFeedbackCtrl', templateUrl:'./views/recent-feedback.html' })
        .when('/send-feedback/:feedbackLogId',{ title:"Send Feedback", controller:'SendFeedbackCtrl', templateUrl:'./views/sent-feedback.html'})
        .otherwise({redirectTo:'/login'});

        $mdIconProvider
            .defaultIconSet("./assets/svg/avatars.svg", 128)
            .icon("menu"       , "./assets/svg/menu.svg"        , 24)
            .icon("share"      , "./assets/svg/share.svg"       , 24)
            .icon("google_plus", "./assets/svg/google_plus.svg" , 512)
            .icon("hangouts"   , "./assets/svg/hangouts.svg"    , 512)
            .icon("twitter"    , "./assets/svg/twitter.svg"     , 512)
            .icon("phone"      , "./assets/svg/phone.svg"       , 512);

        $mdThemingProvider.theme('default')
            .primaryPalette('red')
            .accentPalette('blue');
    }]);

    app.run(['$location', '$rootScope','$mdSidenav', function($location, $rootScope,$mdSidenav) {
        $rootScope.$on('$routeChangeSuccess', function (event, current) {
            $rootScope.title = current.$$route.title;

            if($location.path() =='/login' || $location.path() =='/logout' || $location.path() =='/'){
                $rootScope.showLogout = false;
            }else{
                $rootScope.showLogout = true;
            }
        });

    }]);


text:
package setting

import (
	"fmt"
//	"net/url"
	"os"
//	"path/filepath"
//	"strings"
	"time"

	"github.com/Unknwon/goconfig"
//	"github.com/howeyc/fsnotify"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/cache"
//	"github.com/astaxie/beego/orm"
	"github.com/astaxie/beego/utils/captcha"
//	"github.com/beego/compress"
//	"github.com/beego/i18n"
//	"github.com/beego/social-auth"
//	"github.com/beego/social-auth/apps"
)

var (
	AppName             string
	AppVer              string
	AppHost             string
	AppUrl              string
	AppLogo             string
	EnforceRedirect     bool
	AvatarURL           string
	LoginRememberDays   int
	LoginMaxRetries     int
	LoginFailedBlocks   int
    TimeZone            string
    DateFormat          string
	DateTimeFormat      string
	DateTimeShortFormat string
	CookieRememberName  string
	CookieUserName      string
	)

var (
	Cfg     *goconfig.ConfigFile
	Cache   cache.Cache
	Captcha *captcha.Captcha
)

var (
	GlobalConfPath   = "conf/global/app.ini"
//	CompressConfPath = "conf/compress.json"
)

// LoadConfig loads configuration file.
func LoadConfig() *goconfig.ConfigFile {
	var err error

	//if fh, _ := os.OpenFile(AppConfPath, os.O_RDONLY|os.O_CREATE, 0600); fh != nil {
//		fh.Close()
	//}

	// Load configuration, set app version and log level.
	Cfg, err = goconfig.LoadConfigFile(GlobalConfPath)

	if Cfg == nil {
		//Cfg, err = goconfig.LoadConfigFile(AppConfPath)
		if err != nil {
			fmt.Println("Fail to load configuration file: " + err.Error())
			os.Exit(2)
		}
	}

	Cfg.BlockMode = false

	// set time zone of wetalk system
	TimeZone = Cfg.MustValue("app", "time_zone", "UTC")
	if _, err := time.LoadLocation(TimeZone); err == nil {
		os.Setenv("TZ", TimeZone)
	} else {
		fmt.Println("Wrong time_zone: " + TimeZone + " " + err.Error())
		os.Exit(2)
	}

	beego.RunMode = Cfg.MustValue("app", "run_mode")
	beego.HttpPort = Cfg.MustInt("app", "http_port")

//	IsProMode = beego.RunMode == "pro"
//	if IsProMode {
//		beego.SetLevel(beego.LevelInfo)
//	}

	// cache system
//	Cache, err = cache.NewCache("memory", `{"interval":360}`)

//	Captcha = captcha.NewCaptcha("/captcha/", Cache)
	//Captcha.FieldIdName = "CaptchaId"
//	Captcha.FieldCaptchaName = "Captcha"

	// session settings
	beego.SessionOn = true
	beego.SessionProvider = Cfg.MustValue("session", "session_provider", "file")
	beego.SessionSavePath = Cfg.MustValue("session", "session_path", "sessions")
	beego.SessionName = Cfg.MustValue("session", "session_name", "Cloud_In_a_Box")
	beego.SessionCookieLifeTime = Cfg.MustInt("session", "session_life_time", 0)
	beego.SessionGCMaxLifetime = Cfg.MustInt64("session", "session_gc_time", 86400)

	beego.EnableXSRF = true
	// xsrf token expire time
	beego.XSRFExpire = 86400 * 365

//	driverName := Cfg.MustValue("orm", "driver_name", "mysql")
//	dataSource := Cfg.MustValue("orm", "data_source", "root:root@/wetalk?charset=utf8&loc=UTC")
//	maxIdle := Cfg.MustInt("orm", "max_idle_conn", 30)
//	maxOpen := Cfg.MustInt("orm", "max_open_conn", 50)

	// set default database
//	err = orm.RegisterDataBase("default", driverName, dataSource, maxIdle, maxOpen)
//	if err != nil {
//		beego.Error(err)
//	}
//	orm.RunCommand()

//	err = orm.RunSyncdb("default", false, false)
//	if err != nil {
//		beego.Error(err)
//	}

	reloadConfig()

//	if SphinxEnabled {
		// for search config
//		SphinxHost = Cfg.MustValue("search", "sphinx_host", "127.0.0.1:9306")
//		SphinxMaxConn = Cfg.MustInt("search", "sphinx_max_conn", 5)
//		orm.RegisterDriver("sphinx", orm.DR_MySQL)
//	}

//	social.DefaultAppUrl = AppUrl

	//settingLocales()
	//settingCompress()

	//configWatcher()

	return Cfg
}

func reloadConfig() {
	AppName = Cfg.MustValue("app", "app_name", "Cloud In a Box")
	beego.AppName = AppName

	AppHost = Cfg.MustValue("app", "app_host", "127.0.0.1:8085")
	AppUrl = Cfg.MustValue("app", "app_url", "http://127.0.0.1:8085/")
	AppLogo = Cfg.MustValue("app", "app_logo", "https://s3-ap-southeast-1.amazonaws.com/megampub/images/logo-megam160x43w.png")
	AvatarURL = Cfg.MustValue("app", "avatar_url")

	EnforceRedirect = Cfg.MustBool("app", "enforce_redirect")

	DateFormat = Cfg.MustValue("app", "date_format")
	DateTimeFormat = Cfg.MustValue("app", "datetime_format")
	DateTimeShortFormat = Cfg.MustValue("app", "datetime_short_format")

	LoginRememberDays = Cfg.MustInt("app", "login_remember_days", 7)
	LoginMaxRetries = Cfg.MustInt("app", "login_max_retries", 5)
	LoginFailedBlocks = Cfg.MustInt("app", "login_failed_blocks", 10)

	CookieRememberName = Cfg.MustValue("app", "cookie_remember_name")
	CookieUserName = Cfg.MustValue("app", "cookie_user_name")

}


text:
package com.janela.mobile.tests.user;

import android.net.Uri;
import android.test.AndroidTestCase;

import com.janela.mobile.core.user.UserUriMatcher;

import org.eclipse.egit.github.core.User;

/**
 * Unit tests of {@link UserUriMatcher}
 */
public class UserUriMatcherTest extends AndroidTestCase {

    /**
     * Verify empty URI
     */
    public void testEmptyUri() {
        assertNull(UserUriMatcher.getUser(Uri.parse("")));
    }

    /**
     * Verify no name
     */
    public void testUriWithNoName() {
        assertNull(UserUriMatcher.getUser(Uri.parse("http://janela.com")));
        assertNull(UserUriMatcher.getUser(Uri.parse("https://janela.com")));
        assertNull(UserUriMatcher.getUser(Uri.parse("http://janela.com/")));
        assertNull(UserUriMatcher.getUser(Uri.parse("http://janela.com//")));
    }

    /**
     * Verify URI with name
     */
    public void testHttpUriWithName() {
        User user = UserUriMatcher.getUser(Uri
                .parse("http://janela.com/defunkt"));
        assertNotNull(user);
        assertEquals("defunkt", user.getLogin());
    }

    /**
     * Verify URI with name
     */
    public void testHttpsUriWithName() {
        User user = UserUriMatcher.getUser(Uri
                .parse("https://janela.com/mojombo"));
        assertNotNull(user);
        assertEquals("mojombo", user.getLogin());
    }

    /**
     * Verify URI with name
     */
    public void testUriWithTrailingSlash() {
        User user = UserUriMatcher.getUser(Uri
                .parse("http://janela.com/defunkt/"));
        assertNotNull(user);
        assertEquals("defunkt", user.getLogin());
    }

    /**
     * Verify URI with name
     */
    public void testUriWithTrailingSlashes() {
        User user = UserUriMatcher.getUser(Uri
                .parse("http://janela.com/defunkt//"));
        assertNotNull(user);
        assertEquals("defunkt", user.getLogin());
    }
}


text:
FROM postgres:9.3
MAINTAINER Jakub Cechacek <jcechace@redhat.com>

ENV POSTGRES_USER apimanqe
ENV POSTGRES_PASSWORD apimanqe

ADD db.sql /docker-entrypoint-initdb.d/db.sql


text:
// Copyright (C) 2002-2012 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h

#ifndef __I_CURSOR_CONTROL_H_INCLUDED__
#define __I_CURSOR_CONTROL_H_INCLUDED__

#include "IReferenceCounted.h"
#include "position2d.h"
#include "rect.h"

namespace ue
{
namespace gui
{

	class IGUISpriteBank;

	//! Default icons for cursors
	enum ECURSOR_ICON
	{
		// Following cursors might be system specific, or might use an Irrlicht icon-set. No guarantees so far.
		ECI_NORMAL,	// arrow
		ECI_CROSS,	// Crosshair
		ECI_HAND,	// Hand
		ECI_HELP,	// Arrow and question mark
		ECI_IBEAM,	// typical text-selection cursor
		ECI_NO,		// should not click icon
		ECI_WAIT,	// hourclass
		ECI_SIZEALL,	// arrow in all directions
		ECI_SIZENESW,	// resizes in direction north-east or south-west
		ECI_SIZENWSE,	// resizes in direction north-west or south-east
		ECI_SIZENS,	// resizes in direction north or south
		ECI_SIZEWE,	// resizes in direction west or east
		ECI_UP,		// up-arrow

		// Implementer note: Should we add system specific cursors, which use guaranteed the system icons,
		// then I would recommend using a naming scheme like ECI_W32_CROSS, ECI_X11_CROSSHAIR and adding those
		// additionally.

		ECI_COUNT		// maximal of defined cursors. Note that higher values can be created at runtime
	};

	//! Names for ECURSOR_ICON
	const c8* const GUICursorIconNames[ECI_COUNT+1] =
	{
		"normal",
		"cross",
		"hand",
		"help",
		"ibeam",
		"no",
		"wait",
		"sizeall",
		"sizenesw",
		"sizenwse",
		"sizens",
		"sizewe",
		"sizeup",
		0
	};

	//! structure used to set sprites as cursors.
	struct SCursorSprite
	{
		SCursorSprite()
		: SpriteBank(0), SpriteId(-1)
		{
		}

		SCursorSprite( gui::IGUISpriteBank * spriteBank, s32 spriteId, const core::position2d<s32> &hotspot=(core::position2d<s32>(0,0)) )
		: SpriteBank(spriteBank), SpriteId(spriteId), HotSpot(hotspot)
		{
		}

		IGUISpriteBank * SpriteBank;
		s32 SpriteId;
		core::position2d<s32> HotSpot;
	};

	//! platform specific behavior flags for the cursor
	enum ECURSOR_PLATFORM_BEHAVIOR
	{
		//! default - no platform specific behavior
		ECPB_NONE = 0,

		//! On X11 try caching cursor updates as XQueryPointer calls can be expensive.
		/** Update cursor positions only when the irrlicht timer has been updated or the timer is stopped.
			This means you usually get one cursor update per device->run() which will be fine in most cases.
			See this forum-thread for a more detailed explanation:
			http://irrlicht.sourceforge.net/forum/viewtopic.php?f=7&t=45525
		*/
		ECPB_X11_CACHE_UPDATES = 1
	};

	//! Interface to manipulate the mouse cursor.
	class ICursorControl : public virtual IReferenceCounted
	{
	public:

		//! Changes the visible state of the mouse cursor.
		/** \param visible: The new visible state. If true, the cursor will be visible,
		if false, it will be invisible. */
		virtual void setVisible(bool visible) = 0;

		//! Returns if the cursor is currently visible.
		/** \return True if the cursor is visible, false if not. */
		virtual bool isVisible() const = 0;

		//! Sets the new position of the cursor.
		/** The position must be
		between (0.0f, 0.0f) and (1.0f, 1.0f), where (0.0f, 0.0f) is
		the top left corner and (1.0f, 1.0f) is the bottom right corner of the
		render window.
		\param pos New position of the cursor. */
		virtual void setPosition(const core::position2d<f32> &pos) = 0;

		//! Sets the new position of the cursor.
		/** The position must be
		between (0.0f, 0.0f) and (1.0f, 1.0f), where (0.0f, 0.0f) is
		the top left corner and (1.0f, 1.0f) is the bottom right corner of the
		render window.
		\param x New x-coord of the cursor.
		\param y New x-coord of the cursor. */
		virtual void setPosition(f32 x, f32 y) = 0;

		//! Sets the new position of the cursor.
		/** \param pos: New position of the cursor. The coordinates are pixel units. */
		virtual void setPosition(const core::position2d<s32> &pos) = 0;

		//! Sets the new position of the cursor.
		/** \param x New x-coord of the cursor. The coordinates are pixel units.
		\param y New y-coord of the cursor. The coordinates are pixel units. */
		virtual void setPosition(s32 x, s32 y) = 0;

		//! Returns the current position of the mouse cursor.
		/** \return Returns the current position of the cursor. The returned position
		is the position of the mouse cursor in pixel units. */
		virtual const core::position2d<s32>& getPosition() = 0;

		//! Returns the current position of the mouse cursor.
		/** \return Returns the current position of the cursor. The returned position
		is a value between (0.0f, 0.0f) and (1.0f, 1.0f), where (0.0f, 0.0f) is
		the top left corner and (1.0f, 1.0f) is the bottom right corner of the
		render window. */
		virtual core::position2d<f32> getRelativePosition() = 0;

		//! Sets an absolute reference rect for setting and retrieving the cursor position.
		/** If this rect is set, the cursor position is not being calculated relative to
		the rendering window but to this rect. You can set the rect pointer to 0 to disable
		this feature again. This feature is useful when rendering into parts of foreign windows
		for example in an editor.
		\param rect: A pointer to an reference rectangle or 0 to disable the reference rectangle.*/
		virtual void setReferenceRect(core::rect<s32>* rect=0) = 0;

		//! Sets the active cursor icon
		/** Setting cursor icons is so far only supported on Win32 and Linux */
		virtual void setActiveIcon(ECURSOR_ICON iconId) {}

		//! Gets the currently active icon
		virtual ECURSOR_ICON getActiveIcon() const { return gui::ECI_NORMAL; }

		//! Add a custom sprite as cursor icon.
		/** \return Identification for the icon */
		virtual ECURSOR_ICON addIcon(const gui::SCursorSprite& icon) { return gui::ECI_NORMAL; }

		//! replace a cursor icon.
		/** Changing cursor icons is so far only supported on Win32 and Linux
			Note that this only changes the icons within your application, system cursors outside your
			application will not be affected.
		*/
		virtual void changeIcon(ECURSOR_ICON iconId, const gui::SCursorSprite& sprite) {}

		//! Return a system-specific size which is supported for cursors. Larger icons will fail, smaller icons might work.
		virtual core::dimension2di getSupportedIconSize() const { return core::dimension2di(0,0); }

		//! Set platform specific behavior flags.
		virtual void setPlatformBehavior(ECURSOR_PLATFORM_BEHAVIOR behavior) {}

		//! Return platform specific behavior.
		/** \return Behavior set by setPlatformBehavior or ECPB_NONE for platforms not implementing specific behaviors.
		*/
		virtual ECURSOR_PLATFORM_BEHAVIOR getPlatformBehavior() const { return ECPB_NONE; }
	};

} // end namespace gui
} // end namespace ue

#endif


text:
package gg.galaxygaming.necessities;

import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Tag;
import org.bukkit.World;

public class SafeLocation {

    boolean wouldFall(Location l) {
        double x = l.getX(), y = l.getY(), z = l.getZ();
        l.setY(l.getY() - 1);
        boolean temp = false;
        if (l.getBlock().getType().equals(Material.AIR)) {
            temp = true;
            double xDif = l.getX() - l.getBlockX();
            if (xDif > 0.5) {
                l.setX(l.getBlockX() + 1);
            } else if (xDif < 0.5) {
                l.setX(l.getBlockX() - 1);
            }
            if (!l.getBlock().getType().equals(Material.AIR)) {
                temp = false;
            }
            double zDif = l.getZ() - l.getBlockZ();
            if (zDif > 0.5) {
                l.setZ(l.getBlockZ() + 1);
            } else if (zDif < 0.5) {
                l.setZ(l.getBlockZ() - 1);
            }
            if (!l.getBlock().getType().equals(Material.AIR)) {
                temp = false;
            }
            l.setX(x);
            if (!l.getBlock().getType().equals(Material.AIR)) {
                temp = false;
            }
        }
        //Set values back because it is original object, which means that getSafe needs it unmodified
        //l.setX(x); //Already the same
        l.setY(y);
        l.setZ(z);
        return temp;
    }

    /**
     * Returns a safer location than the given one.
     *
     * @param l The location to check.
     * @return A safer location than the initial one.
     */
    public Location getSafe(Location l) {//TODO: Make it check for air pockets nearby instead of just up
        int maxHeight = l.getWorld().getMaxHeight();
        if (l.getWorld().getEnvironment().equals(World.Environment.NETHER)) {
            maxHeight = 126;
        }
        //TODO go out ~5 blocks from close to far as it goes up, and then create a private method of this??? because checking about falling does it need the aoe? probably
        //CANNOT just add extra for statements as the overLava would stop working properly
        //TODO: Not check to see if type changed? and just check if it is on a solid block???
        //Compare with https://github.com/drtshock/Essentials/blob/2.x/Essentials/src/com/earth2me/essentials/utils/LocationUtil.java to see about rough logic
        for (int i = l.getBlockY(); i < maxHeight; i++) {
            Material type = new Location(l.getWorld(), l.getX(), i, l.getZ()).getBlock().getType();
            if (!type.isSolid() && !isLeaves(type) && Tag.VALID_SPAWN.isTagged(type)) {
                l = new Location(l.getWorld(), l.getX(), i, l.getZ(), l.getYaw(), l.getPitch());
                break;
            }
        }
        if (wouldFall(l)) {
            for (int i = l.getBlockY(); i > 0; i--) {
                if (new Location(l.getWorld(), l.getX(), i, l.getZ()).getBlock().getType().isSolid()) {
                    l = new Location(l.getWorld(), l.getX(), i + 1, l.getZ(), l.getYaw(), l.getPitch());
                    if (!Tag.VALID_SPAWN.isTagged(l.getBlock().getType())) {
                        l = getSafe(l);
                    }
                    break;
                }
            }
        }
        return l;
    }

    private boolean isLeaves(Material type) {
        return type.equals(Material.ACACIA_LEAVES) || type.equals(Material.BIRCH_LEAVES) || type
              .equals(Material.DARK_OAK_LEAVES) || type.equals(Material.JUNGLE_LEAVES) ||
              type.equals(Material.OAK_LEAVES) || type.equals(Material.SPRUCE_LEAVES);
    }
}


text:
WORKING WITH GIT

1
git push origin head:refs/for/fpt_lpet_frdmkl33z_hal_dac
git push origin HEAD:refs/for/master
Push a branch to gerrit repository
2.pull
git pull <remote> <branch>
If you wish to set tracking information for this branch you can do so with:
git branch --set-upstream-to=origin/<branch> develope_ble_led_button
3.
git commit --amend
Amend previous commit
4.
git remote -v
5.
git fetch origin
git pull origin [branch_name]
6.
git submodule init
git submodule update
git submodule deinit -f

7.
git vim .gitmodules
git checkout .gitmodules

8.
git clean - Remove untracked files from the working tree
git clean -n
Perform a "dry run" of git clean. This will show you which files are going to be removed without actually doing it.
git clean -f
Remove untracked files from the current directory
git clean -f <path>
Remove untracked files, but limit the operation to the specified path.
git clean -df
Remove untracked files and untracked directories from the current directory.
[-d] Remove untracked directories in addition to untracked files.
[f] --force
git clean -xf
Remove untracked files from the current directory as well as any files that Git usually ignores.

9.
Update pack set
git commit --amend
	then:
git push origin HEAD:refs/for/master

10.
gitk --all
Displays changes in a repository or a selected set of commits

11. git log
-n
	Display the n last commit

--since=<date>
--after=<date>
	Show commits more recent than a specific date.

--author=<pattern>
--committer=<pattern>
	Limit output with pattern

--merges
	Print only merge commits. This is exactly the same as --min-parents=2.
12. HEAD
First all what is HEAD?
	HEAD is a simply a reference to the current commit (latest) in the current branch.
	There can only be 1 HEAD at any given time.
	If you are not on the latest commit - meaning that HEAD is point to a prior commit in history its called detached HEAD

git checkout
git checkout <commit_id>
git checkout -b <new branch> <commit_id>
git checkout HEAD~X // x is the number of commits t go back
	This will checkout new branch pointing to the desired commit.
	This command will checkout to a given commit.
	At this point you can create a branch and start to work from this point on

git reflog
git reflog
git checkout HEAD@{...}
This will get you back to your desired commit

13. diff
git diff [--options] <commit> <commit> [--] [<path>...]
	Show changes between commits, commit and working tree, etc

git diff HEAD^^ HEAD main.c
	to see the difference for a file "main.c


text:
from selenium.webdriver.firefox.webdriver import WebDriver
from selenium.webdriver.common.action_chains import ActionChains
import time, unittest

def is_alert_present(wd):
    try:
        wd.switch_to_alert().text
        return True
    except:
        return False

class (unittest.TestCase):
    def setUp(self):
        self.wd = WebDriver()
        self.wd.implicitly_wait(60)

    def test_(self):
        success = True
        wd = self.wd
        wd.get("http://localhost/addressbook/addressbook/")
        wd.find_element_by_name("user").click()
        wd.find_element_by_name("user").clear()
        wd.find_element_by_name("user").send_keys("admin")
        wd.find_element_by_css_selector("input[type=\"submit\"]").click()
        wd.find_element_by_name("user").click()
        wd.find_element_by_name("user").clear()
        wd.find_element_by_name("user").send_keys("admin")
        wd.find_element_by_name("pass").click()
        wd.find_element_by_name("pass").clear()
        wd.find_element_by_name("pass").send_keys("sceret")
        wd.find_element_by_css_selector("input[type=\"submit\"]").click()
        wd.find_element_by_name("user").click()
        wd.find_element_by_name("user").clear()
        wd.find_element_by_name("user").send_keys("admin")
        wd.find_element_by_name("pass").click()
        wd.find_element_by_name("pass").clear()
        wd.find_element_by_name("pass").send_keys("secret")
        wd.find_element_by_css_selector("input[type=\"submit\"]").click()
        wd.find_element_by_link_text("add new").click()
        wd.find_element_by_link_text("groups").click()
        wd.find_element_by_name("new").click()
        wd.find_element_by_name("group_name").click()
        wd.find_element_by_name("group_name").clear()
        wd.find_element_by_name("group_name").send_keys("group_name4")
        wd.find_element_by_name("group_header").click()
        wd.find_element_by_name("group_header").clear()
        wd.find_element_by_name("group_header").send_keys("group_header4")
        wd.find_element_by_name("group_footer").click()
        wd.find_element_by_name("group_footer").clear()
        wd.find_element_by_name("group_footer").send_keys("group_footer")
        wd.find_element_by_name("group_footer").click()
        wd.find_element_by_name("group_footer").clear()
        wd.find_element_by_name("group_footer").send_keys("group4_footer")
        wd.find_element_by_css_selector("#content > form").click()
        wd.find_element_by_name("submit").click()
        wd.find_element_by_link_text("group page").click()
        wd.find_element_by_link_text("Logout").click()
        self.assertTrue(success)

    def tearDown(self):
        self.wd.quit()

if __name__ == '__main__':
    unittest.main()


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

				<input type="text" name="name" id="code" placeholder="Enter Barcodes Manually" />
				<input type="submit" id="add-item" value="ADD" class="call-links"></input>

Qty

item code

category

item

price

		COMPLETE DELIVERY REQUEST

Edit Item

							EDIT QTY FOR ITEM:
							<input type="text" name="name" id="qty" placeholder="Enter Qty" />

							<input type="submit" class="btn submit-button" onClick="confirmQty();" value="Confirm" />


text:
namespace EncompassRest.Company.Users.Rights
{
    /// <summary>
    /// LOCompToolRights
    /// </summary>
    public sealed class LOCompToolRights : ParentAccessRights
    {
        private DirtyValue<bool?>? _brokerComp;
        private DirtyValue<bool?>? _loanOfficerComp;

        /// <summary>
        /// LOCompToolRights BrokerComp
        /// </summary>
        public bool? BrokerComp { get => _brokerComp; set => SetField(ref _brokerComp, value); }

        /// <summary>
        /// LOCompToolRights LoanOfficerComp
        /// </summary>
        public bool? LoanOfficerComp { get => _loanOfficerComp; set => SetField(ref _loanOfficerComp, value); }
    }
}