text:
import datetime

from flask import session, make_response, jsonify
from sqlalchemy.exc import IntegrityError

from api_version.utils import activate_mail, validate_, resend_activate_mail, send_one_time_mail, send_sms, exec_
from ext_declaration import db
from models import User, PrivateDetails, User_Msgs
from api_version.utils import generate_onetime_password

# let the job begin

def create_account_handler(user="", email="", name="", num=""):
    """
    This function would be used to insert data into db
     and this function would handle the creation of account

    """
    if validate_("username", user) and validate_("email", email) and validate_("fullname", name) and validate_("number",
                                                                                num):

        try:
            user_ = User.query.filter_by(username=user).first()
            email_ = User.query.filter_by(email=email).first()
            phn_ = User.query.filter_by(phone_number=num).first()

            if user_ is not None:

                # return make_response(jsonify({'res':'user'}))
                return "user"

            elif email_ is not None:

                # return make_response(jsonify({'res':'email'}))
                return "email"

            elif phn_ is not None:

                # return make_response(jsonify({'res':'number'}))
                return "number"

            else:
                user = User(full_name=name, email=email, username=user, phone_number=num,
                            img_path="img_badge/fm0894tf9re.jpg")
                db.session.add(user)
                res = activate_mail(email)
                if not res:
                    db.session.commit()
                    # return make_response(jsonify({'res':'true'}))
                    return True
                else:
                    db.session.rollback()
                    # return make_response(jsonify({'res':'mailErr'}))
                    return "mail"

        except IntegrityError as e:

            print("Exception @: \n")
            print(e)

            db.session.rollback()
            # return make_response(jsonify({'res':'false'}))
            return False
        except Exception as e:

            db.session.delete(user)
            db.session.commit()
            print("Error Occured: \n" + str(e))
            # return make_response(jsonify({'res':'false'}))
            return False

    else:
        # return make_response(jsonify({'res':'error'}))
        return "error"

def resend_mail(email=""):
    """
    This function would be used to resend activation link to user's mail

    """
    if validate_("email", email):

        try:
            email_ = User.query.filter_by(email=email).first()

            if email_ is not None and not email_.account_confirmed:

                res = resend_activate_mail(email)

                if not res:
                    # return make_response(jsonify({'res':'sent'}))
                    return True
                else:
                    # return make_response(jsonify({'res':'mailErr'}))
                    return "mail"

            else:
                # return make_response(jsonify({'res':'invalid'}))
                return "invalid"

        except IntegrityError as  e:

            print("Exception: \n")
            print(e)

            # return make_response(jsonify({'res':'false'}))
            return False
        except Exception as e:

            print("Error Occured: \n" + str(e))
            # return make_response(jsonify({'res':'false'}))
            return False

    else:
        # return make_response(jsonify({'res':'false'}))
        return False

def update_account_handler(add="", state="", city="", postal="", dob=""):
    # print "hy"
    if 'user' in session:

        if validate_("address", add) and validate_("state", state) and validate_("city", city) and validate_("postal",
                                                                                postal) and validate_(
            "date", dob):

            try:
                # User.query.filter_by(username=user).first()
                user_ = User.query.filter_by(username=session['user']).first()
                # return make_response(jsonify({'res':str(session['user'])}))

                if user_ is not None:
                    try:
                        pDtails = PrivateDetails(address=add, city=city, state=state, postal_code=postal,
                                                 date_of_birth=dob, user_id=str(session['user']))
                        db.session.add(pDtails)
                        user_.account_confirmed = True
                        db.session.commit()
                        # return make_response(jsonify({'res':'true'}))
                        return True
                    except Exception as e:
                        db.session.rollback()
                        db.session.commit()
                        # print "Error Occured: \n"+str(e)
                        # return make_response(jsonify({'res':'false'}))
                        print(e)
                        return False

                else:
                    # return make_response(jsonify({'res':'error'}))
                    return 'error'

            except IntegrityError as e:
                db.session.rollback()
                print(e)
                # return make_response(jsonify({'res':'false'}))
                return False
            except Exception as e:
                db.session.rollback()
                print(e)
                # db.session.delete(pDtails)
                # print "Error Occured: \n"+str(e)
                # return make_response(jsonify({'res':'false'}))
                return False

        else:
            # return make_response(jsonify({'res':'error'}))
            print("Validation error")
            return 'error'

    else:
        # return make_response(jsonify({'res':'error'}))
        print("User does not exist error")
        return 'not_logged'

def otp_generator(user="", type_=""):
    if validate_("username", user) or validate_("email", user):

        user = User.query.filter((User.email == user) | (User.username == user)).first()
        if user is not None:
            if user.email_confirmed:

                try:
                    if type_ == "email":
                        res = send_one_time_mail(user.email)
                        if not res:

                            user.password_hash = res
                            db.session.commit()
                            # exec_(str(user.email))
                            print("username password change is done")
                            # return make_response(jsonify({'res':'success'}))
                            return True

                        else:
                            print("error in connection so email could not be sent successfully")
                            # print make_response(jsonify({'res':'error'}))
                            # return make_response(jsonify({'res':'error'}))
                            return False

                    else:
                        try:
                            data = generate_onetime_password()
                            otp = 'Your Paymiumm Login OTP is: {}'.format(data)
                            res = send_sms(user.phone_number, otp)
                            user.password_hash = res
                            db.session.commit()
                            exec_(str(user.email))
                            print("username password change is done")
                            return True
                        except:

                            print("error in connection so text could not be sent successfully")
                            # print make_response(jsonify({'res':'error'}))
                            # return make_response(jsonify({'res':'error'}))
                            return False

                except Exception as e:

                    print("error in occured")
                    print(e)
                    # return make_response(jsonify({'res':'error'}))
                    return False

            else:
                # return make_response(jsonify({'res':'unconfirmed'}))
                print('unconfirmed')
                return 'unconfirmed'

        else:
            # return make_response(jsonify({'res':'unconfirmed'}))
            print('invalid')
            return 'invalid'

    else:
        print("opps")
        # return make_response(jsonify({'res':"invalid"}))
        return 'invalid'

def log_user_in(user="", pwd="", device=""):
    if validate_("username", user) or validate_("email", user) and validate_("password", pwd):

        user = User.query.filter((User.email == user) | (User.username == user)).first()  # check if user exist
        if user is not None and user.password_hash == pwd:
            if user.email_confirmed and user.account_confirmed:

                try:
                    user.dev_identity = device
                    user.password_hash = ""
                    db.session.commit()
                    session['user'] = user.username
                    session['device'] = user.dev_identity
                    now = datetime.datetime.now()
                    return make_response(jsonify(
                        {'res': 'true', 'da_t_e': str(now.year), 'userId': str(session['user']),
                         'user': str(user.username), 't_k_n_t_R': user.dev_identity, 'user_email': str(user.email),
                         'user_img': str(user.img_path)}))

                except Exception as e:

                    print("Error at:\n")
                    print(e)
                    db.session.rollback()
                    return make_response(jsonify({'res': "error"}))
            elif user.email_confirmed and not user.account_confirmed:
                try:
                    user.dev_identity = device
                    user.password_hash = ""
                    db.session.commit()
                    session['user'] = user.username
                    session['device'] = user.dev_identity
                    now = datetime.datetime.now()
                    return make_response(jsonify(
                        {'res': 'accountUnconfirmed', 'da_t_e': str(now.year), 'userId': str(session['user']),
                         'user': str(user.username), 't_k_n_t_R': user.dev_identity, 'user_email': str(user.email),
                         'user_img': str(user.img_path)}))

                except Exception as  e:

                    print("Error at:\n")
                    print(e)

                    db.session.rollback()
                    return make_response(jsonify({'res': "error"}))

            else:

                return make_response(jsonify({'res': "unconfirmed"}))

        else:
            print("false user name/email does not exist")
            return make_response(jsonify({'res': "false"}))

    else:
        print("false invalid format")
        return make_response(jsonify({'res': "false"}))

def search_user(query):
    if 'user' in session and 'device' in session:
        try:
            users = User.query.filter(User.username.like("%" + query + "%")).all()
            # print users
            if users:
                results = []
                # print user[0].img_path
                for user in users:

                    if user.username == session['user']:
                        print(user)
                        print("naf this is the user that is already logged Into the system\n")
                    else:
                        print("not logged user")
                        print(user)
                        results.append({"user": {"username": user.username, "img": user.img_path}})
                        print(results)
                return make_response(jsonify({'res': results, 'status': True}))
            else:
                print("no result found")
                return make_response(jsonify({'res': "false", 'status': False}))
        except Exception as e:

            print(e)
            return make_response(jsonify({'res': "error", 'status': False}))
    else:
        print("User not logged in")
        return make_response(jsonify({'res': "not_logged", 'status': False}))

def load_Chat(user):
    try:
        if 'user' in session:
            # print user
            users = User_Msgs.query.filter(
                (User_Msgs.sndrs_name == session['user']) & (User_Msgs.recvrs_name == user) | (
                    User_Msgs.sndrs_name == user) & (User_Msgs.recvrs_name == session["user"])).all()
            if users:
                result = []
                for user in users:
                    # print user.sndrs_name
                    # logic for determining sender and reciever goes in here
                    date = user.sent_time_Date
                    print(str(date))
                    if user.sndrs_name.lower() == session['user'].lower():
                        print(user.sndrs_name + " is the current user logged in")
                        # display this if this is the user currently loggedin
                        # formated_date=str(date).split(" ")[0]
                        result.append({'message': {'isUser': True, 'transact_status': user.trnsction_info,
                                                   'msg_type': user.msg_type, 'shrt_msg': user.shrt_msg,
                                                   'isSeen': user.is_Read, 'amt': user.s_or_r_Amnt, 'date': str(date)}})
                    else:

                        # update the message has already been marked as seen if false convert to true
                        print(user.is_Read)
                        if not user.is_Read:
                            user.is_Read = True
                            db.session.commit()
                            print("Messages has now been marked as read")
                        result.append({'message': {'isUser': False, 'transact_status': user.trnsction_info,
                                                   'msg_type': user.msg_type, 'shrt_msg': user.shrt_msg,
                                                   'isSeen': user.is_Read, 'amt': user.s_or_r_Amnt, 'date': str(date)}})
            else:
                print("Naf no result was found")
                return make_response(jsonify({'res': 'no_msg'}))

            # print "user's chat to load is "+users.s_or_r_Amnt
            # return user

            # result.append({'message':{'isUser':True,'transact_status':'success','isSeen':True,'amt':100.00,'date':'2017-10-07 16:45:50'}})
            return make_response(jsonify({'res': result}))
        else:
            print("User not logged in")
            return make_response(jsonify({'res': "not_logged", 'status': False}))
    except Exception as  e:
        print(e)
        db.session.rollback()
        return make_response(jsonify({'res': 'error'}))
    except IntegrityError:
        db.session.rollback()


text:
import carnatic_util
import raagas
import random

class MarkovAnalyser:
  def __init__(self, width=4, raaga=0):
    self.width = width
    self.ascend_descend_probability = 0.1
    self.flow_probability = 0.3
    self.songs = []
    self.markov_state_space = {}

    self.NumberNotes(raagas.notes[raaga])
    return

  def SetAscendDescendProbability(self, prob):
    self.ascend_descend_probability = prob
    return

  def SetAscendProbability(self, des):
    self.descend_probability = des
    return

  def NumberNotes(self, notes):
    numberings = []
    l = len(notes)
    for i in range(l):
      numberings.append((notes[i]+"."     , i))       # Lower Octave
      numberings.append((notes[i]         , i+l))   # Current Octave
      numberings.append((notes[i].upper() , i+2*l)) # Higher Octave

    self.notes_to_numbers = dict([(a, b) for (a,b) in numberings])
    self.numbers_to_notes = dict([(b, a) for (a,b) in numberings])
    return

  def IncrementNote(self, note):
    note, l = note.split()
    n = self.notes_to_numbers[note]
    n += 1
    if n == self.notes_to_numbers["D2"]:
      n -= 1
    return self.HashNote((self.numbers_to_notes[n], 1))

  def DecrementNote(self, note):
    note, l = note.split()
    n = self.notes_to_numbers[note]
    n -= 1
    if n == self.notes_to_numbers["s."]:
      n += 1
    return self.HashNote((self.numbers_to_notes[n], 1))

  def HashNote(self, (a, b)):
    return a + " " + str(b)

  def UnHashNote(self, s):
    (a, b) = s.split()
    b = int(b)
    return (a, b)

  def AddSong(self, notes):
    song = []
    for (note, length) in notes:
      song.append(self.HashNote((note, length)))

    self.songs.append(song)
    return

  def MakeKeyFromNotes(self, notes):
    """ Makes an immutable string from the given notes played
    that can be used as a hash key"""
    return '|'.join(notes)

  def MarkovAnalyse(self):
    """ Analyse the songs given, so that we have
        a dictionary from last `width` notes played
        to the next possible note """
    for song in self.songs:
      for i in range(len(song) - self.width-1):
        key = self.MakeKeyFromNotes(song[i:i+self.width])
        try:
          self.markov_state_space[key].append((song[i+self.width], song[i+self.width:i+2*self.width]))
        except KeyError:
          self.markov_state_space[key] = [(song[i+1], song[i+1:i+self.width])]

    return

  def GenerateStartingNotes(self):
    song = random.choice(self.songs)
    random_start_index = random.randint(0, len(song) - self.width - 2)
    # print random_start_index
    return song[random_start_index:random_start_index+self.width]

  def ChooseFirstWithProbability(self, a, b, p):
    roll = random.uniform(0, 1)
    if roll <= p:
      return a
    else:
      return b

  def PerturbNote(self, notes):
    last_note = notes[-1]
    (up_note, down_note) = (self.IncrementNote(notes[-1]) ,self.DecrementNote(notes[-1]))

    if notes[-2] == up_note:
      perturbed_note = self.ChooseFirstWithProbability(down_note, up_note, 0.75)
    elif notes[-2] == down_note:
      perturbed_note = self.ChooseFirstWithProbability(up_note, down_note, 0.75)
    else:
      perturbed_note = self.ChooseFirstWithProbability(up_note, down_note, 0.5)

    perturbed_note = self.ChooseFirstWithProbability(notes[-1], perturbed_note, 0.2)
    (s, l) = self.UnHashNote(perturbed_note)
    # Choose length according to the following distribution
    l = random.choice([1,1,1,1,2,2,3,4])
    # print "perturbed_note is", perturbed_note
    perturbed_note = self.HashNote((s, l))

    return perturbed_note

  def MarkovGenerate(self, song_length=100):
    # print self.markov_state_space
    notes = self.GenerateStartingNotes()

    i = 0
    while i+self.width < song_length:
      key = self.MakeKeyFromNotes(notes[-self.width:])

      perturbed_note = self.PerturbNote(notes[-self.width:])

      if self.markov_state_space.has_key(key):
        next_note, follow_notes = random.choice(self.markov_state_space[key])

        r = random.uniform(0,1)
        if r < self.flow_probability :
          # print follow_notes[-1], notes[-1]
          if follow_notes[-1] != notes[-1]:
            # print "In the flow"
            notes.extend(follow_notes)
            # print i,
            # print follow_notes
            i += sum([l for (s,l) in map(self.UnHashNote, follow_notes)])
            # print i
            continue

        next_note = self.ChooseFirstWithProbability(perturbed_note, next_note, self.ascend_descend_probability)
      else:
        next_note = perturbed_note

      notes.append(next_note)
      (n, l) = self.UnHashNote(next_note)
      i+=l

    # print notes
    self.generated_song = notes
    return

  def WriteToFile(self, song, filename="temp.song.swp"):
    print "Writing a copy to %s"%filename
    f = open(filename, "w")
    l = 0
    for (s, r) in song:
      f.write(s.ljust(3))
      l += 1
      if l%16 == 0:
        f.write("\n")

      for i in range(r-1):
        f.write(",".ljust(3))
        l += 1
        if l%16 == 0:
          f.write("\n")

    f.close()
    return

  def GetGeneratedSong(self, filename):
    song = [self.UnHashNote(n) for n in self.generated_song]
    # print song
    print filename
    self.WriteToFile(song, filename)
    return song

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<link rel="stylesheet" type="text/css" href="tools/zcode2js.css">
	<title>zcode</title>

zcode

Playing any Z-machine story on Parchment is pretty easy, thanks to a simple web service located at <tt>zcode.appspot.com</tt> that converts a Z-code file located anywhere on the internet to a JSONP representation that Parchment can understand.

Simply upload the Z-code file to a server and enter the URL to the story in the field below.

<input id="url-entry" type="text" size="60">

The link for playing your story is:

Alternatively, you can also convert the Z-code to JavaScript yourself instead of relying on <tt>zcode.appspot.com</tt> by using zcode2js.


text:
<?php

use yii\db\Schema;
use yii\db\Migration;

class m150615_182718_create_table__form2_form_property_enum extends Migration
{
    public function safeUp()
    {
        $tableExist = $this->db->getTableSchema("{{%form2_form_property_enum}}", true);
        if ($tableExist)
        {
            return true;
        }

        $tableOptions = null;
        if ($this->db->driverName === 'mysql') {
            $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB';
        }

        $this->createTable("{{%form2_form_property_enum}}", [
            'id'                    => Schema::TYPE_PK,

            'created_by'            => Schema::TYPE_INTEGER . ' NULL',
            'updated_by'            => Schema::TYPE_INTEGER . ' NULL',

            'created_at'            => Schema::TYPE_INTEGER . ' NULL',
            'updated_at'            => Schema::TYPE_INTEGER . ' NULL',

            'property_id'           => Schema::TYPE_INTEGER . ' NULL',

            'value'                 => Schema::TYPE_STRING . '(255) NOT NULL',
            'def'                   => "CHAR(1) NOT NULL DEFAULT 'N'",
            'code'                  => Schema::TYPE_STRING. '(32) NOT NULL',
            'priority'              => Schema::TYPE_INTEGER. "(11) NOT NULL DEFAULT '500'",

        ], $tableOptions);

        $this->createIndex('form2_form_property_enum__updated_by', '{{%form2_form_property_enum}}', 'updated_by');
        $this->createIndex('form2_form_property_enum__created_by', '{{%form2_form_property_enum}}', 'created_by');
        $this->createIndex('form2_form_property_enum__created_at', '{{%form2_form_property_enum}}', 'created_at');
        $this->createIndex('form2_form_property_enum__updated_at', '{{%form2_form_property_enum}}', 'updated_at');

        $this->createIndex('form2_form_property_enum__property_id', '{{%form2_form_property_enum}}', 'property_id');
        $this->createIndex('form2_form_property_enum__def', '{{%form2_form_property_enum}}', 'def');
        $this->createIndex('form2_form_property_enum__code', '{{%form2_form_property_enum}}', 'code');
        $this->createIndex('form2_form_property_enum__priority', '{{%form2_form_property_enum}}', 'priority');
        $this->createIndex('form2_form_property_enum__value', '{{%form2_form_property_enum}}', 'value');

        $this->addForeignKey(
            'form2_form_property_enum_created_by', "{{%form2_form_property_enum}}",
            'created_by', '{{%cms_user}}', 'id', 'SET NULL', 'SET NULL'
        );

        $this->addForeignKey(
            'form2_form_property_enum_updated_by', "{{%form2_form_property_enum}}",
            'updated_by', '{{%cms_user}}', 'id', 'SET NULL', 'SET NULL'
        );

        $this->addForeignKey(
            'form2_form_property_enum_property_id', "{{%form2_form_property_enum}}",
            'property_id', '{{%form2_form_property}}', 'id', 'CASCADE', 'CASCADE'
        );
    }

    public function down()
    {
        echo "m150615_182718_create_table__form2_form_property_enum cannot be reverted.\n";
        return false;
    }
}


text:
package org.lamport.tla.toolbox.tool.tlc.ui.dialog;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.CheckboxTableViewer;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.lamport.tla.toolbox.tool.tlc.output.data.TLCVariable;

/**
 * The genesis of this dialog is https://github.com/tlaplus/tlaplus/issues/274 and then further modified to support
 * https://github.com/tlaplus/tlaplus/issues/360
 */
public class ErrorViewTraceFilterDialog extends Dialog {
	public enum MutatedFilter {
		NO_FILTER, CHANGED_ALL_FRAMES, CHANGED_CHANGED_FRAMES;
	}

	private static final String[] MUTATED_VARIABLE_SELECTIONS = { "Show all variables",
																  "Show only changed variables",
																  "Show only changed variables in changed frames" };

	private CheckboxTableViewer tableViewer;

	private final List<TLCVariable> variables;
	private final HashSet<TLCVariable> selection;

	private Combo mutatedVariablesCombo;
	private MutatedFilter selectedFilter;

	/**
	 * @param parentShell
	 * @param variableList a copy of this list will be made
	 */
	public ErrorViewTraceFilterDialog(final Shell parentShell, final List<TLCVariable> variableList) {
		super(parentShell);

		variables = new ArrayList<>(variableList);
		selection = new HashSet<>();
	}

	public Set<TLCVariable> getSelection() {
		return selection;
	}

	public void setSelection(final Set<TLCVariable> newSelection) {
		selection.clear();

		if ((newSelection == null) || (newSelection.size() == 0)) {
			return;
		}

		selection.addAll(newSelection);
		if (tableViewer != null) {
			tableViewer.setAllChecked(false);
			selection.stream().forEach((element) -> tableViewer.setChecked(element, true));
		}
	}

	public MutatedFilter getMutatedFilterSelection() {
		return selectedFilter;
	}

    @Override
    protected final Control createDialogArea(final Composite parent) {
    	final Composite container = (Composite) super.createDialogArea(parent);
    	GridLayout gl = new GridLayout(2, false);
    	gl.verticalSpacing = 9;
    	container.setLayout(gl);

    	Label l = new Label(container, SWT.LEFT);
    	l.setText("Selected variables and expressions will be hidden from the error trace.");
    	l.setFont(JFaceResources.getFontRegistry().get(JFaceResources.DIALOG_FONT));
    	GridData gd = new GridData();
    	gd.horizontalSpan = 2;
    	l.setLayoutData(gd);

    	tableViewer = CheckboxTableViewer.newCheckList(container, SWT.BORDER | SWT.V_SCROLL | SWT.SINGLE);
    	tableViewer.setContentProvider(new ArrayContentProvider());
    	tableViewer.setLabelProvider(new ColumnLabelProvider() {
    		@Override
    		public String getText(final Object element) {
    			return ((TLCVariable)element).getName();
    		}
    	});
    	tableViewer.setInput(variables);
		selection.stream().forEach((element) -> tableViewer.setChecked(element, true));
    	gd = new GridData();
    	gd.horizontalAlignment = SWT.FILL;
    	gd.grabExcessHorizontalSpace = true;
    	gd.minimumWidth = 333;
    	tableViewer.getTable().setLayoutData(gd);

    	final Composite buttonPane = new Composite(container, SWT.NONE);
    	gl = new GridLayout(1, false);
    	buttonPane.setLayout(gl);

    	Button b = new Button(buttonPane, SWT.PUSH);
    	b.setText("Select All");
    	gd = new GridData();
    	gd.horizontalAlignment = SWT.FILL;
    	gd.grabExcessHorizontalSpace = true;
    	b.setLayoutData(gd);
    	b.addSelectionListener(new SelectionAdapter() {
    		@Override
    		public void widgetSelected(final SelectionEvent se) {
    			tableViewer.setAllChecked(true);
    		}
    	});

    	b = new Button(buttonPane, SWT.PUSH);
    	b.setText("Deselect All");
    	gd = new GridData();
    	gd.horizontalAlignment = SWT.FILL;
    	gd.grabExcessHorizontalSpace = true;
    	b.setLayoutData(gd);
    	b.addSelectionListener(new SelectionAdapter() {
    		@Override
    		public void widgetSelected(final SelectionEvent se) {
    			tableViewer.setAllChecked(false);
    		}
    	});

    	final Composite mutatedVariablesComboPane = new Composite(container, SWT.NONE);
    	gd = new GridData();
    	gd.horizontalAlignment = SWT.FILL;
    	gd.grabExcessHorizontalSpace = true;
    	gd.horizontalSpan = 2;
    	mutatedVariablesComboPane.setLayoutData(gd);
    	gl = new GridLayout(2, false);
    	mutatedVariablesComboPane.setLayout(gl);

    	l = new Label(mutatedVariablesComboPane, SWT.LEFT);
    	l.setText("Filter by change:");
    	l.setFont(JFaceResources.getFontRegistry().get(JFaceResources.DIALOG_FONT));

    	mutatedVariablesCombo = new Combo(mutatedVariablesComboPane, SWT.READ_ONLY);
    	mutatedVariablesCombo.setItems(MUTATED_VARIABLE_SELECTIONS);
    	gd = new GridData();
    	gd.horizontalAlignment = SWT.FILL;
    	gd.grabExcessHorizontalSpace = true;
    	mutatedVariablesCombo.setLayoutData(gd);
    	mutatedVariablesCombo.setText(MUTATED_VARIABLE_SELECTIONS[0]);

        return container;
    }

    @Override
    protected void okPressed() {
    	selection.clear();

		Arrays.stream(tableViewer.getCheckedElements()).forEach((element) -> selection.add((TLCVariable)element));
		selectedFilter = MutatedFilter.values()[mutatedVariablesCombo.getSelectionIndex()];

        super.okPressed();
    }

    @Override
    protected void createButtonsForButtonBar(Composite parent) {
        createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true);
    }

	@Override
	protected void configureShell(Shell shell) {
		super.configureShell(shell);
		shell.setText("Error Trace Filter");
	}
}


text:
import React, { Component } from 'react';
import { View, Text } from 'react-native';

class EditContact extends Component {
    render() {
        return (
            <View style={{
                flex: 1,
                justifyContent: 'center',
                alignItems: 'center',
            }}>
                <Text>EditContact</Text>
            </View>
        );
    }
}

export default EditContact;


text:
import rospy
import math
from std_msgs.msg import *
from sensor_msgs.msg import *
import tf
import threading
from tf.transformations import *
from transformation_helper import *
from geometry_msgs.msg import *
import hubo_robot_msgs.msg as hrms
import hubo_sensor_msgs.srv as hsss
import dynamixel_msgs.msg as dmms

class LaserPointCloudGenerator:

    def __init__(self, tilt_controller_prefix, zero_tilt_position, max_tilt_position, min_tilt_position, laser_topic, laser_aggregation_service, target_angular_rate, error_threshold):
        self.zero_tilt_position = zero_tilt_position
        self.max_tilt_position = max_tilt_position
        self.min_tilt_position = min_tilt_position
        self.target_angular_rate = target_angular_rate
        self.error_threshold = error_threshold
        self.scan_lock = threading.Lock()
        self.active = False
        self.laser_scans = []
        self.last_tilt_state = None
        rospy.loginfo("Configuring LaserPointCloudGenerator...")
        rospy.loginfo("Setting up connection to LIDAR scan aggregator...")
        self.scan_processor = rospy.ServiceProxy(laser_aggregation_service, hsss.LidarAggregation)
        self.scan_processor.wait_for_service()
        rospy.loginfo("...connected to scan aggregator")
        rospy.loginfo("tilt_controller_prefix = " + tilt_controller_prefix)
        rospy.loginfo("laser_topic = " + laser_topic)
        self.tilt_subscriber = rospy.Subscriber(tilt_controller_prefix + "/state", dmms.JointState, self.tilt_state_cb)
        self.laser_scan_subscriber = rospy.Subscriber(laser_topic, LaserScan, self.laser_scan_cb)
        rospy.loginfo("Loaded subscribers to laser states")
        retry_rate = rospy.Rate(1.0)
        while (self.last_tilt_state == None and not rospy.is_shutdown()):
            rospy.loginfo("Waiting for state from laser tilt controller...")
            retry_rate.sleep()
        rospy.loginfo("...laser tilt controller ready")
        rospy.loginfo("Loading laser controller command publisher...")
        self.tilt_command_pub = rospy.Publisher(tilt_controller_prefix + "/command", Float64)
        rospy.loginfo("...Loaded command publisher")
        rospy.loginfo("...LaserScanController setup finished")

    def tilt_state_cb(self, msg):
        self.last_tilt_state = msg

    def laser_scan_cb(self, msg):
        with self.scan_lock:
            if (self.active):
                self.laser_scans.append(msg)

    def SelfTest(self):
        rospy.loginfo("Self-testing LaserScan Controller")
        zero_traj = self.BuildTrajectory(self.last_tilt_state.current_pos, self.zero_tilt_position, self.target_angular_rate)
        result = self.RunTrajectory(zero_traj)
        if (result):
            rospy.loginfo("Moved to zero position")
        else:
            rospy.logerr("Unable to zero")
            return result
        max_traj = self.BuildTrajectory(self.last_tilt_state.current_pos, self.max_tilt_position, self.target_angular_rate)
        result = self.RunTrajectory(max_traj)
        if (result):
            rospy.loginfo("Moved to max position")
        else:
            rospy.logerr("Unable to reach max position")
            return result
        min_traj = self.BuildTrajectory(self.last_tilt_state.current_pos, self.min_tilt_position, self.target_angular_rate)
        result = self.RunTrajectory(min_traj)
        if (result):
            rospy.loginfo("Moved to min position")
        else:
            rospy.logerr("Unable to reach min position")
            return result
        zero_traj = self.BuildTrajectory(self.last_tilt_state.current_pos, self.zero_tilt_position, self.target_angular_rate)
        result = self.RunTrajectory(zero_traj)
        if (result):
            rospy.loginfo("Self-test procedure complete")
        else:
            rospy.logerr("Unable to complete self-test")
        return result

    def Loop(self):
        while not rospy.is_shutdown():
            self.GeneratePointCloud()
        return False

    def GeneratePointCloud(self):
        # Bring LIDAR to MIN_ANGLE (actually the *top*)
        prep_traj = self.BuildTrajectory(self.last_tilt_state.current_pos, self.min_tilt_position, self.target_angular_rate)
        result = self.RunTrajectory(prep_traj)
        if (result):
            rospy.logdebug("Prep completed")
        else:
            rospy.logerr("Unable to reach prep angle")
            return
        # Flush and enable laser scan storage
        with self.scan_lock:
            self.laser_scans = []
            self.active = True
        # Sweep the LIDAR down to MAX_ANGLE
        scan_traj1 = self.BuildTrajectory(self.last_tilt_state.current_pos, self.max_tilt_position, self.target_angular_rate)
        result = self.RunTrajectory(scan_traj1)
        if (result):
            rospy.logdebug("scan_traj1 completed")
        else:
            rospy.logerr("Unable to complete scan_traj1")
            return
        # Sweep the LIDAR back up to MIN_ANGLE
        scan_traj2 = self.BuildTrajectory(self.last_tilt_state.current_pos, self.min_tilt_position, self.target_angular_rate)
        result = self.RunTrajectory(scan_traj2)
        if (result):
            rospy.logdebug("scan_traj2 completed")
        else:
            rospy.logerr("Unable to complete scan_traj2")
            return
        # Stop storing laser scans
        with self.scan_lock:
             self.active = False
        # Send the scans to the aggregator
        request = hsss.LidarAggregationRequest()
        request.Scans = self.laser_scans
        response = None
        try:
            response = self.scan_processor.call(request)
        except:
            rospy.logerr("Failed to process LIDAR scans to pointcloud")
        rospy.loginfo("GeneratePointCloud complete")

    def BuildTrajectory(self, start_tilt, end_tilt, angular_rate):
        steps_per_sec = 50.0
        steptime = 1.0 / steps_per_sec
        trajectory_states = []
        angle = abs(end_tilt - start_tilt)
        nominal_time = angle / angular_rate
        if (abs(angular_rate) > self.target_angular_rate):
            rospy.logerr("Commanded scan velocity (rad/s) is greater than limit")
            nominal_time = angle / self.target_angular_rate
        steps = int(math.ceil(nominal_time * steps_per_sec))
        if (steps == 1):
            return [[end_tilt, steptime]]
        elif (steps < 1):
            rospy.logwarn("Trajectory built has zero states")
            return []
        else:
            for step in range(steps):
                p = float(step) / float(steps - 1)
                tilt = ((end_tilt - start_tilt) * p) + start_tilt
                trajectory_states.append([tilt, steptime])
            return trajectory_states

    def RunTrajectory(self, trajectory, debug=False):
        if (debug):
            rospy.logwarn("Running in debug mode, trajectory will not execute")
            for state in trajectory:
                print state
            return False
        for [tilt, timestep] in trajectory:
            self.tilt_command_pub.publish(tilt)
            rospy.sleep(timestep)
        if (self.last_tilt_state.error > self.error_threshold):
            self.tilt_command_pub.publish(self.last_tilt_state.current_pos)
            return False
        else:
            return True

if __name__ == '__main__':
    rospy.init_node("drchubo_laser_generator")
    rospy.loginfo("Loading LaserPointCloudGenerator...")
    tilt_controller_prefix = rospy.get_param("~tilt_controller_prefix", "/lidar_tilt_controller")
    zero_tilt_position = rospy.get_param("~zero_tilt_position", 0.0)
    max_tilt_position = rospy.get_param("~max_tilt_position", (math.pi / 4.0))
    min_tilt_position = rospy.get_param("~min_tilt_position", -(math.pi / 4.0))
    target_angular_rate = rospy.get_param("~target_angular_rate", (math.pi / 8.0))
    error_threshold = rospy.get_param("~error_threshold", (math.pi / 36.0))
    laser_topic = rospy.get_param("~laser_topic", "laser_scan")
    laser_aggregation_service = rospy.get_param("~laser_aggregation_service", "laser_aggregation")
    LPCG = LaserPointCloudGenerator(tilt_controller_prefix, zero_tilt_position, max_tilt_position, min_tilt_position, laser_topic, laser_aggregation_service, target_angular_rate, error_threshold)
    retry_rate = rospy.Rate(1.0)
    result = False
    while not result and not rospy.is_shutdown():
        result = LPCG.SelfTest()
        retry_rate.sleep()
    result = False
    rospy.loginfo("Starting LaserPointCloudGenerator...")
    result = LPCG.Loop()
    if (not result):
        rospy.logwarn("LaserPointCloudGenerator stopped, attempting to safely shutdown")
    rospy.loginfo("...Operations complete, LaserPointCloudGenerator safed and shutdown")


text:
package tests;

import application.HttpSession;
import org.testng.Assert;
import org.testng.annotations.Test;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;

import static tests.TestBase.app;

/**
 * Created on 11/10/2017.
 * пробный тест чтоб проверить что логин под админом без браузера (через HTTP клиент)  работает

 */
public class LoginTests extends  TestBase {

    @Test
    //* * тест для проверки логин в мантис с креденшлс взятых с проперти-файла
    public void loginAsAdministrator() throws IOException {
        HttpSession session = app.newSession();// т.к. сессии очень легковесны без браузера они создаются напрямую в тесте,
        // это удобно когда нужно делать проверки зайдя под другим пользователем (тестером или девом или админом)

        boolean login = session.login(app.getProperty("web.AdminLogin"), app.getProperty("web.AdminPassword"));
        System.out.println("login "+ login);
        Assert.assertTrue(session.isLoggedInAs("administrator"), "строка поиска не найдена");

    }

    //* * тест для проверки логин в мантис с созданным юзером
    public void loginAsUser(String username, String password) throws IOException {
        HttpSession session = app.newSession();

        boolean login = session.login(username, password);
        System.out.println("login is "+ login);
        Assert.assertTrue(session.isLoggedInAs(username), "Проблема с логином - имя юзера на странице  не найдено!");

    }

}


text:
#pragma once
#include <aws/customer-profiles/CustomerProfiles_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/customer-profiles/model/ListProfileObjectTypeTemplateItem.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace CustomerProfiles
{
namespace Model
{
  class AWS_CUSTOMERPROFILES_API ListProfileObjectTypeTemplatesResult
  {
  public:
    ListProfileObjectTypeTemplatesResult();
    ListProfileObjectTypeTemplatesResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    ListProfileObjectTypeTemplatesResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

    /**
     *
The list of ListProfileObjectType template instances.

     */
    inline const Aws::Vector<ListProfileObjectTypeTemplateItem>& GetItems() const{ return m_items; }

    /**
     *
The list of ListProfileObjectType template instances.

     */
    inline void SetItems(const Aws::Vector<ListProfileObjectTypeTemplateItem>& value) { m_items = value; }

    /**
     *
The list of ListProfileObjectType template instances.

     */
    inline void SetItems(Aws::Vector<ListProfileObjectTypeTemplateItem>&& value) { m_items = std::move(value); }

    /**
     *
The list of ListProfileObjectType template instances.

     */
    inline ListProfileObjectTypeTemplatesResult& WithItems(const Aws::Vector<ListProfileObjectTypeTemplateItem>& value) { SetItems(value); return *this;}

    /**
     *
The list of ListProfileObjectType template instances.

     */
    inline ListProfileObjectTypeTemplatesResult& WithItems(Aws::Vector<ListProfileObjectTypeTemplateItem>&& value) { SetItems(std::move(value)); return *this;}

    /**
     *
The list of ListProfileObjectType template instances.

     */
    inline ListProfileObjectTypeTemplatesResult& AddItems(const ListProfileObjectTypeTemplateItem& value) { m_items.push_back(value); return *this; }

    /**
     *
The list of ListProfileObjectType template instances.

     */
    inline ListProfileObjectTypeTemplatesResult& AddItems(ListProfileObjectTypeTemplateItem&& value) { m_items.push_back(std::move(value)); return *this; }

    /**
     *
The pagination token from the previous ListObjectTypeTemplates API call.

     */
    inline const Aws::String& GetNextToken() const{ return m_nextToken; }

    /**
     *
The pagination token from the previous ListObjectTypeTemplates API call.

     */
    inline void SetNextToken(const Aws::String& value) { m_nextToken = value; }

    /**
     *
The pagination token from the previous ListObjectTypeTemplates API call.

     */
    inline void SetNextToken(Aws::String&& value) { m_nextToken = std::move(value); }

    /**
     *
The pagination token from the previous ListObjectTypeTemplates API call.

     */
    inline void SetNextToken(const char* value) { m_nextToken.assign(value); }

    /**
     *
The pagination token from the previous ListObjectTypeTemplates API call.

     */
    inline ListProfileObjectTypeTemplatesResult& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;}

    /**
     *
The pagination token from the previous ListObjectTypeTemplates API call.

     */
    inline ListProfileObjectTypeTemplatesResult& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;}

    /**
     *
The pagination token from the previous ListObjectTypeTemplates API call.

     */
    inline ListProfileObjectTypeTemplatesResult& WithNextToken(const char* value) { SetNextToken(value); return *this;}

  private:

    Aws::Vector<ListProfileObjectTypeTemplateItem> m_items;

    Aws::String m_nextToken;
  };

} // namespace Model
} // namespace CustomerProfiles
} // namespace Aws


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

<title>WengertJacobian</title>
<meta name="date" content="2017-01-04">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.drip.quant.calculus

Class WengertJacobian

java.lang.Object

org.drip.quant.calculus.WengertJacobian

public class WengertJacobian
extends java.lang.Object

WengertJacobian contains the Jacobian of the given set of Wengert variables to the set of parameters. It
        exposes the following functionality:
        - Set/Retrieve the Wengert variables
        - Accumulate the Partials
        - Scale the partial entries
        - Merge the Jacobian with another
        - Retrieve the WengertJacobian elements
        - Display the contents of the WengertJacobian

Author:

Lakshmi Krishnamurthy

Constructor Summary

Constructors

Constructor and Description

WengertJacobian(int iNumWengerts,
               int iNumParameters)

WengertJacobian constructor

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

boolean
accumulatePartialFirstDerivative(int iWengertIndex,
                                int iParameterIndex,
                                double dblDWengertDParameter)

Accumulate {D(Wengert)}/{D(Parameter)}

boolean
cumulativeMerge(WengertJacobian wjOther)

Accumulate and merge partial entries from the other CurveWengertJacobian

boolean
cumulativeMerge(WengertJacobian wjOther,
               double dblWeight)

Accumulate and merge the weighted partial entries from the other CurveWengertJacobian

java.lang.String
displayString()

Stringifies the contents of WengertJacobian

double
firstDerivative(int iWengertIndex,
               int iParameterIndex)

Retrieve {D(Wengert)}/{D(Parameter)} for the Wengert and the parameter identified by their indices

int
numParameters()

Retrieve the number of Parameters

int
numWengerts()

Retrieve the number of Wengert Variables

boolean
scale(double dblScale)

Scale the partial entries

boolean
setWengert(int iWengertIndex,
          double dblWengert)

Set the Value for the Wengert variable

double
wengert(int iIndex)

Get the Value for the Wengert Variable

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

WengertJacobian

public WengertJacobian(int iNumWengerts,
                       int iNumParameters)
                throws java.lang.Exception

WengertJacobian constructor

Parameters:

iNumWengerts - Number of Wengert variables

iNumParameters - Number of Parameters

Throws:

java.lang.Exception - Thrown if the inputs are invalid

Method Detail

numWengerts

public int numWengerts()

Retrieve the number of Wengert Variables

Returns:

Number of Wengert Variables

numParameters

public int numParameters()

Retrieve the number of Parameters

Returns:

Number of Parameters

setWengert

public boolean setWengert(int iWengertIndex,
                          double dblWengert)

Set the Value for the Wengert variable

Parameters:

iWengertIndex - Wengert Variable Index

dblWengert - The Value for the Wengert Variable

Returns:

TRUE - Successfully set

wengert

public double wengert(int iIndex)
               throws java.lang.Exception

Get the Value for the Wengert Variable

Parameters:

iIndex - Wengert Variable Index

Returns:

The Value for the Wengert variable

Throws:

java.lang.Exception - Thrown if the inputs are invalid

accumulatePartialFirstDerivative

public boolean accumulatePartialFirstDerivative(int iWengertIndex,
                                                int iParameterIndex,
                                                double dblDWengertDParameter)

Accumulate {D(Wengert)}/{D(Parameter)}

Parameters:

iWengertIndex - Wengert Variable Index

iParameterIndex - Parameter Index

dblDWengertDParameter - The incremental {D(Wengert)}/{D(Parameter)}

Returns:

TRUE - Successfully set

firstDerivative

public double firstDerivative(int iWengertIndex,
                              int iParameterIndex)

Retrieve {D(Wengert)}/{D(Parameter)} for the Wengert and the parameter identified by their indices

Parameters:

iWengertIndex - Wengert Variable Index

iParameterIndex - Parameter Index

Returns:

{D(Wengert)}/{D(Parameter)}

cumulativeMerge

public boolean cumulativeMerge(WengertJacobian wjOther)

Accumulate and merge partial entries from the other CurveWengertJacobian

Parameters:

wjOther - CurveWengertJacobian to be accumulated and merged

Returns:

TRUE - Successfully accumulated and merged

cumulativeMerge

public boolean cumulativeMerge(WengertJacobian wjOther,
                               double dblWeight)

Accumulate and merge the weighted partial entries from the other CurveWengertJacobian

Parameters:

wjOther - CurveWengertJacobian to be accumulated and merged

dblWeight - The Weight

Returns:

TRUE - Successfully accumulated and merged

scale

public boolean scale(double dblScale)

Scale the partial entries

Parameters:

dblScale - Factor by which the partials are to be scaled by

Returns:

TRUE - Scaling down successful

displayString

public java.lang.String displayString()

Stringifies the contents of WengertJacobian

Returns:

Stringified WengertJacobian

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
cordova-domready
=================

Fires _deviceready_ when running in Cordova; _domready_ otherwise. For use with [Component(1)](http://github.com/component/component).

## Usage

```js
var ready = require('cordova-domready');

/**
 * In Cordova: will fire on `ondeviceready`
 * Otherwise: will fire on DOM ready
 */
function onReady () {
  document.querySelector('body').innerHTML = '<h1>Device Ready!</h1>';
}

// register listener
ready(onReady);
```


text:
<?php

namespace common\tests\unit\provision\search;

use common\fixtures\helpers\IssueFixtureHelper;
use common\fixtures\helpers\ProvisionFixtureHelper;
use common\fixtures\helpers\SettlementFixtureHelper;
use common\fixtures\helpers\UserFixtureHelper;
use common\models\provision\ProvisionReportSearch;
use common\models\SearchModel;
use common\tests\_support\UnitSearchModelTrait;
use common\tests\unit\Unit;

/**
 * Class ProvisionReportSearchTest
 *
 * @property ProvisionReportSearch $model
 */
class ProvisionReportSearchTest extends Unit {

	use UnitSearchModelTrait;

	public function _before() {
		parent::_before();
		$this->model = $this->createModel();
	}

	public function _fixtures(): array {
		return array_merge(
			IssueFixtureHelper::issue(),
			IssueFixtureHelper::users(),
			SettlementFixtureHelper::pay(codecept_data_dir() . 'provision/'),
			SettlementFixtureHelper::settlement(codecept_data_dir() . 'provision/'),
			ProvisionFixtureHelper::type(),
			ProvisionFixtureHelper::provision(),
		);
	}

	public function testWithoutUser(): void {
		$this->tester->assertFalse($this->model->validate());
		$this->tester->assertSame('To User cannot be blank.', $this->model->getFirstError('to_user_id'));
		$this->tester->assertSame(0, $this->model->search([])->getTotalCount());
	}

	public function testBindToUserIdWithSearchParam(): void {
		$this->model->to_user_id = 1;
		$this->model->search(['to_user_id' => 2]);
		$this->tester->assertSame(1, $this->model->to_user_id);
	}

	public function testHasHiddenProvision(): void {
		$this->model->to_user_id = UserFixtureHelper::AGENT_PETER_NOWAK;
		$this->tester->assertTrue($this->model->hasHiddenProvisions());
	}

	protected function createModel(): SearchModel {
		return new ProvisionReportSearch([
			'defaultCurrentMonth' => false,
		]);
	}
}


text:
<!DOCTYPE html>
<meta charset="utf-8">


text:
cp -r src/lib/* build/lib/
cp -r src/decoder.json build/
rm -rf build/injections/*
mkdir -p build/src/injections

uglifyjs "build/global.js" --compress --screw-ie8 --define --keep-fnames -o build/global.js
for f in src/injections/*; do uglifyjs "build/global.js" "src/lib/jquery.js" $f --compress --screw-ie8 --define --stats --keep-fnames -o build/$f; done

cp -rp build/src/* build/
rm -rf build/src
rm -rf build/lib


text:
package org.apache.ignite.internal.managers.systemview.walker;

import org.apache.ignite.spi.systemview.view.SystemViewRowAttributeWalker;
import org.apache.ignite.spi.systemview.view.datastructures.ReentrantLockView;

/**
 * Generated by {@code org.apache.ignite.codegen.SystemViewRowAttributeWalkerGenerator}.
 * {@link ReentrantLockView} attributes walker.
 *
 * @see ReentrantLockView
 */
public class ReentrantLockViewWalker implements SystemViewRowAttributeWalker<ReentrantLockView> {
    /** {@inheritDoc} */
    @Override public void visitAll(AttributeVisitor v) {
        v.accept(0, "name", String.class);
        v.accept(1, "locked", boolean.class);
        v.accept(2, "hasQueuedThreads", boolean.class);
        v.accept(3, "failoverSafe", boolean.class);
        v.accept(4, "fair", boolean.class);
        v.accept(5, "broken", boolean.class);
        v.accept(6, "groupName", String.class);
        v.accept(7, "groupId", int.class);
        v.accept(8, "removed", boolean.class);
    }

    /** {@inheritDoc} */
    @Override public void visitAll(ReentrantLockView row, AttributeWithValueVisitor v) {
        v.accept(0, "name", String.class, row.name());
        v.acceptBoolean(1, "locked", row.locked());
        v.acceptBoolean(2, "hasQueuedThreads", row.hasQueuedThreads());
        v.acceptBoolean(3, "failoverSafe", row.failoverSafe());
        v.acceptBoolean(4, "fair", row.fair());
        v.acceptBoolean(5, "broken", row.broken());
        v.accept(6, "groupName", String.class, row.groupName());
        v.acceptInt(7, "groupId", row.groupId());
        v.acceptBoolean(8, "removed", row.removed());
    }

    /** {@inheritDoc} */
    @Override public int count() {
        return 9;
    }
}


text:
#include "Terrain.h"
#include "Mesh.h"

DC_BEGIN_DREEMCHEST

namespace Scene {

// --------------------------------------------------------------------- Terrain --------------------------------------------------------------------- //

// ** Terrain::kChunkSize
s32 Terrain::kChunkSize = 32;

// ** Terrain::kMaxSize
s32 Terrain::kMaxSize = 2048;

// ** Terrain::Terrain
Terrain::Terrain( u32 size )
    : m_heightmap( size ), m_maxHeight( static_cast<f32>( size ) )
{
    NIMBLE_BREAK_IF( (size % kChunkSize) != 0, "terrain size should be a multiple of chunk size" );
}

// ** Terrain::size
u32 Terrain::size( void ) const
{
    return m_heightmap.size();
}

// ** Terrain::maxHeight
f32 Terrain::maxHeight( void ) const
{
    return m_maxHeight;
}

// ** Terrain::chunkCount
u32 Terrain::chunkCount( void ) const
{
    return m_heightmap.size() / kChunkSize;
}

// ** Terrain::hasVertex
bool Terrain::hasVertex( s32 x, s32 z ) const
{
    bool invalid = x < 0 || z < 0 || x > static_cast<s32>( size() ) || z > static_cast<s32>( size() );
    return !invalid;
}

// ** Terrain::heightAtVertex
f32 Terrain::heightAtVertex( s32 x, s32 z ) const
{
    return f32( m_heightmap.height( x, z ) ) / m_heightmap.maxValue() * m_maxHeight;
}

// ** Terrain::height
f32 Terrain::height( f32 x, f32 z ) const
{
    if( x < 0.0f || x > size() ) return -1.0f;
    if( z < 0.0f || z > size() ) return -1.0f;

    // Convert to cell coordinates
    s32 hx = static_cast<s32>( floor( x ) );
    s32 hz = static_cast<s32>( floor( z ) );

    // Make sure that we are using right indices
    if( hx + 1 >= static_cast<s32>( size() ) ) hx--;
    if( hz + 1 >= static_cast<s32>( size() ) ) hz--;

    // Calculate the fraction values
    f32 fx = x - hx;
    f32 fz = z - hz;

    // Calculate interpolated terrain height
    f32 height = 0.0f;

    height += heightAtVertex( hx    , hz     ) * (1.0f - fx) * (1.0f - fz);
    height += heightAtVertex( hx + 1, hz     ) * (       fx) * (1.0f - fz);
    height += heightAtVertex( hx    , hz + 1 ) * (1.0f - fx) * (       fz);
    height += heightAtVertex( hx + 1, hz + 1 ) * (       fx) * (       fz);

    return height;
}

// ** Terrain::rayMarch
Vec3 Terrain::rayMarch( const Ray& ray, f32 epsilon ) const
{
    f32 dt        = 0.5f;
    f32 scalar    = 0.5f;
    f32 step    = 0.25f;
    Vec3 point;

    do {
        // Get the point on ray
        point = ray.origin() + ray.direction() * 1000.0f * scalar;

        // Get height at point
        f32 height = this->height( point.x, point.z );

        // Check the height difference, if it's less than epsilon - intersection point is found.
        if( fabs( height - point.y ) <= epsilon ) {
            break;
        }

        // Select the next segment of a ray based on height difference
        if( height < point.y ) {
            f32 newScalar = scalar + step;
            dt = newScalar - scalar;
            scalar = newScalar;
        }
        else if( height > point.y ) {
            f32 newScalar = scalar - step;
            dt = scalar - newScalar;
            scalar = newScalar;
        }

        step *= 0.5f;
    } while( dt >= 0.00001f );

    return point;
}

// ** Terrain::heightmap
const Heightmap& Terrain::heightmap( void ) const
{
    return m_heightmap;
}

// ** Terrain::heightmap
Heightmap& Terrain::heightmap( void )
{
    return m_heightmap;
}

// ** Terrain::chunkVertexBuffer
Array<Terrain::Vertex> Terrain::chunkVertexBuffer( u32 x, u32 z ) const
{
    NIMBLE_ABORT_IF( x >= chunkCount(), "invalid chunk coordinate" )
    NIMBLE_ABORT_IF( z >= chunkCount(), "invalid chunk coordinate" )

    // UV tiling
    f32 uvSize = 1.0f / m_heightmap.size();

    // Vertex stride
    s32 stride = kChunkSize + 1;

    // Construct vertex buffer
    Array<Vertex> vertices;
    vertices.resize( stride * stride );

    // Fill vertex buffer
    for( s32 i = 0; i <= kChunkSize; i++ ) {
        for( s32 j = 0; j <= kChunkSize; j++ ) {
            Vertex& vertex = vertices[i * stride + j];
            f32        height = heightAtVertex( x * kChunkSize + j, z * kChunkSize + i );

            vertex.position = Vec3( ( f32 )j, ( f32 )height, ( f32 )i );
            vertex.normal   = m_heightmap.normal( x * kChunkSize + j, z * kChunkSize + i );
            vertex.uv        = Vec2( vertex.position.x, vertex.position.z ) * uvSize;
        }
    }

    return vertices;
}

// ** Terrain::chunkIndexBuffer
Array<u16> Terrain::chunkIndexBuffer( void ) const
{
    // Index offset
    u16 idx = 0;

    // Vertex stride
    s32 stride = kChunkSize + 1;

    // Construct index buffer
    Array<u16> indices;
    indices.resize( stride * stride * 6 );

    // Fill index buffer
    for( s32 i = 0; i < kChunkSize; i++ ) {
        for( s32 j = 0; j < kChunkSize; j++ ) {
            indices[idx + 0] = (i    ) * stride + (j    );
            indices[idx + 1] = (i + 1) * stride + (j    );
            indices[idx + 2] = (i    ) * stride + (j + 1);

            indices[idx + 3] = (i    ) * stride + (j + 1);
            indices[idx + 4] = (i + 1) * stride + (j    );
            indices[idx + 5] = (i + 1) * stride + (j + 1);

            idx += 6;
        }
    }

    return indices;
}

// ** Terrain::createMesh
Mesh Terrain::createMesh( void ) const
{
    // Create an empty mesh
    Mesh mesh;

    // Set the number of mesh chunks
    mesh.setChunkCount( chunkCount() * chunkCount() );

    // Construct chunks
    u32 chunk = 0;

    for( u32 i = 0; i < chunkCount(); i++ ) {
        for( u32 j = 0; j < chunkCount(); j++ ) {
            // Get the chunk buffers
            VertexBuffer vertices = chunkVertexBuffer( i, j );
            IndexBuffer  indices  = chunkIndexBuffer();

            // Set chunk mesh
            setMeshChunk( mesh, chunk, vertices, indices, i * kChunkSize, j * kChunkSize );

            // Increase the chunk index
            chunk++;
        }
    }

    // Now update the mesh bounding box
    mesh.updateBounds();

    return mesh;
}

// ** Terrain::createChunkMesh
Mesh Terrain::createChunkMesh( u32 x, u32 z ) const
{
    // Create an empty mesh
    Mesh mesh;

    // Get the chunk buffers
    VertexBuffer vertices = chunkVertexBuffer( x, z );
    IndexBuffer  indices  = chunkIndexBuffer();

    // Set the number of mesh chunks
    mesh.setChunkCount( 1 );

    // Set the chunk data
    setMeshChunk( mesh, 0, vertices, indices );

    // Now update the mesh bounding box
    mesh.updateBounds();

    return mesh;
}

// ** Terrain::setMeshChunk
void Terrain::setMeshChunk( Mesh& mesh, u32 chunk, const VertexBuffer& vertices, const IndexBuffer& indices, u32 x, u32 z ) const
{
#if 0
    // Set the chunk data
    Mesh::VertexBuffer vb;
    vb.resize( vertices.size() );

    for( u32 i = 0, n = ( u32 )vertices.size(); i < n; i++ ) {
        vb[i].position = vertices[i].position + Vec3( x, 0, z );
        vb[i].normal = vertices[i].normal;
        vb[i].uv[0] = vertices[i].uv;
    }

    mesh.setVertexBuffer( vb );
    mesh.setIndexBuffer( indices );
#else
    NIMBLE_NOT_IMPLEMENTED
#endif
}

// --------------------------------------------------------------------- Heightmap ---------------------------------------------------------------------- //

// ** Heightmap::Heightmap
Heightmap::Heightmap( u32 size ) : m_size( size )
{
    // Allocate the heightmap.
    m_buffer.resize( (size + 1) * (size + 1) );
    memset( &m_buffer[0], 0, sizeof( u16 ) * m_buffer.size() );
}

// ** Heightmap::size
u32 Heightmap::size( void ) const
{
    return m_size;
}

// ** Heightmap::maxValue
Heightmap::Type Heightmap::maxValue( void ) const
{
    Type value = ~static_cast<Type>( 0 );
    NIMBLE_BREAK_IF( value <= 0, "invalid maximum value" );
    return value;
}

// ** Heightmap::height
Heightmap::Type Heightmap::height( u32 x, u32 z ) const
{
    NIMBLE_ABORT_IF( x > m_size || z > m_size, "index is out of range" );
    return m_buffer[z * (m_size + 1) + x];
}

// ** Heightmap::setHeight
void Heightmap::setHeight( u32 x, u32 z, Type value )
{
    NIMBLE_ABORT_IF( x > m_size || z > m_size, "index is out of range" );
    m_buffer[z * (m_size + 1) + x] = value;
}

// ** Heightmap::normal
Vec3 Heightmap::normal( u32 x, u32 z ) const
{
    // Compute the X gradient
    f32 dx = static_cast<f32>( height( x < m_size - 1 ? x + 1 : x, z ) - height( x > 0 ? x - 1 : x, z ) );

    if( x == 0 || x == m_size - 1 ) {
        dx *= 2;
    }

    // Compute the Z gradient
    f32 dz = static_cast<f32>( height( x, z < m_size-1 ? z + 1 : z ) - height( x, z > 0 ?  z - 1 : z ) );

    if( z == 0 || z == m_size - 1 ) {
        dz *= 2;
    }

    // Normalize
    Vec3 normal( -dx, 2.0f, dz );
    normal.normalize();

    return normal;
}

// ** Heightmap::set
void Heightmap::set( StrongPtr<Generator> generator )
{
    // Generate heightmap
    for( u32 z = 0; z <= m_size; z++ ) {
        for( u32 x = 0; x <= m_size; x++ ) {
            setHeight( x, z, generator->calculate( x, z ) );
        }
    }
}

} // namespace Scene

DC_END_DREEMCHEST


text:
Deutsch | Englisch | Bedeutung
------- | -------- | ---------
Archiv | archive | Unterteilt die Datenbank des Imagic IMS in mehrere Bereiche.
Arkivar | Arkivar | Name der Software welche wir entwickeln. Steht für Archivar auf Dänisch.
Bilder Tabelle | image table | Letzte Tabelle in der Hierarchie eines Archivs.
Continuous Delivery | Continuous Delivery | Praktiken, welche sicherstellen, dass jede Codeänderung automatisiert getestet und dadurch mit geringem Risiko ausgeliefert werden kann.
Continuous Deployment | Continuous Deployment | Erweiterung von Continuous Delivery, bei der jede Codeänderung sofort ausgeliefert wird.
Eintrag | Entry | Element innerhalb einer bestimmten Tabellen-Hierarchie.
Elternbildtabelle | Parent image table | Zweitletzte Tabelle in der Tabellen-Hierarchie eines Archivs.
Fall | case | Begriff der Polizei für eine Ebene im Imagic IMS, entspricht der Elternbildtabelle.
Feld | Metadata field | Daten (resp. Metadaten auf der Ebene Bilder Tabelle), welche zu einem Eintrag gespeichert werden.
Filter | Filter | Durch Berechtigungen eingeschränkte Sicht des Benutzers auf ein Archiv.
IMS Datenbank | IMS database | Datenspeicher des Imagic IMS.
IMS REST API | |  Programmierschnittstelle in das Imagic IMS nach dem Paradigma [Representational State Transfer](https://de.wikipedia.org/wiki/Representational_State_Transfer).
Imagic IMS | | Bildmanagement-System zur Erfassung, Bearbeitung, Speicherung, Visualisierung und Präsentation von digitalen Bildern, Filmen und allgemeinen Dokumenten für medizinische, industrielle und Verwaltungs-Institutionen.
Imagic | | Imagic Bildverarbeitung AG, Hersteller des Imagic IMS.
Mobile Client | | Synonym für Arkivar - die Software, welche wir entwickeln.
Mobilgeräteverwaltung | Mobile Device Management | Software zur zentralen Verwaltung von mobilen Geräten wie Smartphones im Unternehmen. Siehe auch [Wikipedia](https://de.wikipedia.org/wiki/Mobile-Device-Management).
PIC Systems | | PIC Systems AG, Partner von Imagic und spezialisiert auf den Polizeibereich.
REST API Eingangspunkt | REST API Endpoint | URL, welche die Navigation auf weitere IMS REST API Ressourcen erlaubt.
Store | | Apple Appstore oder Google Play Store.
Schlüsselwort | Keyword | Gültiger Wert eines Felds vom Typ *KeywordField*.
Tabelle | table | Gliedert das Archiv in hierarchisch geordnete Ebenen.
Test Charter | Test Charter | Leitfaden für eine explorative Testsession.
URL | URL | Uniform Resource Locator, Identifikator für eine Resource im Web, siehe auch [Wikipedia](https://de.wikipedia.org/wiki/Uniform_Resource_Identifier).
kann | nice-to-have | Optionale Anforderung, nach IEEE Std 830-1998.
muss | mandatory | Zwingende Anforderung, nach IEEE Std 830-1998.
soll | optional | Gewünschte Anforderung, nach IEEE Std 830-1998.


text:
# bat
Go implemented CLI cURL-like tool for humans. Bat can be used for testing, debugging, and generally interacting with HTTP servers.

Inspired by [Httpie](https://github.com/jakubroztocil/httpie). Thanks to the author, Jakub.

![](images/logo.png)

![](images/example.png)

- [Main Features](#main-features)
- [Installation](#installation)
- [Usage](#usage)
- [HTTP Method](#http-method)
- [Request URL](#request-url)
- [Request Items](#request-items)
- [JSON](#json)
- [Forms](#forms)
- [HTTP Headers](#http-headers)
- [Authentication](#authentication)
- [Proxies](#proxies)

## Docker

    # Build the docker image
	$ docker build -t astaxie/bat .

	# Run bat in a container
	$ docker run --rm -it --net=host astaxie/bat example.org

## Main Features

- Expressive and intuitive syntax
- Built-in JSON support
- Forms and file uploads
- HTTPS, proxies, and authentication
- Arbitrary request data
- Custom headers

## Installation

### Install with Modules - Go 1.11 or higher

If you only want to install the `bat` tool:

	go get -u github.com/astaxie/bat

If you want a mutable copy of source code:

	git clone https://github.com/astaxie/bat ;# clone outside of GOPATH
	cd bat
	go install

Make sure the `~/go/bin` is added into `$PATH`.

### Install without Modules - Before Go 1.11

	go get -u github.com/astaxie/bat

Make sure the `$GOPATH/bin` is added into `$PATH`.

## Usage

Hello World:

	$ bat beego.me

Synopsis:

	bat [flags] [METHOD] URL [ITEM [ITEM]]

See also `bat --help`.

### Examples

Basic settings - [HTTP method](#http-method), [HTTP headers](#http-headers) and [JSON](#json) data:

	$ bat PUT example.org X-API-Token:123 name=John

Any custom HTTP method (such as WebDAV, etc.):

	$ bat -method=PROPFIND example.org name=John

Submitting forms:

	$ bat -form=true POST example.org hello=World

See the request that is being sent using one of the output options:

	$ bat -print="Hhb" example.org

Use Github API to post a comment on an issue with authentication:

	$ bat -a USERNAME POST https://api.github.com/repos/astaxie/bat/issues/1/comments body='bat is awesome!'

Upload a file using redirected input:

	$ bat example.org < file.json

Download a file and save it via redirected output:

	$ bat example.org/file > file

Download a file wget style:

	$ bat -download=true example.org/file

Set a custom Host header to work around missing DNS records:

	$ bat localhost:8000 Host:example.com

Following is the detailed documentation. It covers the command syntax, advanced usage, and also features additional examples.

## HTTP Method
The name of the HTTP method comes right before the URL argument:

	$ bat DELETE example.org/todos/7

which looks similar to the actual Request-Line that is sent:

DELETE /todos/7 HTTP/1.1

When the METHOD argument is omitted from the command, bat defaults to either GET (if there is no request data) or POST (with request data).

## Request URL
The only information bat needs to perform a request is a URL. The default scheme is, somewhat unsurprisingly, http://, and can be omitted from the argument – `bat example.org` works just fine.

Additionally, curl-like shorthand for localhost is supported. This means that, for example :3000 would expand to http://localhost:3000 If the port is omitted, then port 80 is assumed.

	$ bat :/foo

	GET /foo HTTP/1.1
	Host: localhost

	$ bat :3000/bar

	GET /bar HTTP/1.1
	Host: localhost:3000

	$ bat :

	GET / HTTP/1.1
	Host: localhost

If you find yourself manually constructing URLs with query string parameters on the terminal, you may appreciate the `param=value` syntax for appending URL parameters so that you don't have to worry about escaping the & separators. To search for bat on Google Images you could use this command:

	$ bat GET www.google.com search=bat tbm=isch

	GET /?search=bat&tbm=isch HTTP/1.1

## Request Items
There are a few different request item types that provide a convenient mechanism for specifying HTTP headers, simple JSON and form data, files, and URL parameters.

They are key/value pairs specified after the URL. All have in common that they become part of the actual request that is sent and that their type is distinguished only by the separator used: `:`, `=`, `:=`, `@`, `=@`, and `:=@`. The ones with an `@` expect a file path as value.

|       Item Type         |	          Description           |
| ------------------------| ------------------------------ |
|HTTP Headers `Name:Value`|Arbitrary HTTP header, e.g. `X-API-Token:123`.|
|Data Fields `field=value`|Request data fields to be serialized as a JSON object (default), or to be form-encoded (--form, -f).|
|Form File Fields `field@/dir/file`|Only available with `-form`, `-f`. For example `screenshot@~/Pictures/img.png`. The presence of a file field results in a `multipart/form-data` request.|
|Form Fields from file `field=@file.txt`|read content from file as value|
|Raw JSON fields `field:=json`, `field:=@file.json`|Useful when sending JSON and one or more fields need to be a Boolean, Number, nested Object, or an Array, e.g., meals:='["ham","spam"]' or pies:=[1,2,3] (note the quotes).|

You can use `\` to escape characters that shouldn't be used as separators (or parts thereof). For instance, foo\==bar will become a data key/value pair (foo= and bar) instead of a URL parameter.

You can also quote values, e.g. `foo="bar baz"`.
## JSON
JSON is the lingua franca of modern web services and it is also the implicit content type bat by default uses:

If your command includes some data items, they are serialized as a JSON object by default. bat also automatically sets the following headers, both of which can be overridden:

| header       | value            |
| ------------ | ---------------- |
| Content-Type | application/json |
| Accept       | application/json |

You can use --json=true, -j=true to explicitly set Accept to `application/json` regardless of whether you are sending data (it's a shortcut for setting the header via the usual header notation – `bat url Accept:application/json`).

Simple example:

	$ bat PUT example.org name=John email=john@example.org
	PUT / HTTP/1.1
	Accept: application/json
	Accept-Encoding: gzip, deflate
	Content-Type: application/json
	Host: example.org

	{
	    "name": "John",
	    "email": "john@example.org"
	}

Even custom/vendored media types that have a json format are getting detected, as long as they implement a json type response and contain a `json` in their declared form:

	$ bat GET example.org/user/1 Accept:application/vnd.example.v2.0+json
	GET / HTTP/1.1
	Accept: application/vnd.example.v2.0+json
	Accept-Encoding: gzip, deflate
	Content-Type: application/vnd.example.v2.0+json
	Host: example.org

	{
	    "name": "John",
	    "email": "john@example.org"
	}

Non-string fields use the := separator, which allows you to embed raw JSON into the resulting object. Text and raw JSON files can also be embedded into fields using =@ and :=@:

	$ bat PUT api.example.com/person/1 \
    name=John \
    age:=29 married:=false hobbies:='["http", "pies"]' \  # Raw JSON
    description=@about-john.txt \   # Embed text file
    bookmarks:=@bookmarks.json      # Embed JSON file

	PUT /person/1 HTTP/1.1
	Accept: application/json
	Content-Type: application/json
	Host: api.example.com

	{
	    "age": 29,
	    "hobbies": [
	        "http",
	        "pies"
	    ],
	    "description": "John is a nice guy who likes pies.",
	    "married": false,
	    "name": "John",
	    "bookmarks": {
	        "HTTPie": "http://httpie.org",
	    }
	}

Send JSON data stored in a file (see redirected input for more examples):

	$ bat POST api.example.com/person/1 < person.json

## Forms
Submitting forms are very similar to sending JSON requests. Often the only difference is in adding the `-form=true`, `-f` option, which ensures that data fields are serialized correctly and Content-Type is set to, `application/x-www-form-urlencoded; charset=utf-8`.

It is possible to make form data the implicit content type instead of JSON via the config file.

### Regular Forms

	$ bat -f=true POST api.example.org/person/1 name='John Smith' \
    email=john@example.org

	POST /person/1 HTTP/1.1
	Content-Type: application/x-www-form-urlencoded; charset=utf-8

	name=John+Smith&email=john%40example.org

### File Upload Forms

If one or more file fields is present, the serialization and content type is `multipart/form-data`:

	$ bat -f=true POST example.com/jobs name='John Smith' cv@~/Documents/cv.pdf

The request above is the same as if the following HTML form were submitted:

```
<form enctype="multipart/form-data" method="post" action="http://example.com/jobs">
    <input type="text" name="name" />
    <input type="file" name="cv" />
</form>
```

Note that `@` is used to simulate a file upload form field.

## HTTP Headers
To set custom headers you can use the Header:Value notation:

	$ bat example.org  User-Agent:Bacon/1.0  'Cookie:valued-visitor=yes;foo=bar'  \
    X-Foo:Bar  Referer:http://beego.me/

	GET / HTTP/1.1
	Accept: */*
	Accept-Encoding: gzip, deflate
	Cookie: valued-visitor=yes;foo=bar
	Host: example.org
	Referer: http://beego.me/
	User-Agent: Bacon/1.0
	X-Foo: Bar

There are a couple of default headers that bat sets:

	GET / HTTP/1.1
	Accept: */*
	Accept-Encoding: gzip, deflate
	User-Agent: bat/<version>
	Host: <taken-from-URL>

Any of the default headers can be overridden.

# Authentication
Basic auth:

	$ bat -a=username:password example.org

# Proxies
You can specify proxies to be used through the --proxy argument for each protocol (which is included in the value in case of redirects across protocols):

	$ bat --proxy=http://10.10.1.10:3128 example.org

With Basic authentication:

	$ bat --proxy=http://user:pass@10.10.1.10:3128 example.org

You can also configure proxies by environment variables HTTP_PROXY and HTTPS_PROXY, and the underlying Requests library will pick them up as well. If you want to disable proxies configured through the environment variables for certain hosts, you can specify them in NO_PROXY.

In your ~/.bash_profile:

	export HTTP_PROXY=http://10.10.1.10:3128
	export HTTPS_PROXY=https://10.10.1.10:1080
	export NO_PROXY=localhost,example.com


text:
/**
 * Calculates the sum of the array
 * @augments Math
 *
 * @param {Number[]}
 * @return {Number}
 */
Math.sum = function( inArray ) {

	var sum = 0;

	for( var i = 0; i < inArray.length; i++ ) {

		sum += inArray[i];
	}

	return sum;
},

/**
 * Calculates the average of the array
 * @augments Math
 *
 * @param {Number[]}
 * @return {Number}
 */
Math.mean = function( inArray ) {

	return ( inArray.length > 0 ) ? ( this.sum( inArray ) / inArray.length ) : false;
},

/**
 * Calculates the median of the array
 * @see Median - Wikipedia.
 * @augments Math
 *
 * @param {Number[]}
 * @return {Number}
 */
Math.median = function( inArray ) {

	if( inArray.length <= 0 ) {

		return false;
	}

	inArray = this.sort( inArray );

	if( inArray.length.isEven() ) {

		return this.mean( [inArray[inArray.length / 2 - 1], inArray[inArray.length / 2]] );
	} else {

		return inArray[( inArray.length / 2 ).floor()];
	}
},

/**
 * Calculates the measure of how far a set of numbers are spread out from each other
 * @see Variance - Wikipedia.
 * @augments Math
 *
 * @param {Number[]}
 * @return {Number}
 */
Math.variance = function( inArray ) {

	if( inArray.length <= 0 ) return false;

	var mean = this.mean( inArray );
	var dev = [];

	for( var i = 0; i < inArray.length; i++ ) {

		dev.push( this.pow( ( inArray[i] - mean ), 2 ) );
	}

	return this.mean( dev );
},

/**
 * Calculates how much variation there is from the average
 * @see Standard Deviation - Wikipedia.
 * @augments Math
 *
 * @param {Number[]}
 * @return {Number}
 */
Math.stdDev = function( inArray ) {

	return this.sqrt( this.variance( inArray ) );
},

/**
 * Hyperbolic sine
 * @see Hyperbolic Function - Wikipedia.
 * @augments Math
 *
 * @param {Number}
 * @return {Number}
 */
Math.sinh = function( n ) {

	return ( this.exp( n ) - this.exp( -n ) ) / 2;
},

/**
 * Hyperbolic cosine
 * @see Hyperbolic Function - Wikipedia.
 * @augments Math
 *
 * @param {Number}
 * @return {Number}
 */
Math.cosh = function( n ) {

	return ( this.exp( n ) + this.exp( -n ) ) / 2;
},

/**
 * Hyperbolic tangent
 * @see Hyperbolic Function - Wikipedia.
 * @augments Math
 *
 * @param {Number}
 * @return {Number}
 */
Math.tanh = function( n ) {

	return this.sinh( n ) / this.cosh( n );
},

/**
 * Hyperbolic cotangent
 * @see Hyperbolic Function - Wikipedia.
 * @augments Math
 *
 * @param {Number}
 * @return {Number}
 */
Math.coth = function( n ) {

	return this.cosh( n ) / this.sinh( n );
},

/**
 * Hyperbolic secant
 * @see Hyperbolic Function - Wikipedia.
 * @augments Math
 *
 * @param {Number}
 * @return {Number}
 */
Math.sech = function( n ) {

	return 2 / ( this.exp( n ) + this.exp( -n ) );
},

/**
 * Hyperbolic cosecant
 * @see Hyperbolic Function - Wikipedia.
 * @augments Math
 *
 * @param {Number}
 * @return {Number}
 */
Math.csch = function( n ) {

	return 2 / ( this.exp( n ) - this.exp( -n ) );
},

/**
 * Sorts the array numerically
 * @augments Math
 *
 * @param {Number[]}
 * @param {boolean} [desc] True for descending numerical order
 * @return {Number[]}
 */
Math.sort = function( inArray, desc ) {

	return inArray.clone().sort(
			function( a, b ) {

				return desc ? b - a : a - b
			}
		);
}


text:
class DateTimePickerInput < SimpleForm::Inputs::Base
  def input
    template.content_tag(:div, class: 'row') do
      template.content_tag(:div, class: 'col-sm-5') do
        template.content_tag(:div, class: 'form-group') do
          template.content_tag(:div, class: 'input-group date', id: "datetimepicker_#{options[:time]}") do
            template.concat @builder.text_field(attribute_name, input_html_options)
            template.concat span_remove
          end
        end
      end
    end
  end

  def input_html_options
    super.merge(class: 'form-control', type: 'text')
  end

  def span_remove
    template.content_tag(:span, class: 'input-group-addon') do
      template.content_tag(:span, nil, class: 'glyphicon glyphicon-calendar')
    end
  end
end


text:
package com.epam.reportportal.auth.integration.handler.impl;

import com.epam.reportportal.auth.integration.AuthIntegrationType;
import com.epam.reportportal.auth.integration.converter.ActiveDirectoryConverter;
import com.epam.reportportal.auth.integration.handler.GetAuthIntegrationStrategy;
import com.epam.ta.reportportal.dao.IntegrationRepository;
import com.epam.ta.reportportal.dao.IntegrationTypeRepository;
import com.epam.ta.reportportal.entity.integration.Integration;
import com.epam.ta.reportportal.entity.integration.IntegrationType;
import com.epam.ta.reportportal.exception.ReportPortalException;
import com.epam.ta.reportportal.ws.model.ErrorType;
import com.epam.ta.reportportal.ws.model.integration.auth.ActiveDirectoryResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author Ivan Budayeu
 */
@Service
public class GetActiveDirectoryStrategy implements GetAuthIntegrationStrategy {

	private final IntegrationTypeRepository integrationTypeRepository;

	private final IntegrationRepository integrationRepository;

	@Autowired
	public GetActiveDirectoryStrategy(IntegrationTypeRepository integrationTypeRepository, IntegrationRepository integrationRepository) {
		this.integrationTypeRepository = integrationTypeRepository;
		this.integrationRepository = integrationRepository;
	}

	@Override
	public ActiveDirectoryResource getIntegration() {
		IntegrationType adIntegrationType = integrationTypeRepository.findByName(AuthIntegrationType.ACTIVE_DIRECTORY.getName())
				.orElseThrow(() -> new ReportPortalException(ErrorType.AUTH_INTEGRATION_NOT_FOUND,
						AuthIntegrationType.ACTIVE_DIRECTORY.getName()
				));
		//or else empty integration with default 'enabled = false' flag
		ActiveDirectoryResource adResource = ActiveDirectoryConverter.TO_RESOURCE.apply(integrationRepository.findByNameAndTypeIdAndProjectIdIsNull(
				AuthIntegrationType.ACTIVE_DIRECTORY.getName(),
				adIntegrationType.getId()
		).orElseGet(Integration::new));
		adResource.setType(adIntegrationType.getName());
		return adResource;
	}
}


text:
#ifndef __SOT_SOT_HH
#define __SOT_SOT_HH

/* --------------------------------------------------------------------- */
/* --- INCLUDE --------------------------------------------------------- */
/* --------------------------------------------------------------------- */

/* Matrix */
#include <dynamic-graph/linear-algebra.h>

/* Classes standards. */
#include <list> /* Classe std::list   */

/* SOT */
#include <dynamic-graph/entity.h>

#include <sot/core/flags.hh>
#include <sot/core/task-abstract.hh>

/* --------------------------------------------------------------------- */
/* --- API ------------------------------------------------------------- */
/* --------------------------------------------------------------------- */

#ifndef SOTSOT_CORE_EXPORT
#if defined(WIN32)
#if defined(sot_EXPORTS)
#define SOTSOT_CORE_EXPORT __declspec(dllexport)
#else
#define SOTSOT_CORE_EXPORT __declspec(dllimport)
#endif
#else
#define SOTSOT_CORE_EXPORT
#endif
#endif

/* --------------------------------------------------------------------- */
/* --- CLASS ----------------------------------------------------------- */
/* --------------------------------------------------------------------- */

namespace dynamicgraph {
namespace sot {

/*! @ingroup stackoftasks
  \brief This class implements the Stack of Task.
  It allows to deal with the priority of the controllers
  through the shell.
*/
class SOTSOT_CORE_EXPORT Sot : public Entity {
 public:
  /*! \brief Specify the name of the class entity. */
  static const std::string CLASS_NAME;

 public:
  /*! \brief Returns the name of this class. */
  virtual const std::string &getClassName() const { return CLASS_NAME; }

  /*! \brief Defines a type for a list of tasks */
  typedef std::list<TaskAbstract *> StackType;

 protected:
  /*! \brief This field is a list of controllers
    managed by the stack of tasks. */
  StackType stack;

  /*! \brief Store the number of joints to be used in the
    command computed by the stack of tasks. */
  unsigned int nbJoints;

  /*! \brief Option to disable the computation of the SVD for the last task
    if this task is a Task with a single FeaturePosture */
  bool enablePostureTaskAcceleration;

  /*! \brief Maximum allowed squared norm of control increment.
    A task whose control increment is above this value is discarded.
    It defaults to \c std::numeric_limits<double>::max().
    \warning This is a security feature and is **not** a good way of adding a
    proper constraint on the control generated by SoT.
    */
  double maxControlIncrementSquaredNorm;

 public:
  /*! \brief Threshold to compute the dumped pseudo inverse. */
  static const double INVERSION_THRESHOLD_DEFAULT;  // = 1e-4;

  /*   static const double DIRECTIONAL_THRESHOLD_DEFAULT = 1e-2; */
  /*   static const bool USE_CONTI_INVERSE_DEFAULT = false; */

  /*! \brief Number of joints by default. */
  static void taskVectorToMlVector(const VectorMultiBound &taskVector,
                                   Vector &err);

 public:
  /*! \brief Default constructor */
  Sot(const std::string &name);
  ~Sot(void) { /* TODO!! */
  }

  /*! \name Methods to handle the stack.
    @{
  */
  virtual const StackType &tasks() const { return stack; }

  /*! \brief Push the task in the stack.
    It has a lowest priority than the previous ones.
    If this is the first task, then it has the highest
    priority. */
  virtual void push(TaskAbstract &task);
  /*! \brief Pop the task from the stack.
    This method removes the task with the smallest
    priority in the task. The other are projected
    in the null-space of their predecessors. */
  virtual TaskAbstract &pop(void);

  /*! \brief This method allows to know if a task exists or not */
  virtual bool exist(const TaskAbstract &task);

  /*! \brief Remove a task regardless to its position in the stack.
    It removes also the signals connected to the output signal of this
    stack.*/
  virtual void remove(const TaskAbstract &task);

  /*! \brief This method removes the output signals depending on
      this task. */
  virtual void removeDependency(const TaskAbstract &key);

  /*! \brief This method makes the task to swap with the task having the
    immediate superior priority. */
  virtual void up(const TaskAbstract &task);

  /*! \brief This method makes the task to swap with the task having the
    immediate inferior priority. */
  virtual void down(const TaskAbstract &task);

  /*! \brief Remove all the tasks from the stack. */
  virtual void clear(void);
  /*! @} */

  /*! @} */

  /*! \brief This method defines the part of the state vector
    which correspond to the free flyer of the robot. */
  virtual void defineNbDof(const unsigned int &nbDof);
  virtual const unsigned int &getNbDof() const { return nbJoints; }

  /*! @} */
 public: /* --- CONTROL --- */
  /*! \name Methods to compute the control law following the
    recursive definition of the stack of tasks.
    @{
  */

  /*! \brief Compute the control law. */
  virtual dynamicgraph::Vector &computeControlLaw(dynamicgraph::Vector &control,
                                                  const int &time);

  /*! @} */

 public: /* --- DISPLAY --- */
  /*! \name Methods to display the stack of tasks.
    @{
  */
  /*! Display the stack of tasks in text mode as a tree. */
  virtual void display(std::ostream &os) const;
  /*! Wrap the previous method around an operator. */
  SOTSOT_CORE_EXPORT friend std::ostream &operator<<(std::ostream &os,
                                                     const Sot &sot);
  /*! @} */
 public: /* --- SIGNALS --- */
  /*! \name Methods to handle signals
    @{
  */
  /*! \brief Intrinsec velocity of the robot, that is used to initialized
   * the recurence of the SOT (e.g. velocity coming from the other
   * OpenHRP plugins).
   */
  SignalPtr<dynamicgraph::Vector, int> q0SIN;
  /*! \brief A matrix K whose columns are a base of the desired velocity.
   * In other words, \f$ \dot{q} = K * u \f$ where \f$ u \f$ is the free
   * parameter to be computed.
   * \note K should be an orthonormal matrix.
   */
  SignalPtr<dynamicgraph::Matrix, int> proj0SIN;
  /*! \brief This signal allow to change the threshold for the
    damped pseudo-inverse on-line */
  SignalPtr<double, int> inversionThresholdSIN;
  /*! \brief Allow to get the result of the computed control law. */
  SignalTimeDependent<dynamicgraph::Vector, int> controlSOUT;
  /*! @} */

  /*! \brief This method write the priority between tasks in the output stream
   * os. */
  virtual std::ostream &writeGraph(std::ostream &os) const;
};
}  // namespace sot
}  // namespace dynamicgraph

#endif /* #ifndef __SOT_SOT_HH */


text:
"""
Support for Wink fans.

For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/fan.wink/
"""
import asyncio
import logging

from homeassistant.components.fan import (FanEntity, SPEED_HIGH,
                                          SPEED_LOW, SPEED_MEDIUM,
                                          STATE_UNKNOWN, SUPPORT_SET_SPEED,
                                          SUPPORT_DIRECTION)
from homeassistant.helpers.entity import ToggleEntity
from homeassistant.components.wink import WinkDevice, DOMAIN

DEPENDENCIES = ['wink']

_LOGGER = logging.getLogger(__name__)

SPEED_LOWEST = 'lowest'
SPEED_AUTO = 'auto'

SUPPORTED_FEATURES = SUPPORT_DIRECTION + SUPPORT_SET_SPEED

def setup_platform(hass, config, add_devices, discovery_info=None):
    """Set up the Wink platform."""
    import pywink

    for fan in pywink.get_fans():
        if fan.object_id() + fan.name() not in hass.data[DOMAIN]['unique_ids']:
            add_devices([WinkFanDevice(fan, hass)])

class WinkFanDevice(WinkDevice, FanEntity):
    """Representation of a Wink fan."""

    @asyncio.coroutine
    def async_added_to_hass(self):
        """Callback when entity is added to hass."""
        self.hass.data[DOMAIN]['entities']['fan'].append(self)

    def set_direction(self: ToggleEntity, direction: str) -> None:
        """Set the direction of the fan."""
        self.wink.set_fan_direction(direction)

    def set_speed(self: ToggleEntity, speed: str) -> None:
        """Set the speed of the fan."""
        self.wink.set_state(True, speed)

    def turn_on(self: ToggleEntity, speed: str=None, **kwargs) -> None:
        """Turn on the fan."""
        self.wink.set_state(True, speed)

    def turn_off(self: ToggleEntity, **kwargs) -> None:
        """Turn off the fan."""
        self.wink.set_state(False)

    @property
    def is_on(self):
        """Return true if the entity is on."""
        return self.wink.state()

    @property
    def speed(self) -> str:
        """Return the current speed."""
        current_wink_speed = self.wink.current_fan_speed()
        if SPEED_AUTO == current_wink_speed:
            return SPEED_AUTO
        if SPEED_LOWEST == current_wink_speed:
            return SPEED_LOWEST
        if SPEED_LOW == current_wink_speed:
            return SPEED_LOW
        if SPEED_MEDIUM == current_wink_speed:
            return SPEED_MEDIUM
        if SPEED_HIGH == current_wink_speed:
            return SPEED_HIGH
        return STATE_UNKNOWN

    @property
    def current_direction(self):
        """Return direction of the fan [forward, reverse]."""
        return self.wink.current_fan_direction()

    @property
    def speed_list(self: ToggleEntity) -> list:
        """Get the list of available speeds."""
        wink_supported_speeds = self.wink.fan_speeds()
        supported_speeds = []
        if SPEED_AUTO in wink_supported_speeds:
            supported_speeds.append(SPEED_AUTO)
        if SPEED_LOWEST in wink_supported_speeds:
            supported_speeds.append(SPEED_LOWEST)
        if SPEED_LOW in wink_supported_speeds:
            supported_speeds.append(SPEED_LOW)
        if SPEED_MEDIUM in wink_supported_speeds:
            supported_speeds.append(SPEED_MEDIUM)
        if SPEED_HIGH in wink_supported_speeds:
            supported_speeds.append(SPEED_HIGH)
        return supported_speeds

    @property
    def supported_features(self: ToggleEntity) -> int:
        """Flag supported features."""
        return SUPPORTED_FEATURES


text:
/* This file was generated by upbc (the upb compiler) from the input
 * file:
 *
 *     envoy/api/v2/route/route.proto
 *
 * Do not edit -- your changes will be discarded when the file is
 * regenerated. */

#ifndef ENVOY_API_V2_ROUTE_ROUTE_PROTO_UPB_H_
#define ENVOY_API_V2_ROUTE_ROUTE_PROTO_UPB_H_

#include "upb/generated_util.h"
#include "upb/msg.h"
#include "upb/decode.h"
#include "upb/encode.h"

/* Public Imports. */
#include "envoy/api/v2/route/route_components.upb.h"

#include "upb/port_def.inc"

#ifdef __cplusplus
extern "C" {
#endif

#ifdef __cplusplus
}  /* extern "C" */
#endif

#include "upb/port_undef.inc"

#endif  /* ENVOY_API_V2_ROUTE_ROUTE_PROTO_UPB_H_ */