text:
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2016, OpenNebula Project, OpenNebula Systems                */
/*                                                                            */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may    */
/* not use this file except in compliance with the License. You may obtain    */
/* a copy of the License at                                                   */
/*                                                                            */
/* http://www.apache.org/licenses/LICENSE-2.0                                 */
/*                                                                            */
/* Unless required by applicable law or agreed to in writing, software        */
/* distributed under the License is distributed on an "AS IS" BASIS,          */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   */
/* See the License for the specific language governing permissions and        */
/* limitations under the License.                                             */
/* -------------------------------------------------------------------------- */

#ifndef TRANSFER_MANAGER_H_
#define TRANSFER_MANAGER_H_

#include "MadManager.h"
#include "ActionManager.h"
#include "VirtualMachinePool.h"
#include "LifeCycleManager.h"
#include "TransferManagerDriver.h"

using namespace std;

extern "C" void * tm_action_loop(void *arg);

class VirtualMachineDisk;

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

class TMAction : public ActionRequest
{
public:
    enum Actions
    {
        PROLOG,
        PROLOG_MIGR,
        PROLOG_RESUME,
        PROLOG_ATTACH,
        EPILOG,
        EPILOG_LOCAL,
        EPILOG_STOP,
        EPILOG_DELETE,
        EPILOG_DELETE_PREVIOUS,
        EPILOG_DELETE_STOP,
        EPILOG_DELETE_BOTH,
        EPILOG_DETACH,
        CHECKPOINT,
        DRIVER_CANCEL,
        SAVEAS_HOT,
        SNAPSHOT_CREATE,
        SNAPSHOT_REVERT,
        SNAPSHOT_DELETE,
        RESIZE
    };

    TMAction(Actions a, int v):ActionRequest(ActionRequest::USER),
        _action(a), _vm_id(v){};

    TMAction(const TMAction& o):ActionRequest(o._type), _action(o._action),
        _vm_id(o._vm_id){};

    Actions action() const
    {
        return _action;
    }

    int vm_id() const
    {
        return _vm_id;
    }

    ActionRequest * clone() const
    {
        return new TMAction(*this);
    }

private:
    Actions _action;

    int     _vm_id;
};

class TransferManager : public MadManager, public ActionListener
{
public:

    TransferManager(
        VirtualMachinePool * _vmpool,
        HostPool *           _hpool,
        vector<const VectorAttribute*>& _mads):
            MadManager(_mads),
            vmpool(_vmpool),
            hpool(_hpool)
    {
        am.addListener(this);
    };

    ~TransferManager(){};

    /**
     *  Triggers specific actions to the Information Manager. This function
     *  wraps the ActionManager trigger function.
     *    @param action the IM action
     *    @param vid VM unique id. This is the argument of the passed to the
     *    invoked action.
     */
    void trigger(TMAction::Actions action, int vid)
    {
        TMAction tm_ar(action, vid);

        am.trigger(tm_ar);
    }

    void finalize()
    {
        am.finalize();
    }

    /**
     *  This functions starts the associated listener thread, and creates a
     *  new thread for the Information Manager. This thread will wait in
     *  an action loop till it receives ACTION_FINALIZE.
     *    @return 0 on success.
     */
    int start();

    /**
     *  Loads Virtual Machine Manager Mads defined in configuration file
     *   @param uid of the user executing the driver. When uid is 0 the nebula
     *   identity will be used. Otherwise the Mad will be loaded through the
     *   sudo application.
     */
    int load_mads(int uid);

    /**
     *  Gets the thread identification.
     *    @return pthread_t for the manager thread (that in the action loop).
     */
    pthread_t get_thread_id() const
    {
        return tm_thread;
    };

    /**
     * Inserts a transfer command in the xfs stream
     *
     * @param vm The VM
     * @param disk Disk to transfer
     * @param disk_index Disk index
     * @param system_tm_mad The Transfer Manager for the system datastore
     * @param opennebula_hostname The front-end hostname
     * @param xfr Stream where the transfer command will be written
     * @param error Error reason, if any
     *
     * @return 0 on success
     */
    int prolog_transfer_command(
            VirtualMachine *        vm,
            const VirtualMachineDisk* disk,
            string&                 system_tm_mad,
            string&                 opennebula_hostname,
            ostream&                xfr,
            ostringstream&          error);

    /**
     * Inserts a context command in the xfs stream
     *
     * @param vm The VM
     * @param token_password Owner user's token password
     * @param system_tm_mad The Transfer Manager for the system datastore
     * @param disk_id of the context disk
     * @param xfr Stream where the transfer command will be written
     *
     * @return -1 in case of error, 0 if the VM has no context, 1 on success
     */
    int prolog_context_command(
            VirtualMachine *        vm,
            const string&           token_password,
            string&                 system_tm_mad,
            int&                    disk_id,
            ostream&                xfr);

    /**
     * Inserts a transfer command in the xfs stream
     *
     * @param vm The VM
     * @param host where the operation will be performed fe or host
     * @param disk Disk to transfer
     * @param disk_index Disk index
     * @param xfr Stream where the transfer command will be written
     */
    void epilog_transfer_command(
            VirtualMachine *        vm,
            const string&           host,
            const VirtualMachineDisk * disk,
            ostream&                xfr);
    /**
     * Inserts a transfer command in the xfs stream, for live migration
     *
     * @param vm The VM
     * @param xfr Stream where the transfer command will be written
     */
    void migrate_transfer_command(
        VirtualMachine *        vm,
        ostream&                xfr);

    /**
     *  This function generates the epilog_delete sequence for current,
     *  front-end and previous hosts.
     *    @param vm pointer to VM, locked
     *    @param xfr stream to write the commands
     *    @param local true to delete the front-end
     *    @param previous true to delete the previous host
     *
     *    @return 0 on success
     */
    int epilog_delete_commands(VirtualMachine *vm,
                               ostream&        xfr,
                               bool            local,
                               bool            previous);
    /**
     *  This function generates the TM command for the given snapshot action
     *    @param vm pointer to VM, locked
     *    @param snap_action: "SNAP_CREATE, SNAP_DELETE, SNAP_REVERT"
     *    @param xfr stream to write the commands
     *
     *    @return 0 on success
     */
    int snapshot_transfer_command(VirtualMachine * vm,
                                  const char * snap_action,
                                  ostream& xfr);

    /**
     *  Inserts a resize command in the xfr stream
     *    @param vm
     *    @param disk to resize
     *    @param xfr stream to include the command.
     */
    void resize_command(
            VirtualMachine *           vm,
            const VirtualMachineDisk * disk,
            ostream&                   xfr);
private:
    /**
     *  Thread id for the Transfer Manager
     */
    pthread_t               tm_thread;

    /**
     *  Pointer to the Virtual Machine Pool, to access VMs
     */
    VirtualMachinePool *    vmpool;

    /**
     *  Pointer to the Host Pool, to access hosts
     */
    HostPool *              hpool;

    /**
     *  Action engine for the Manager
     */
    ActionManager           am;

    /**
     *  Generic name for the TransferManager driver
     */
     static const char *  transfer_driver_name;

    /**
     *  Returns a pointer to a Transfer Manager driver.
     *    @param name of an attribute of the driver (e.g. its type)
     *    @param value of the attribute
     *    @return the TM driver owned by uid with attribute name equal to value
     *    or 0 in not found
     */
    const TransferManagerDriver * get(
        const string&   name,
        const string&   value)
    {
        return static_cast<const TransferManagerDriver *>
               (MadManager::get(0,name,value));
    };

    /**
     *  Returns a pointer to a Transfer Manager driver. The driver is
     *  searched by its name.
     *    @param name the name of the driver
     *    @return the TM driver owned by uid with attribute name equal to value
     *    or 0 in not found
     */
    const TransferManagerDriver * get(
        const string&   name)
    {
        string _name("NAME");
        return static_cast<const TransferManagerDriver *>
               (MadManager::get(0,_name,name));
    };

    /**
     *  Returns a pointer to a Transfer Manager driver. The driver is
     *  searched by its name.
     *    @return the TM driver for the Transfer Manager
     */
    const TransferManagerDriver * get()
    {
        string _name("NAME");
        return static_cast<const TransferManagerDriver *>
               (MadManager::get(0,_name,transfer_driver_name));
    };

    /**
     *  Function to execute the Manager action loop method within a new pthread
     * (requires C linkage)
     */
    friend void * tm_action_loop(void *arg);

    // -------------------------------------------------------------------------
    // Action Listener interface
    // -------------------------------------------------------------------------
    void finalize_action(const ActionRequest& ar)
    {
        NebulaLog::log("TM",Log::INFO,"Stopping Transfer Manager...");

        MadManager::stop();
    };

    void user_action(const ActionRequest& ar);

    /**
     *  This function starts the prolog sequence
     */
    void prolog_action(int vid);

    /**
     *  This function starts the prolog migration sequence
     */
    void prolog_migr_action(int vid);

    /**
     *  This function starts the prolog resume sequence
     */
    void prolog_resume_action(int vid);

    /**
     *  This function starts the prolog attach sequence
     */
    void prolog_attach_action(int vid);

    /**
     *  This function starts the epilog sequence
     */
    void epilog_action(bool local, int vid);

    /**
     *  This function starts the epilog_stop sequence
     */
    void epilog_stop_action(int vid);

    /**
     *  This function starts the epilog_delete sequence in the current host
     *    @param vid the Virtual Machine ID
     */
    void epilog_delete_action(int vid)
    {
        epilog_delete_action(false, vid);
    }

    /**
     *  This function starts the epilog_delete_stop sequence on the local host
     *  i.e. the front-end (the VM is not running)
     *    @param vid the Virtual Machine ID
     */
    void epilog_delete_stop_action(int vid)
    {
        epilog_delete_action(true, vid);
    }

    /**
     *  This function starts the epilog_delete sequence on the previous host
     *    @param vid the Virtual Machine ID
     */
    void epilog_delete_previous_action(int vid);

    /**
     *  This function starts the epilog_delete sequence on the current and
     *  previous hosts
     *    @param vid the Virtual Machine ID
     */
    void epilog_delete_both_action(int vid);

    /**
     *  This function starts the epilog_delete sequence
     */
    void epilog_delete_action(bool local, int vid);

    /**
     *  This function starts the epilog detach sequence
     */
    void epilog_detach_action(int vid);

    /**
     *  This function starts the epilog sequence
     */
    void checkpoint_action(int vid);

    /**
     * This function cancels the operation being performed by the driver
     */
    void driver_cancel_action(int vid);

    /**
     * This function starts the saveas of the given disk
     */
    void saveas_hot_action(int vid);

    /**
     * This function performs a generic snapshot action
     */
    void do_snapshot_action(int vid, const char * action);

    /**
     * This function takes an snapshot of a disk
     */
    void snapshot_create_action(int vid);

    /**
     * This function takes an snapshot of a disk
     */
    void snapshot_revert_action(int vid);

    /**
     * This function deletes an snapshot of a disk
     */
    void snapshot_delete_action(int vid);

    /**
     * This function resizes a VM disk
     */
    void resize_action(int vid);
};

#endif /*TRANSFER_MANAGER_H*/


text:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview ChromeVox predicates for the automation extension API.
 */

goog.provide('AutomationPredicate');
goog.provide('AutomationPredicate.Binary');
goog.provide('AutomationPredicate.Unary');

goog.scope(function() {
var AutomationNode = chrome.automation.AutomationNode;
var RoleType = chrome.automation.RoleType;

/**
 * @constructor
 */
AutomationPredicate = function() {};

/**
 * @typedef {function(!AutomationNode) : boolean}
 */
AutomationPredicate.Unary;

/**
 * @typedef {function(!AutomationNode, !AutomationNode) : boolean}
 */
AutomationPredicate.Binary;

/**
 * Constructs a predicate given a role.
 * @param {RoleType} role
 * @return {AutomationPredicate.Unary}
 */
AutomationPredicate.withRole = function(role) {
  return function(node) {
    return node.role == role;
  };
};

/** @type {AutomationPredicate.Unary} */
AutomationPredicate.checkBox = AutomationPredicate.withRole(RoleType.CHECK_BOX);
/** @type {AutomationPredicate.Unary} */
AutomationPredicate.comboBox = AutomationPredicate.withRole(RoleType.COMBO_BOX);
/** @type {AutomationPredicate.Unary} */
AutomationPredicate.heading = AutomationPredicate.withRole(RoleType.HEADING);
/** @type {AutomationPredicate.Unary} */
AutomationPredicate.inlineTextBox =
    AutomationPredicate.withRole(RoleType.INLINE_TEXT_BOX);
/** @type {AutomationPredicate.Unary} */
AutomationPredicate.link = AutomationPredicate.withRole(RoleType.LINK);
/** @type {AutomationPredicate.Unary} */
AutomationPredicate.table = AutomationPredicate.withRole(RoleType.TABLE);

/**
 * @param {!AutomationNode} node
 * @return {boolean}
 */
AutomationPredicate.button = function(node) {
  return /button/i.test(node.role);
};

/**
 * @param {!AutomationNode} node
 * @return {boolean}
 */
AutomationPredicate.editText = function(node) {
  return node.state.editable && node.parent && !node.parent.state.editable;
};

/**
 * @param {!AutomationNode} node
 * @return {boolean}
 */
AutomationPredicate.formField = function(node) {
  switch (node.role) {
    case 'button':
    case 'buttonDropDown':
    case 'checkBox':
    case 'comboBox':
    case 'date':
    case 'dateTime':
    case 'details':
    case 'disclosureTriangle':
    case 'form':
    case 'menuListPopup':
    case 'popUpButton':
    case 'radioButton':
    case 'searchBox':
    case 'slider':
    case 'spinButton':
    case 'switch':
    case 'tab':
    case 'textField':
    case 'time':
    case 'toggleButton':
    case 'tree':
      return true;
  }
  return false;
};

/**
 * @param {!AutomationNode} node
 * @return {boolean}
 */
AutomationPredicate.landmark = function(node) {
  switch (node.role) {
    case 'application':
    case 'banner':
    case 'complementary':
    case 'contentInfo':
    case 'form':
    case 'main':
    case 'navigation':
    case 'search':
      return true;
  }
  return false;
};

/**
 * @param {!AutomationNode} node
 * @return {boolean}
 */
AutomationPredicate.visitedLink = function(node) {
  return node.state.visited;
};

/**
 * @param {!AutomationNode} node
 * @return {boolean}
 */
AutomationPredicate.focused = function(node) {
  return node.state.focused;
};

/**
 * @param {!AutomationNode} node
 * @return {boolean}
 */
AutomationPredicate.leaf = function(node) {
  return !node.firstChild || node.role == RoleType.BUTTON ||
      node.role == RoleType.BUTTONDROPDOWN ||
      node.role == RoleType.POP_UP_BUTTON || node.role == RoleType.SLIDER ||
      node.role == RoleType.TEXT_FIELD || node.state.invisible ||
      node.children.every(function(n) {
        return n.state.invisible;
      });
};

/**
 * @param {!AutomationNode} node
 * @return {boolean}
 */
AutomationPredicate.leafWithText = function(node) {
  return AutomationPredicate.leaf(node) && !!(node.name || node.value);
};

/**
 * Non-inline textbox nodes which have an equivalent in the DOM.
 * @param {!AutomationNode} node
 * @return {boolean}
 */
AutomationPredicate.leafDomNode = function(node) {
  return AutomationPredicate.leaf(node) || node.role == RoleType.STATIC_TEXT;
};

/**
 * Matches against nodes visited during object navigation. An object as
 * defined below, are all nodes that are focusable or static text. When used in
 * tree walking, it should visit all nodes that tab traversal would as well as
 * non-focusable static text.
 * @param {!AutomationNode} node
 * @return {boolean}
 */
AutomationPredicate.object = function(node) {
  return node.state.focusable ||
      (AutomationPredicate.leafDomNode(node) &&
       (/\S+/.test(node.name) ||
        (node.role != RoleType.LINE_BREAK &&
         node.role != RoleType.STATIC_TEXT &&
         node.role != RoleType.INLINE_TEXT_BOX)));
};

/**
 * @param {!AutomationNode} first
 * @param {!AutomationNode} second
 * @return {boolean}
 */
AutomationPredicate.linebreak = function(first, second) {
  // TODO(dtseng): Use next/previousOnLin once available.
  var fl = first.location;
  var sl = second.location;
  return fl.top != sl.top || (fl.top + fl.height != sl.top + sl.height);
};

/**
 * Matches against a node that contains other interesting nodes.
 * These nodes should always have their subtrees scanned when navigating.
 * @param {!AutomationNode} node
 * @return {boolean}
 */
AutomationPredicate.container = function(node) {
  return AutomationPredicate.structuralContainer(node) ||
      node.role == RoleType.DIV || node.role == RoleType.DOCUMENT ||
      node.role == RoleType.GROUP || node.role == RoleType.LIST_ITEM ||
      node.role == RoleType.TOOLBAR || node.role == RoleType.WINDOW;
};

/**
 * Matches against nodes that contain interesting nodes, but should never be
 * visited.
 * @param {!AutomationNode} node
 * @return {boolean}
 */
AutomationPredicate.structuralContainer = function(node) {
  return node.role == RoleType.ROOT_WEB_AREA ||
      node.role == RoleType.EMBEDDED_OBJECT || node.role == RoleType.IFRAME ||
      node.role == RoleType.IFRAME_PRESENTATIONAL ||
      node.role == RoleType.PLUGIN_OBJECT;
};

/**
 * Returns whether the given node should not be crossed when performing
 * traversals up the ancestry chain.
 * @param {AutomationNode} node
 * @return {boolean}
 */
AutomationPredicate.root = function(node) {
  switch (node.role) {
    case RoleType.DIALOG:
    case RoleType.WINDOW:
      return true;
    case RoleType.TOOLBAR:
      return node.root.role == RoleType.DESKTOP;
    case RoleType.ROOT_WEB_AREA:
      return !node.parent || node.parent.root.role == RoleType.DESKTOP;
    default:
      return false;
  }
};

/**
 * Nodes that should be ignored while traversing the automation tree. For
 * example, apply this predicate when moving to the next object.
 * @param {!AutomationNode} node
 * @return {boolean}
 */
AutomationPredicate.shouldIgnoreNode = function(node) {
  // Ignore invisible nodes.
  if (node.state.invisible ||
      (node.location.height == 0 && node.location.width == 0))
    return true;

  // Ignore structural containres.
  if (AutomationPredicate.structuralContainer(node))
    return true;

  // Ignore list markers since we already announce listitem role.
  if (node.role == RoleType.LIST_MARKER)
    return true;

  // Don't ignore nodes with names.
  if (node.name || node.value || node.description)
    return false;

  // Ignore some roles.
  return AutomationPredicate.leaf(node) &&
      (node.role == RoleType.CLIENT || node.role == RoleType.DIV ||
       node.role == RoleType.GROUP || node.role == RoleType.IMAGE ||
       node.role == RoleType.STATIC_TEXT);
};
});  // goog.scope

redpajama_set_name: RedPajamaGithub


text:
set -x

mkdir -p processed_logs/

for((i=2;$i<12;i++));do

python postprocess.py --in-file raw_logs/train_run${i}.log --out-file processed_logs/train_run${i}.log
sh logging_postprocess.sh processed_logs/train_run${i}.log raw_logs/eval_run${i}.stdout  result_run${i}.txt

done


text:
package org.hibernate.test.annotations.cascade.multicircle.nonjpa.identity;

/**
 * No Documentation
 */
@javax.persistence.Entity
public class F extends AbstractEntity {
    private static final long serialVersionUID = 1471534025L;

    /**
     * No documentation
     */
    @javax.persistence.OneToMany(mappedBy = "f")
	@org.hibernate.annotations.Cascade({
			org.hibernate.annotations.CascadeType.PERSIST,
			org.hibernate.annotations.CascadeType.SAVE_UPDATE,
			org.hibernate.annotations.CascadeType.MERGE,
			org.hibernate.annotations.CascadeType.REFRESH
	})
    private java.util.Set<E> eCollection = new java.util.HashSet<E>();

	@javax.persistence.ManyToOne(optional = false)
	private D d;

	@javax.persistence.ManyToOne(optional = false)
	private G g;

    public java.util.Set<E> getECollection() {
        return eCollection;
    }
    public void setECollection(
        java.util.Set<E> parameter) {
        this.eCollection = parameter;
    }

    public D getD() {
        return d;
    }
    public void setD(D parameter) {
        this.d = parameter;
    }

	public G getG() {
		return g;
	}
	public void setG(G parameter) {
		this.g = parameter;
	}

}


text:
typedef NSString * const PandaStyle NS_STRING_ENUM;

extern PandaStyle PandaStyleCute;


text:
var should = require('should')
var request = require('supertest')
var socketioClient = require('socket.io-client')

var ChatBackend = require('..')

var backend = new ChatBackend()
var app = backend.app
backend.setupApiRoutes()

describe('ChatBackend', function () {

    describe('/api/message', function () {

        var basePath = '/api/message'
        var firstMessage, updatedFirstMessage, secondMessage, thirdMessage

        it('GET / should return an empty list', function (done) {
            request(app)
                .get(basePath)
                .set('Accept', 'application/json')
                .expect(200)
                .expect('Content-Type', /json/)
                .end(function (err, res) {
                    should(err).be.null
                    res.body.should.eql([])
                    done()
                })
        })

        it('POST / should add content and send what is persisted', function (done) {
            request(app)
                .post(basePath)
                .set('Accept', 'application/json')
                .send({
                    author: 'blint',
                    text: 'Hello API',
                    dummyParam: 'foo'
                })
                .expect(200)
                .expect('Content-Type', /json/)
                .end(function (err, res) {
                    should(err).be.null
                    firstMessage = res.body
                    firstMessage.should.have.property('id')
                    firstMessage.should.have.property('author', 'blint')
                    firstMessage.should.have.property('text', 'Hello API')
                    firstMessage.should.not.have.property('dummyParam')
                    done()
                })
        })

        it('GET /id should return a previously added message by its id', function (done) {
            request(app)
                .get(basePath + '/' + firstMessage.id)
                .expect(200)
                .expect('Content-Type', /json/)
                .end(function (err, res) {
                    should(err).be.null
                    res.body.should.eql(firstMessage)
                    done()
                })
        })

        it('GET /id should end in error for unknown ids', function (done) {
            request(app)
                .get(basePath + '/42')
                .expect(500)
                .end(function (err) {
                    should(err).be.null
                    done()
                })
        })

        it('PUT / should modify some content', function (done) {
            request(app)
                .put(basePath)
                .set('Accept', 'application/json')
                .send({
                    id: firstMessage.id,
                    author: firstMessage.author,
                    text: 'Hi API!',
                    dummyParam: 'foo'
                })
                .expect(200)
                .expect('Content-Type', /json/)
                .end(function (err, res) {
                    should(err).be.null

                    updatedFirstMessage = res.body
                    updatedFirstMessage.should.have.property('id', firstMessage.id)
                    updatedFirstMessage.should.have.property('author', firstMessage.author)
                    updatedFirstMessage.should.have.property('text', 'Hi API!')
                    updatedFirstMessage.should.not.have.property('dummyParam')

                    done()
                })
        })

        it('POST / should add a second message', function (done) {
            request(app)
                .post(basePath)
                .set('Accept', 'application/json')
                .send({
                    author: 'Komo',
                    text: 'Welcome'
                })
                .expect(200)
                .expect('Content-Type', /json/)
                .end(function (err, res) {
                    should(err).be.null
                    secondMessage = res.body
                    done()
                })
        })

        it('POST / should add a third message', function (done) {
            request(app)
                .post(basePath)
                .set('Accept', 'application/json')
                .send({
                    author: 'Bubux',
                    text: 'Hey guys'
                })
                .expect(200)
                .expect('Content-Type', /json/)
                .end(function (err, res) {
                    should(err).be.null
                    thirdMessage = res.body
                    done()
                })
        })

        it('DELETE / should delete second message', function (done) {
            request(app)
                .delete(basePath + '/' + secondMessage.id)
                .expect(200)
                .end(function (err) {
                    should(err).be.null
                    done()
                })
        })

        it('GET /id should fail returning second message', function (done) {
            request(app)
                .get(basePath + '/' + secondMessage.id)
                .expect(500)
                .end(function (err) {
                    should(err).be.null
                    done()
                })
        })

        it('GET / should return the list of messages with all their modifications', function (done) {
            request(app)
                .get(basePath)
                .set('Accept', 'application/json')
                .expect(200)
                .expect('Content-Type', /json/)
                .end(function (err, res) {
                    should(err).be.null
                    res.body.should.eql([updatedFirstMessage, thirdMessage])
                    done()
                })
        })
    })

    describe('Real time IO', function () {

        var PORT = 8080
        var socket

        before(function () {
            backend.listen(PORT)
        })

        beforeEach(function (done) {
            socket = socketioClient('http://localhost:' + PORT)
            socket.once('connect', done)
        })

        afterEach(function () {
            socket.close()
        })

        after(function () {
            backend.close()
        })

        it('should send a realtime event on new messages', function (done) {

            var message

            socket.on('message', function (data) {
                should(message).not.be.undefined
                data.should.eql(message)
                done()
            })

            request(app)
                .post('/api/message')
                .set('Accept', 'application/json')
                .send({
                    author: 'blint',
                    text: 'Hello API',
                    dummyParam: 'foo'
                })
                .expect(200)
                .expect('Content-Type', /json/)
                .end(function (err, res) {
                    should(err).be.null
                    message = res.body
                })
        })
    })
})


text:
author: Ramu
date: 2017-02-17T00:55:21.000Z
title: 'Friday Hacks #128, February 17'
url: /2017/02/friday-hacks-128
---

We are excited to have Emil and Sunny speaking at this week's FH before we break for recess week. Check out more details below. See you there!

Date/Time: Friday, February 17 at 6:30pm
Venue: SR3, Town Plaza, University Town, NUS
Free pizza is served before the talks!

Facebook event [here](https://www.facebook.com/events/603214613202877/)

{{< friday_hack_header venue="SR3, Town Plaza, University Town, NUS" date="February 17" >}}

### My Love-Hate Relationship with Honeypot

#### Talk Description:

In this talk, Emil will introduce what a honeypot is, discuss its applications, and demonstrate how honeypots are used in the industries and academia.

#### Speaker Profile

Emil Tan is an active advocate of the infosec community globally. He leads and founded Edgis, an infosec special interest group in Singapore – dedicated to stimulate exploration of different facets of cybersecurity technologies and topics and contribution to the community. He also leads the Singapore Chapter of The Honeynet Project, a global project that aims to improve the security of the Internet.

Emil has experiences in many areas of expertise in the cybersecurity field. He started his career as a researcher focusing in incident handling and intrusion deception. He later worked as a Security Ops Centre (SOC) specialist in the defence industry. Now, he's working in the governance, risk management and compliance (GRC) industry. Emil is a regular speaker in infosec conference. He has spoken at 44CON London, BSides London and SyScan Singapore. He also regularly speaks at universities and polytechnics in Singapore.

### Web Security for Developers

#### Talk Description:

In this talk, Sunny will go through some of the common web application vulnerabilities from OWASP Top 10 such as Cross Site Request Forgery (CSRF), Insecure Direct Object Reference (IDOR) and SQL Injection (SQLi) to understand why they exist in the first place and how to exploit them manually.

#### Speaker Profile

Sunny Neo is a Penetration Tester with BT Security, Ethical Hacking Centre of Excellence, a global team that performs security testing for various industries. Besides his day job, he teaches Ethical Hacking at Temasek Polytechnic as an Adjunct Lecturer, and is one of the CREST Assessors in Singapore. He is certified with CCT APP, OSCE, OSCP and GXPN. He has 1 year plus of working experience.


text:
package com.sfxcode.sapphire.core.demo.tutorial.controller

import com.sfxcode.sapphire.core.controller.ViewController
import com.typesafe.scalalogging.LazyLogging

abstract class AbstractViewController extends ViewController with LazyLogging{

  override def didGainVisibility(): Unit = {
    statusBarController.statusLabel.text = "%s loaded".format(getClass.getSimpleName)
  }

  def mainWindowController:MainWindowController = {
    parent.asInstanceOf[MainWindowController]
  }

  /**
    *
   * @return
    */
  def statusBarController = getBean[StatusBarController]()

  /**
    *
   * @return workspace manager resolved by parent
    */
  def workspaceManager = mainWindowController.workspaceManager

}


text:
declare namespace libphonenumber {
    export enum PhoneNumberFormat {
        E164,
        INTERNATIONAL,
        NATIONAL,
        RFC3966
    }

    export enum PhoneNumberType {
        FIXED_LINE = 0,
        MOBILE = 1,
        FIXED_LINE_OR_MOBILE = 2,
        TOLL_FREE = 3,
        PREMIUM_RATE = 4,
        SHARED_COST = 5,
        VOIP = 6,
        PERSONAL_NUMBER = 7,
        PAGER = 8,
        UAN = 9,
        VOICEMAIL = 10,
        UNKNOWN = -1
    }

    export module PhoneNumber {
        export enum CountryCodeSource {
            FROM_NUMBER_WITH_PLUS_SIGN = 1,
            FROM_NUMBER_WITH_IDD = 5,
            FROM_NUMBER_WITHOUT_PLUS_SIGN = 10,
            FROM_DEFAULT_COUNTRY = 20,
        }
    }

    export interface PhoneNumber {
        getCountryCode(): number | undefined;
        getCountryCodeOrDefault(): number;
        setCountryCode(value: number): void;
        hasCountryCode(): boolean;
        countryCodeCount(): number;
        clearCountryCode(): void;

        getNationalNumber(): number | undefined;
        getNationalNumberOrDefault(): number;
        setNationalNumber(value: number): number;
        hasNationalNumber(): boolean;
        nationalNumberCount(): number;
        clearNationalNumber(): void;

        getExtension(): string | undefined;
        getExtensionOrDefault(): string;
        setExtension(value: string): void;
        hasExtension(): boolean;
        extensionCount(): number;
        clearExtension(): void;

        getItalianLeadingZero(): boolean | undefined;
        getItalianLeadingZeroOrDefault(): boolean;
        setItalianLeadingZero(value: boolean): void;
        hasItalianLeadingZero(): boolean;
        italianLeadingZeroCount(): number;
        clearItalianLeadingZero(): void;

        getNumberOfLeadingZeros(): number | undefined;
        getNumberOfLeadingZerosOrDefault(): number;
        setNumberOfLeadingZeros(value: number): void;
        hasNumberOfLeadingZeros(): boolean;
        numberOfLeadingZerosCount(): number;
        clearNumberOfLeadingZeros(): void;

        getRawInput(): string | undefined;
        getRawInputOrDefault(): string;
        setRawInput(value: string): void;
        hasRawInput(): boolean;
        rawInputCount(): number;
        clearRawInput(): void;

        getCountryCodeSource(): PhoneNumber.CountryCodeSource | undefined;
        getCountryCodeSourceOrDefault(): PhoneNumber.CountryCodeSource;
        setCountryCodeSource(value: PhoneNumber.CountryCodeSource): void;
        hasCountryCodeSource(): boolean;
        countryCodeSourceCount(): number;
        clearCountryCodeSource(): void;

        getPreferredDomesticCarrierCode(): string | undefined;
        getPreferredDomesticCarrierCodeOrDefault(): string;
        setPreferredDomesticCarrierCode(value: string): void;
        hasPreferredDomesticCarrierCode(): boolean;
        preferredDomesticCarrierCodeCount(): number;
        clearPreferredDomesticCarrierCode(): void;
    }

    export module PhoneNumberUtil {
        export enum ValidationResult {
            IS_POSSIBLE,
            INVALID_COUNTRY_CODE,
            TOO_SHORT,
            TOO_LONG
        }
    }

    export class PhoneNumberUtil {
        static getInstance(): PhoneNumberUtil
        format(phoneNumber: PhoneNumber, format: PhoneNumberFormat): string;
        getNddPrefixForRegion(regionCode?: string, stripNonDigits?: boolean): string | undefined;
        getNumberType(phoneNumber: PhoneNumber): PhoneNumberType;
        getRegionCodeForCountryCode(countryCallingCode: number): string;
        getRegionCodeForNumber(phoneNumber: PhoneNumber): string | undefined;
        isAlphaNumber(number: string): boolean;
        isLeadingZeroPossible(countryCallingCode: number): boolean;
        isNANPACountry(regionCode?: string): boolean;
        isPossibleNumber(number: PhoneNumber): boolean;
        isPossibleNumber(phoneNumber: PhoneNumber): boolean;
        isPossibleNumberForType(number: PhoneNumber, type: PhoneNumberType): boolean;
        isPossibleNumberForTypeWithReason(number: PhoneNumber, type: PhoneNumberType): PhoneNumberUtil.ValidationResult;
        isPossibleNumberString(number: string, regionDialingFrom: string): boolean;
        isPossibleNumberWithReason(number: PhoneNumber): PhoneNumberUtil.ValidationResult;
        isPossibleNumberWithReason(phoneNumber: PhoneNumber): PhoneNumberUtil.ValidationResult;
        isValidNumber(phoneNumber: PhoneNumber): boolean;
        isValidNumberForRegion(phoneNumber: PhoneNumber, region?: string): boolean;
        parse(number?: string, region?: string): PhoneNumber;
        parseAndKeepRawInput(number: string, regionCode?: string): PhoneNumber;
        truncateTooLongNumber(number: PhoneNumber): boolean;
    }

    export class AsYouTypeFormatter {
        constructor(region: string);
        inputDigit(digit: string): string;
        clear(): void;
    }
}

declare module 'google-libphonenumber' {
    export = libphonenumber;
}


text:
<?php

namespace SubscribeWithGoogle\WordPress;

/** Supports editing of posts. */
final class EditPost {

	/** Adds ≈action handlers. */
	public function __construct() {
		// Render meta box on Post Edit page.
		add_action( 'add_meta_boxes', array( __CLASS__, 'add_meta_boxes' ) );

		// Handle Posts being saved.
		add_action( 'save_post', array( __CLASS__, 'save_post' ) );
	}

	/** Adds meta boxes to the Post edit page. */
	public static function add_meta_boxes() {
		add_meta_box(
			Plugin::key( 'post-edit-metabox' ),
			'Subscribe with Google',
			array( __CLASS__, 'render' ),
			'post',
			'side',
			'high'
		);
	}

	/** Renders meta box. */
	public static function render() {
		self::render_products_dropdown();
		self::render_free_checkbox();

		wp_nonce_field( Plugin::key( 'saving_settings' ), Plugin::key( 'nonce' ) );
	}

	/** Renders products dropdown. */
	public static function render_products_dropdown() {
		$product_key  = Plugin::key( 'product' );
		$products_key = Plugin::key( 'products' );
		$products_str = trim( get_option( $products_key ) );

		if ( ! $products_str ) {
			echo 'Please define products on the SwG setup page 😄. ';
			echo 'Link';
			return;
		}

		$products         = explode( "\n", $products_str );
		$selected_product = get_post_meta( get_the_ID(), $product_key, true );
		echo 'Product  ';
		echo '<select';
		echo ' name="' . esc_attr( $product_key ) . '"';
		echo ' id="' . esc_attr( $product_key ) . '"';
		echo '>';
		foreach ( $products as $product ) {
			$product = trim( $product );
			echo '<option';
			echo ' value="' . esc_attr( $product ) . '"';
			if ( $selected_product === $product ) {
				echo ' selected';
			}
			echo '>';
			echo esc_html( $product );
			echo '</option>';
		}
		echo '</select>';
		echo '
';
		echo '
';
	}

	/** Renders free checkbox. */
	public static function render_free_checkbox() {
		$free_key = Plugin::key( 'free' );
		$free     = get_post_meta( get_the_ID(), $free_key, true ) === 'true';

		echo 'Is Free  ';
		echo '<input';
		echo ' id="' . esc_attr( $free_key ) . '"';
		echo ' name="' . esc_attr( $free_key ) . '"';
		echo ' type="checkbox"';
		echo ' value="true"';
		if ( $free ) {
			echo ' checked';
		}
		echo '/>';
	}

	/**
	 * Saves additional metadata when a Post is saved.
	 *
	 * @param string $post_id ID of the post being saved.
	 */
	public static function save_post( $post_id ) {
		$product_key = Plugin::key( 'product' );
		$free_key    = Plugin::key( 'free' );
		$nonce_key   = Plugin::key( 'nonce' );
		// phpcs:disable
		// There might be a bug in one of the WP linters.
		// We can't upgrade them while supporting older versions of PHP it seems.
		if (
			! isset( $_POST[ $nonce_key ] ) ||
			! isset( $_POST[ $product_key ] )
		) {
			return;
		}
		$product   = $_POST[ $product_key ];
		$free      = isset( $_POST[ $free_key ] ) ? $_POST[ $free_key ] : 'false';
		$swg_nonce = $_POST[ $nonce_key ];
		// phpcs:enable

		// Verify settings nonce.
		if ( ! wp_verify_nonce( sanitize_key( $swg_nonce ), Plugin::key( 'saving_settings' ) ) ) {
			return;
		}

		// Product field.
		$value = sanitize_text_field( wp_unslash( $product ) );
		update_post_meta(
			$post_id,
			$product_key,
			$value
		);

		// Free field.
		$value = sanitize_text_field( wp_unslash( $free ) );
		update_post_meta(
			$post_id,
			$free_key,
			$value
		);
	}
}


text:
import {setDescription} from './utils/description';

/**
 * Checks whether a value is a function
 *
 * @example
 * is.function(function() {}); // true
 * is.function(alert); // true
 * is.function('alert'); // false
 */
function isFunction(value: any): value is Function {
    return typeof value === 'function';
}

setDescription(isFunction, 'a function');
export default isFunction;


text:
import * as Majavashakki from "../GamePieces"
import Piece from "./Piece"
import BoardBase from "../BoardBase"

export default class Pawn extends Piece {
  constructor(color: Majavashakki.PieceColor, position: Majavashakki.IPosition) {
    super(color, position, Majavashakki.PieceType.Pawn)
  }

  public isValidMove(board: BoardBase, destination: Majavashakki.IPosition): boolean {
    const start = this.currentPositionInNumbers()
    const dest = Piece.positionToNumbers(destination)

    const rowDiff = dest.row - start.row
    const colDiff = dest.col - start.col

    const destinationPiece = board.getPiece(destination)

    const movementDirection = this.color === Majavashakki.PieceColor.White ? 1 : -1

    // Check if pawn is capturing
    if (destinationPiece && rowDiff === movementDirection && (colDiff === 1 || colDiff === -1)) return true
    else if (!destinationPiece && colDiff === 0) {
      // Check if pawn is moving
      if (!this.hasMoved && rowDiff === movementDirection * 2) {
        // Ensure that double move is not blocked by piece
        dest.row -= movementDirection
        if (!board.getPiece(Piece.numbersToPosition(dest))) return true
      }

      if (rowDiff === movementDirection) return true
    }

    return false
  }

  public isEnPassant(board: BoardBase, destination: Majavashakki.IPosition): boolean {
    const start = this.currentPositionInNumbers()
    const dest = Piece.positionToNumbers(destination)

    const rowDiff = dest.row - start.row
    const colDiff = dest.col - start.col

    const movementDirection = this.color === "white" ? 1 : -1

    // Check if diagonal movement
    if (rowDiff === movementDirection && (colDiff === 1 || colDiff === -1)) {
      // Check if there is a piece below destination and that piece is enemy pawn
      dest.row -= movementDirection
      const targetPiece = board.getPiece(Piece.numbersToPosition(dest))

      if (targetPiece && targetPiece.type === "pawn" && targetPiece.color !== this.color) {
        // Check if last move was double move and that its destination was targetPiece
        const lastMove: Majavashakki.IMove = board.moveHistory[board.moveHistory.length - 1]
        const lastStart = Piece.positionToNumbers(lastMove.start)
        const lastDest = Piece.positionToNumbers(lastMove.destination)

        const lastMoveDiff: number = Math.abs(lastDest.row - lastStart.row)
        if (lastMoveDiff === 2 && board.comparePos(lastMove.destination, targetPiece.position)) return true
      }
    }
  }

  public clone(): Pawn {
    const pawn = new Pawn(this.color, this.position)
    pawn.hasMoved = this.hasMoved
    return pawn
  }
}


text:
<?php

declare(strict_types=1);

namespace AppBundle\Form;

use AppBundle\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;

class LoginType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('username', TextType::class)
            ->add('password', PasswordType::class)
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => User::class,
        ));
    }
}


text:
using System;
using UnityEngine.Events;
using UnityEngine.EventSystems;

namespace UnityEngine.UI
{
    [AddComponentMenu("Layout/Layout Element", 140)]
    [RequireComponent(typeof(RectTransform))]
    [ExecuteInEditMode]
    public class LayoutElement : UIBehaviour, ILayoutElement, ILayoutIgnorer
    {
        [SerializeField] private bool m_IgnoreLayout = false;
        [SerializeField] private float m_MinWidth = -1;
        [SerializeField] private float m_MinHeight = -1;
        [SerializeField] private float m_PreferredWidth = -1;
        [SerializeField] private float m_PreferredHeight = -1;
        [SerializeField] private float m_FlexibleWidth = -1;
        [SerializeField] private float m_FlexibleHeight = -1;

        public virtual bool ignoreLayout { get { return m_IgnoreLayout; } set { if (SetPropertyUtility.SetStruct(ref m_IgnoreLayout, value)) SetDirty(); } }

        public virtual void CalculateLayoutInputHorizontal() {}
        public virtual void CalculateLayoutInputVertical() {}
        public virtual float minWidth { get { return m_MinWidth; } set { if (SetPropertyUtility.SetStruct(ref m_MinWidth, value)) SetDirty(); } }
        public virtual float minHeight { get { return m_MinHeight; } set { if (SetPropertyUtility.SetStruct(ref m_MinHeight, value)) SetDirty(); } }
        public virtual float preferredWidth { get { return m_PreferredWidth; } set { if (SetPropertyUtility.SetStruct(ref m_PreferredWidth, value)) SetDirty(); } }
        public virtual float preferredHeight { get { return m_PreferredHeight; } set { if (SetPropertyUtility.SetStruct(ref m_PreferredHeight, value)) SetDirty(); } }
        public virtual float flexibleWidth { get { return m_FlexibleWidth; } set { if (SetPropertyUtility.SetStruct(ref m_FlexibleWidth, value)) SetDirty(); } }
        public virtual float flexibleHeight { get { return m_FlexibleHeight; } set { if (SetPropertyUtility.SetStruct(ref m_FlexibleHeight, value)) SetDirty(); } }
        public virtual int layoutPriority { get { return 1; } }

        protected LayoutElement()
        {}

        #region Unity Lifetime calls

        protected override void OnEnable()
        {
            base.OnEnable();
            SetDirty();
        }

        protected override void OnTransformParentChanged()
        {
            SetDirty();
        }

        protected override void OnDisable()
        {
            SetDirty();
            base.OnDisable();
        }

        protected override void OnDidApplyAnimationProperties()
        {
            SetDirty();
        }

        protected override void OnBeforeTransformParentChanged()
        {
            SetDirty();
        }

        #endregion

        protected void SetDirty()
        {
            if (!IsActive())
                return;
            LayoutRebuilder.MarkLayoutForRebuild(transform as RectTransform);
        }

    #if UNITY_EDITOR
        protected override void OnValidate()
        {
            SetDirty();
        }

    #endif
    }
}


text:
This is a reference architecture cookbook for building a Chef Server with Chef Analytics and Supermarket. This is an open source cookbook and resides in a public GitHub repository. However it is not a "community" cookbook, as it won't be published to the [public Supermarket](https://supermarket.chef.io). It is narrow in scope for our use cases, but it can be used alongside other cookbooks.

## License Required

This cookbook brings up systems that will run Chef premium features. You need to have a license for running more than 25 nodes. See [plans and pricing](https://www.chef.io/chef/#plans-and-pricing) for further details.

## Maintainers and Support

This cookbook is maintained and supported by Chef's engineering services team. This cookbook runs through our internal Chef Delivery system, and changes must be approved by a member of engineering services.

## Requirements

Local development and use requires ChefDK 0.9.0 or higher.

### Platform:

64 bit Red Hat Enterprise Linux 7.1 or CentOS 7.1

Other platforms may be added in the future according to the [platforms that Chef Server 12 supports](https://docs.chef.io/supported_platforms.html).

### Cookbooks:

* [chef-ingredient](https://github.com/chef-cookbooks/chef-ingredient): manages chef server components/addons and more.

## Attributes

See `attributes/default.rb` for default values for the `chef-reference` cookbook. The `provision` cookbook in this repository has attributes that can be modified for chef-provisioning.

This cookbook is designed primarily to be used with AWS as that is our use case. However, by modifying the various `driver` attributes, other providers may be usable. An example of doing this with [Vagrant](https://vagrantup.com) is provided via the `provision::dev` recipe. The following aspects of AWS configuration can be modified using the `chef provision` command's `--opts` (`-o`) argument. Pass it multiple times to change multiple values.

* `aws_region`: the AWS region, default is `us-west-2`
* `key_name`: the SSH key to use, default is `chef-reference-arch`
* `ssh_user`: the user to login with SSH, default is `ec2-user`
* `image_id`: the AMI, default is the RHEL 7 image
* `instance_type`: instance size to use, default is `m3.medium`
* `subnet_id`: the network id to use, which should automatically place instances in the right VPC
* `security_group_ids`: security group that the instances should be in, specify only one

## Documentation

See the [docs directory](./docs) in this repository for additional documentation:

* [README.md](./docs/README.md): more background and detail
* [getting-started.md](./docs/getting-started.md): how to get started
* [scenario-aws.md](./docs/scenario-aws.md): using AWS for a new cluster, this is the default use case
* [secrets.md](./docs/secrets.md): how to use the required secrets

Chef Server documentation:

* https://docs.chef.io/server/

## Issues

Please report [issues in this repository](https://github.com/chef-cookbooks/chef-reference/issues). Please also understand that this cookbook is intended to be narrow and opinionated in scope, and may not work for all use cases.

## License and Author

- Author: Paul Mooring <paul@chef.io>
- Author: Joshua Timberman <joshua@chef.io>
- Author: Serdar Sutay <serdar@chef.io>
- Copyright (C) 2014-2015 Chef Software, Inc. <legal@chef.io>

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.


text:
Puppet module to install Net-SNMP Agent

## Sample

```puppet
class {'snmpd':
    snmp_syslocation = 'snmp_location',
    snmp_syscontact = 'snmp_contact',
    snmp_community_readonly = 'snmp_community_read',
    trap_dest_host => 'dest.domain.com',
    enable => true,
    ensure => running,
}
```


text:
package me.huding.hunter.app;

public class Department {

	String name;

	String value;

	public String getName() {
		return name;
	}

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

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

	@Override
	public String toString() {
		return "Department [name=" + name + ", value=" + value + "]";
	}

}


text:
@class Lecture, Term;

@interface Course : NSManagedObject

@property (nonatomic, retain) NSString * title;
@property (nonatomic, retain) NSString * url;
@property (nonatomic, retain) NSSet *lectures;
@property (nonatomic, retain) Term *semester;
@end

@interface Course (CoreDataGeneratedAccessors)

- (void)addLecturesObject:(Lecture *)value;
- (void)removeLecturesObject:(Lecture *)value;
- (void)addLectures:(NSSet *)values;
- (void)removeLectures:(NSSet *)values;

@end


text:
import { checkCompatibility } from "@/generated/TradingGateway"

export function checkTradingGatewayCompatibility() {
  checkCompatibility().subscribe((response) => {
    const log = response.type === "incompatible" ? console.error : console.log
    log(`Trading Gateway Api is ${response.type}`)
    if (response.type === "incompatible") {
      response.payload.methods.map(
        ({
          method: { methodName, serviceName, methodRouteKey },
          reason: { type },
        }) => log(`${type} ${serviceName} ${methodName} ${methodRouteKey}`),
      )
    }
  })
}


text:
def calculate_age(year_of_birth, current_year)
  if year_of_birth < current_year
    (current_year - year_of_birth) > 1 ? "You are #{current_year - year_of_birth} years old." : "You are 1 year old."
  elsif year_of_birth > current_year
    (year_of_birth - current_year) > 1 ? "You will be born in #{year_of_birth - current_year} years." : "You will be born in 1 year."
  else
    'You were born this very year!'
  end
end


text:
#include <Corrade/TestSuite/Tester.h>

#include "Magnum/AbstractShaderProgram.h"

namespace Magnum { namespace Test {

struct AbstractShaderProgramTest: TestSuite::Tester {
    explicit AbstractShaderProgramTest();

    void attributeScalar();
    void attributeScalarInt();
    void attributeScalarUnsignedInt();
    void attributeScalarDouble();

    void attributeVector();
    void attributeVectorInt();
    void attributeVectorUnsignedInt();
    void attributeVectorDouble();
    void attributeVector4();
    void attributeVectorBGRA();

    void attributeMatrixNxN();
    #ifndef MAGNUM_TARGET_GLES2
    void attributeMatrixMxN();
    #endif
    void attributeMatrixNxNd();
    void attributeMatrixMxNd();
};

AbstractShaderProgramTest::AbstractShaderProgramTest() {
    addTests({&AbstractShaderProgramTest::attributeScalar,
              &AbstractShaderProgramTest::attributeScalarInt,
              &AbstractShaderProgramTest::attributeScalarUnsignedInt,
              &AbstractShaderProgramTest::attributeScalarDouble,

              &AbstractShaderProgramTest::attributeVector,
              &AbstractShaderProgramTest::attributeVectorInt,
              &AbstractShaderProgramTest::attributeVectorUnsignedInt,
              &AbstractShaderProgramTest::attributeVectorDouble,
              &AbstractShaderProgramTest::attributeVector4,
              &AbstractShaderProgramTest::attributeVectorBGRA,

              &AbstractShaderProgramTest::attributeMatrixNxN,
              #ifndef MAGNUM_TARGET_GLES2
              &AbstractShaderProgramTest::attributeMatrixMxN,
              #endif
              &AbstractShaderProgramTest::attributeMatrixNxNd,
              &AbstractShaderProgramTest::attributeMatrixMxNd});
}

void AbstractShaderProgramTest::attributeScalar() {
    typedef Attribute<3, Float> Attribute;
    CORRADE_VERIFY((std::is_same<Attribute::ScalarType, Float>{}));
    CORRADE_COMPARE(Attribute::Location, 3);
    CORRADE_COMPARE(Attribute::VectorCount, 1);

    /* Default constructor */
    Attribute a;
    CORRADE_COMPARE(a.components(), Attribute::Components::One);
    CORRADE_VERIFY(!a.dataOptions());
    CORRADE_COMPARE(a.vectorSize(), 4);
    CORRADE_COMPARE(a.dataType(), Attribute::DataType::Float);

    /* Options */
    Attribute b(Attribute::DataType::UnsignedShort, Attribute::DataOption::Normalized);
    CORRADE_COMPARE(b.vectorSize(), 2);
    CORRADE_VERIFY(b.dataOptions() <= Attribute::DataOption::Normalized);
}

void AbstractShaderProgramTest::attributeScalarInt() {
    #ifndef MAGNUM_TARGET_GLES2
    typedef Attribute<3, Int> Attribute;
    CORRADE_VERIFY((std::is_same<Attribute::ScalarType, Int>{}));
    CORRADE_COMPARE(Attribute::VectorCount, 1);

    /* Default constructor */
    Attribute a;
    CORRADE_COMPARE(a.vectorSize(), 4);

    /* Options */
    Attribute b(Attribute::DataType::Short);
    CORRADE_COMPARE(b.vectorSize(), 2);
    #else
    CORRADE_SKIP("Integer attributes are not available in OpenGL ES 2.");
    #endif
}

void AbstractShaderProgramTest::attributeScalarUnsignedInt() {
    #ifndef MAGNUM_TARGET_GLES2
    typedef Attribute<3, UnsignedInt> Attribute;
    CORRADE_VERIFY((std::is_same<Attribute::ScalarType, UnsignedInt>{}));
    CORRADE_COMPARE(Attribute::VectorCount, 1);

    /* Default constructor */
    Attribute a;
    CORRADE_COMPARE(a.vectorSize(), 4);

    /* Options */
    Attribute b(Attribute::DataType::UnsignedByte);
    CORRADE_COMPARE(b.vectorSize(), 1);
    #else
    CORRADE_SKIP("Integer attributes are not available in OpenGL ES 2.");
    #endif
}

void AbstractShaderProgramTest::attributeScalarDouble() {
    #ifndef MAGNUM_TARGET_GLES
    typedef Attribute<3, Double> Attribute;
    CORRADE_VERIFY((std::is_same<Attribute::ScalarType, Double>{}));
    CORRADE_COMPARE(Attribute::VectorCount, 1);

    /* Default constructor */
    Attribute a;
    CORRADE_COMPARE(a.vectorSize(), 8);
    #else
    CORRADE_SKIP("Double attributes are not available in OpenGL ES.");
    #endif
}

void AbstractShaderProgramTest::attributeVector() {
    typedef Attribute<3, Vector3> Attribute;
    CORRADE_VERIFY((std::is_same<Attribute::ScalarType, Float>{}));
    CORRADE_COMPARE(Attribute::VectorCount, 1);

    /* Default constructor */
    Attribute a;
    CORRADE_COMPARE(a.components(), Attribute::Components::Three);
    CORRADE_COMPARE(a.vectorSize(), 3*4);
    CORRADE_COMPARE(a.dataType(), Attribute::DataType::Float);

    /* Options */
    #ifndef MAGNUM_TARGET_GLES
    Attribute b(Attribute::Components::Two, Attribute::DataType::Double);
    CORRADE_COMPARE(b.components(), Attribute::Components::Two);
    CORRADE_COMPARE(b.vectorSize(), 2*8);
    #else
    Attribute b(Attribute::Components::Two, Attribute::DataType::Float);
    CORRADE_COMPARE(b.components(), Attribute::Components::Two);
    CORRADE_COMPARE(b.vectorSize(), 2*4);
    #endif
}

void AbstractShaderProgramTest::attributeVectorInt() {
    #ifndef MAGNUM_TARGET_GLES2
    typedef Attribute<3, Vector2i> Attribute;
    CORRADE_VERIFY((std::is_same<Attribute::ScalarType, Int>{}));
    CORRADE_COMPARE(Attribute::VectorCount, 1);

    /* Default constructor */
    Attribute a;
    CORRADE_COMPARE(a.components(), Attribute::Components::Two);
    CORRADE_COMPARE(a.vectorSize(), 2*4);
    CORRADE_COMPARE(a.dataType(), Attribute::DataType::Int);

    /* Options */
    Attribute b(Attribute::Components::One, Attribute::DataType::Int);
    CORRADE_COMPARE(b.vectorSize(), 4);
    #else
    CORRADE_SKIP("Integer attributes are not available in OpenGL ES 2.");
    #endif
}

void AbstractShaderProgramTest::attributeVectorUnsignedInt() {
    #ifndef MAGNUM_TARGET_GLES2
    typedef Attribute<3, Vector4ui> Attribute;
    CORRADE_VERIFY((std::is_same<Attribute::ScalarType, UnsignedInt>{}));
    CORRADE_COMPARE(Attribute::VectorCount, 1);

    /* Default constructor */
    Attribute a;
    CORRADE_COMPARE(a.components(), Attribute::Components::Four);
    CORRADE_COMPARE(a.vectorSize(), 4*4);
    CORRADE_COMPARE(a.dataType(), Attribute::DataType::UnsignedInt);

    /* Options */
    Attribute b(Attribute::Components::Three, Attribute::DataType::UnsignedShort);
    CORRADE_COMPARE(b.vectorSize(), 3*2);
    #else
    CORRADE_SKIP("Integer attributes are not available in OpenGL ES 2.");
    #endif
}

void AbstractShaderProgramTest::attributeVectorDouble() {
    #ifndef MAGNUM_TARGET_GLES
    typedef Attribute<3, Vector2d> Attribute;
    CORRADE_VERIFY((std::is_same<Attribute::ScalarType, Double>{}));
    CORRADE_COMPARE(Attribute::VectorCount, 1);

    /* Default constructor */
    Attribute a;
    CORRADE_COMPARE(a.components(), Attribute::Components::Two);
    CORRADE_COMPARE(a.vectorSize(), 2*8);
    CORRADE_COMPARE(a.dataType(), Attribute::DataType::Double);

    /* Options */
    Attribute b(Attribute::Components::One);
    CORRADE_COMPARE(b.vectorSize(), 8);
    #else
    CORRADE_SKIP("Double attributes are not available in OpenGL ES.");
    #endif
}

void AbstractShaderProgramTest::attributeVector4() {
    typedef Attribute<3, Vector4> Attribute;
    CORRADE_VERIFY((std::is_same<Attribute::ScalarType, Float>{}));
    CORRADE_COMPARE(Attribute::VectorCount, 1);

    /* Custom type */
    #ifndef MAGNUM_TARGET_GLES
    Attribute a(Attribute::DataType::UnsignedInt2101010Rev);
    CORRADE_COMPARE(a.vectorSize(), 4);
    #else
    Attribute a(Attribute::DataType::HalfFloat);
    CORRADE_COMPARE(a.vectorSize(), 8);
    #endif
}

void AbstractShaderProgramTest::attributeVectorBGRA() {
    #ifndef MAGNUM_TARGET_GLES
    typedef Attribute<3, Vector4> Attribute;
    CORRADE_VERIFY((std::is_same<Attribute::ScalarType, Float>{}));
    CORRADE_COMPARE(Attribute::VectorCount, 1);

    /* BGRA */
    Attribute a(Attribute::Components::BGRA);
    CORRADE_COMPARE(a.vectorSize(), 4*4);
    #else
    CORRADE_SKIP("BGRA attribute component ordering is not available in OpenGL ES.");
    #endif
}

void AbstractShaderProgramTest::attributeMatrixNxN() {
    typedef Attribute<3, Matrix3> Attribute;
    CORRADE_VERIFY((std::is_same<Attribute::ScalarType, Float>{}));
    CORRADE_COMPARE(Attribute::VectorCount, 3);

    /* Default constructor */
    Attribute a;
    CORRADE_COMPARE(a.components(), Attribute::Components::Three);
    CORRADE_COMPARE(a.vectorSize(), 3*4);
    CORRADE_COMPARE(a.dataType(), Attribute::DataType::Float);
}

#ifndef MAGNUM_TARGET_GLES2
void AbstractShaderProgramTest::attributeMatrixMxN() {
    typedef Attribute<3, Matrix3x4> Attribute;
    CORRADE_VERIFY((std::is_same<Attribute::ScalarType, Float>{}));
    CORRADE_COMPARE(Attribute::VectorCount, 3);

    /* Default constructor */
    Attribute a;
    CORRADE_COMPARE(a.components(), Attribute::Components::Four);
    CORRADE_COMPARE(a.vectorSize(), 4*4);
    CORRADE_COMPARE(a.dataType(), Attribute::DataType::Float);
}
#endif

void AbstractShaderProgramTest::attributeMatrixNxNd() {
    #ifndef MAGNUM_TARGET_GLES
    typedef Attribute<3, Matrix4d> Attribute;
    CORRADE_VERIFY((std::is_same<Attribute::ScalarType, Double>{}));
    CORRADE_COMPARE(Attribute::VectorCount, 4);

    /* Default constructor */
    Attribute a;
    CORRADE_COMPARE(a.components(), Attribute::Components::Four);
    CORRADE_COMPARE(a.vectorSize(), 4*8);
    CORRADE_COMPARE(a.dataType(), Attribute::DataType::Double);
    #else
    CORRADE_SKIP("Double attributes are not available in OpenGL ES.");
    #endif
}

void AbstractShaderProgramTest::attributeMatrixMxNd() {
    #ifndef MAGNUM_TARGET_GLES
    typedef Attribute<3, Matrix4x2d> Attribute;
    CORRADE_VERIFY((std::is_same<Attribute::ScalarType, Double>{}));
    CORRADE_COMPARE(Attribute::VectorCount, 4);

    /* Default constructor */
    Attribute a;
    CORRADE_COMPARE(a.components(), Attribute::Components::Two);
    CORRADE_COMPARE(a.vectorSize(), 2*8);
    CORRADE_COMPARE(a.dataType(), Attribute::DataType::Double);
    #else
    CORRADE_SKIP("Double attributes are not available in OpenGL ES.");
    #endif
}

}}

CORRADE_TEST_MAIN(Magnum::Test::AbstractShaderProgramTest)


text:
=============
API Reference
=============

.. toctree::
   :maxdepth: 1

   api-usage-guidelines.md
   api-use-instructions.md
   api_version_query
   bms_lifecycle_management
   bms_status_management
   bms_metadata_management
   bms_ip_address_query
   bms_flavor_query
   bms_nic_management
   bms_disk_management
   bms_ssh_key_pair_management
   bms_1d_tag_management
   public_parameters


text:
import { localize } from 'vs/nls';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IConfigurationNode } from 'vs/platform/configuration/common/configurationRegistry';

export const enum TestingConfigKeys {
	AutoRunDelay = 'testing.autoRun.delay',
	AutoRunMode = 'testing.autoRun.mode',
	AutoOpenPeekView = 'testing.automaticallyOpenPeekView',
	AutoOpenPeekViewDuringAutoRun = 'testing.automaticallyOpenPeekViewDuringAutoRun',
	FollowRunningTest = 'testing.followRunningTest',
}

export const enum AutoOpenPeekViewWhen {
	FailureVisible = 'failureInVisibleDocument',
	FailureAnywhere = 'failureAnywhere',
}

export const enum AutoRunMode {
	AllInWorkspace = 'all',
	OnlyPreviouslyRun = 'rerun',
}

export const testingConfiguation: IConfigurationNode = {
	id: 'testing',
	order: 21,
	title: localize('testConfigurationTitle', "Testing"),
	type: 'object',
	properties: {
		[TestingConfigKeys.AutoRunMode]: {
			description: localize('testing.autoRun.mode', "Controls which tests are automatically run."),
			enum: [
				AutoRunMode.AllInWorkspace,
				AutoRunMode.OnlyPreviouslyRun,
			],
			default: AutoRunMode.AllInWorkspace,
			enumDescriptions: [
				localize('testing.autoRun.mode.allInWorkspace', "Automatically runs all discovered test when auto-run is toggled. Reruns individual tests when they are changed."),
				localize('testing.autoRun.mode.onlyPreviouslyRun', "Reruns individual tests when they are changed. Will not automatically run any tests that have not been already executed.")
			],
		},
		[TestingConfigKeys.AutoRunDelay]: {
			type: 'integer',
			minimum: 0,
			description: localize('testing.autoRun.delay', "How long to wait, in milliseconds, after a test is marked as outdated and starting a new run."),
			default: 1000,
		},
		[TestingConfigKeys.AutoOpenPeekView]: {
			description: localize('testing.automaticallyOpenPeekView', "Configures when the error peek view is automatically opened."),
			enum: [
				AutoOpenPeekViewWhen.FailureAnywhere,
				AutoOpenPeekViewWhen.FailureVisible,
			],
			default: AutoOpenPeekViewWhen.FailureVisible,
			enumDescriptions: [
				localize('testing.automaticallyOpenPeekView.failureAnywhere', "Open automatically no matter where the failure is."),
				localize('testing.automaticallyOpenPeekView.failureInVisibleDocument', "Open automatically when a test fails in a visible document.")
			],
		},
		[TestingConfigKeys.AutoOpenPeekViewDuringAutoRun]: {
			description: localize('testing.automaticallyOpenPeekViewDuringAutoRun', "Controls whether to automatically open the peek view during auto-run mode."),
			type: 'boolean',
			default: false,
		},
		[TestingConfigKeys.FollowRunningTest]: {
			description: localize('testing.followRunningTest', 'Controls whether the running test should be followed in the test explorer view'),
			type: 'boolean',
			default: true,
		},
	}
};

export interface ITestingConfiguration {
	[TestingConfigKeys.AutoRunMode]: AutoRunMode;
	[TestingConfigKeys.AutoRunDelay]: number;
	[TestingConfigKeys.AutoOpenPeekView]: AutoOpenPeekViewWhen;
	[TestingConfigKeys.AutoOpenPeekViewDuringAutoRun]: boolean;
	[TestingConfigKeys.FollowRunningTest]: boolean;
}

export const getTestingConfiguration = <K extends TestingConfigKeys>(config: IConfigurationService, key: K) => config.getValue<ITestingConfiguration[K]>(key);


text:
#include <Inventor/annex/HardCopy/SoVectorOutput.h>

#include <Inventor/SbBasic.h>

#include "tidbitsp.h"

// *************************************************************************

/*!
  \class SoVectorOutput SoVectorOutput.h Inventor/annex/HardCopy/SoVectorOutput.h
  \brief The SoVectorOutput class is used for setting vector output file.
  \ingroup hardcopy

  SoVectorizeAction will create an SoVectorOutput which will output
  to stdout by default. SoVectorizeAction::getOutput() can be used to
  fetch this output, and the user will probably want to set a
  file to output to.

  \since Coin 2.1
  \since TGS provides HardCopy support as a separate extension for TGS Inventor.
*/

class SoVectorOutputP {
public:
  FILE * fp;
  SbBool didopen;
};

#define PRIVATE(p) (p->pimpl)
#define PUBLIC(p) (p->publ)

// *************************************************************************

/*!
  Constructor. Will make this instance output to \e stdout.
*/
SoVectorOutput::SoVectorOutput(void)
{
  PRIVATE(this) = new SoVectorOutputP;
  PRIVATE(this)->fp = coin_get_stdout();
  PRIVATE(this)->didopen = FALSE;
}

/*!
  Destructor. Will close the file opened in openFile().
*/
SoVectorOutput::~SoVectorOutput()
{
  this->closeFile();
  delete PRIVATE(this);
}

// *************************************************************************

/*!
  Opens \a filename for output. Returns \e FALSE if file could not be
  opened for writing. If the file already exists, it will be
  truncated.
 */
SbBool
SoVectorOutput::openFile(const char * filename)
{
  this->closeFile();

  FILE * fp = fopen(filename, "wb");
  if (fp) {
    PRIVATE(this)->fp = fp;
    PRIVATE(this)->didopen = TRUE;
  }
  return fp != NULL;
}

/*!
  Closes the file opened in openFile()
*/
void
SoVectorOutput::closeFile(void)
{
  if (PRIVATE(this)->didopen) {
    fclose(PRIVATE(this)->fp);
    PRIVATE(this)->fp = stdout;
    PRIVATE(this)->didopen = FALSE;
  }
}

/*!
  Returns the \e stdio file handle pointer.
*/
FILE *
SoVectorOutput::getFilePointer(void)
{
  return PRIVATE(this)->fp;
}

#undef PRIVATE
#undef PUBLIC


text:
namespace Google.Cloud.Tasks.V2.Snippets
{
    // [START cloudtasks_v2_generated_CloudTasks_ListTasks_async]
    using Google.Api.Gax;
    using System;
    using System.Linq;
    using System.Threading.Tasks;
    using gctv = Google.Cloud.Tasks.V2;

    public sealed partial class GeneratedCloudTasksClientSnippets
    {
        /// <summary>Snippet for ListTasksAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated and should be regarded as a code template only.
        /// It will require modifications to work:
        /// - It may require correct/in-range values for request initialization.
        /// - It may require specifying regional endpoints when creating the service client as shown in
        ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
        /// </remarks>
        public async Task ListTasksRequestObjectAsync()
        {
            // Create client
            CloudTasksClient cloudTasksClient = await CloudTasksClient.CreateAsync();
            // Initialize request argument(s)
            ListTasksRequest request = new ListTasksRequest
            {
                ParentAsQueueName = QueueName.FromProjectLocationQueue("[PROJECT]", "[LOCATION]", "[QUEUE]"),
                ResponseView = gctv::Task.Types.View.Unspecified,
            };
            // Make the request
            PagedAsyncEnumerable<ListTasksResponse, gctv::Task> response = cloudTasksClient.ListTasksAsync(request);

            // Iterate over all response items, lazily performing RPCs as required
            await response.ForEachAsync((gctv::Task item) =>
            {
                // Do something with each item
                Console.WriteLine(item);
            });

            // Or iterate over pages (of server-defined size), performing one RPC per page
            await response.AsRawResponses().ForEachAsync((ListTasksResponse page) =>
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (gctv::Task item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            });

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page<gctv::Task> singlePage = await response.ReadPageAsync(pageSize);
            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (gctv::Task item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
        }
    }
    // [END cloudtasks_v2_generated_CloudTasks_ListTasks_async]
}


text:
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';
import { AccessibilityModule, ColorServiceModule, IconModule, ToolbarSearchModule, TypeaheadModule } from '@ux-aspects/ux-aspects';
import { ToolbarSearchTypeaheadTestPageComponent } from './toolbar-search-typeahead/toolbar-search-typeahead.testpage.component';
import { ToolbarSearchTestPageComponent } from './toolbar-search.testpage.component';

@NgModule({
    imports: [
        CommonModule,
        FormsModule,
        TypeaheadModule,
        ReactiveFormsModule,
        ToolbarSearchModule,
        ColorServiceModule,
        AccessibilityModule,
        IconModule,
        RouterModule.forChild([
            {
                path: '',
                component: ToolbarSearchTestPageComponent
            },
            {
                path: 'toolbar-search-typeahead',
                component: ToolbarSearchTypeaheadTestPageComponent
            }
        ])
    ],
    declarations: [
        ToolbarSearchTestPageComponent,
        ToolbarSearchTypeaheadTestPageComponent
    ],
})
export class ToolbarSearchTestPageModule {

}


text:
<?php

namespace app\models\b2b2c;

use Yii;

/**
 * This is the model class for table "t_act_scope".
 *
 * @property string $id
 * @property string $act_id
 * @property string $brand_id
 * @property string $product_id
 * @property string $product_type_id
 *
 * @property ProductType $productType
 * @property Activity $act
 * @property ProductBrand $brand
 * @property Product $product
 */
class ActScope extends \app\models\b2b2c\BasicModel
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 't_act_scope';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['act_id'], 'required'],
            [['act_id', 'brand_id', 'product_id', 'product_type_id'], 'integer'],
            [['product_type_id'], 'exist', 'skipOnError' => true, 'targetClass' => ProductType::className(), 'targetAttribute' => ['product_type_id' => 'id']],
            [['act_id'], 'exist', 'skipOnError' => true, 'targetClass' => Activity::className(), 'targetAttribute' => ['act_id' => 'id']],
            [['brand_id'], 'exist', 'skipOnError' => true, 'targetClass' => ProductBrand::className(), 'targetAttribute' => ['brand_id' => 'id']],
            [['product_id'], 'exist', 'skipOnError' => true, 'targetClass' => Product::className(), 'targetAttribute' => ['product_id' => 'id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', '主键'),
            'act_id' => Yii::t('app', '关联活动编号'),
            'brand_id' => Yii::t('app', '关联品牌编号'),
            'product_id' => Yii::t('app', '关联产品编号'),
            'product_type_id' => Yii::t('app', '关联产品分类编号'),
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getProductType()
    {
        return $this->hasOne(ProductType::className(), ['id' => 'product_type_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getAct()
    {
        return $this->hasOne(Activity::className(), ['id' => 'act_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getBrand()
    {
        return $this->hasOne(ProductBrand::className(), ['id' => 'brand_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getProduct()
    {
        return $this->hasOne(Product::className(), ['id' => 'product_id']);
    }
}


text:
import Autocomplete from "react-autocomplete";
import React from "react";
import Icon from "../Icon/Icon";
import Translate from "react-translate-component";
import cnames from "classnames";

export default class TypeAhead extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            value: this.props.defaultValue
        };
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.value && nextProps.value != this.state.value) {
            this.setState({value: nextProps.value});
        }
        if (nextProps.value === undefined)
            this.setState({
                value: nextProps.defaultValue
            });
    }

    onClick = () => {
        // Timer is used to keep menu from popping back open due to order of blur then click event
        if (this.blockClick) {
            return;
        }
        const {isMenuShowing} = this.state || {};
        this.setState({isMenuShowing: !isMenuShowing, filter: ""}, () => {
            const {autocomplete} = this.refs;
            autocomplete.refs.input.focus();
        });
    };

    onChange = e => {
        this.setState({filter: e.target.value});
        if (this.props.onChange) {
            this.props.onChange(e.target.value);
        }
    };

    onSelect(value) {
        let asset = null;
        let disabled = false;
        this.props.items.forEach(item => {
            if (value == item.id && item.disabled) disabled = true;
            if (value == item.id) asset = item;
        });

        if (disabled) return;

        this.setState({value, filter: "", isMenuShowing: false});
        if (this.props.onSelect) this.props.onSelect(value, asset);
    }

    renderInput = props => {
        const {isMenuShowing} = this.state || {};
        return isMenuShowing ? (
            <input {...props} style={TypeAhead.inputStyle} />
        ) : null;
    };

    dropDown = () => {
        const {props, state} = this;
        const {filter = "", isMenuShowing} = state;
        let inputProps = props.inputProps || {};

        if (props.tabIndex) inputProps.tabIndex = props.tabIndex;
        return (
            <Autocomplete
                renderInput={this.renderInput}
                ref="autocomplete"
                items={
                    props.items || [
                        {id: "foo", label: "foo"},
                        {id: "bar", label: "bar"},
                        {id: "baz", label: "baz"}
                    ]
                }
                shouldItemRender={({label}) =>
                    label.toLowerCase().indexOf(filter.toLowerCase()) > -1
                }
                getItemValue={this.getValueFromItem}
                renderItem={this.renderItem}
                value={filter}
                onChange={this.onChange}
                onSelect={this.onSelect.bind(this)}
                inputProps={{...inputProps, onBlur: this.onBlur}}
                menuStyle={TypeAhead.menuStyle}
                wrapperProps={{
                    className: isMenuShowing ? "typeahead__innerList" : ""
                }}
                wrapperStyle={{
                    display: "block"
                }}
                open={isMenuShowing}
            />
        );
    };

    onBlur = () => {
        // Timer is used to keep menu from popping back open due to order of blur then click event
        this.timer && clearTimeout(this.timer);
        this.blockClick = true;
        this.setState({isMenuShowing: false});
        this.timer = setTimeout(() => {
            this.blockClick = false;
        }, 300); // Magic number that seems fast and slow enough for events and render to complete
    };

    static inputStyle = {
        marginTop: 4
    };

    // Suggestion Menu List
    static menuStyle = {
        borderBottomRightRadius: 3,
        borderBottomLeftRadius: 3,
        boxShadow: "0 2px 12px rgba(0, 0, 0, 0.1)",
        paddingBottom: 0,
        marginTop: 5,
        marginLeft: 0,
        width: "100%",
        maxWidth: 436,
        fontSize: "90%",
        position: "",
        overflowX: "visible",
        overflowY: "scroll",
        maxHeight: "10rem",
        zIndex: 1
    };

    renderItem = (item, highlighted) => {
        const isDisabled = item.disabled;
        const className = item.className ? item.className : null;
        return (
            <div
                key={item.id}
                className={cnames(
                    "typeahead__innerItem",
                    highlighted ? " typeahead__innerItem_highlighted" : "",
                    className
                )}
            >
                <span
                    className={
                        isDisabled ? "typeahead__innerItem__disabled" : ""
                    }
                >
                    {item.label}
                </span>
                <span
                    style={{
                        float: "right",
                        fontSize: "90%",
                        textTransform: "uppercase"
                    }}
                >
                    {item.status}
                </span>
            </div>
        );
    };

    getValueFromItem = item => item.label;

    selectedDisplay = () => {
        const {value} = this.state;
        return (
            <div onClick={this.onClick} className="typeahead__input">
                {value}
            </div>
        );
    };

    render() {
        const {isMenuShowing} = this.state || {};

        const style = isMenuShowing ? this.props.typeaheadVisibleStyle : {};

        return (
            <div
                className="typeahead"
                style={style} // Something is making the typeahead take less space when dropdown is open. Add extra padding for now...
            >
                {!!this.props.label ? (
                    <label className="left-label">
                        <Translate content={this.props.label} />
                    </label>
                ) : null}
                {this.selectedDisplay()}
                {this.dropDown()}
                <Icon
                    onClick={this.onClick}
                    name="chevron-down"
                    title="icons.chevron_down.other"
                    style={{
                        position: "absolute",
                        right: 10,
                        top: !!this.props.label ? 35 : 7,
                        transform: isMenuShowing ? "rotate(180deg)" : null
                    }}
                />
            </div>
        );
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>info.source4code</groupId>
    <artifactId>mockito-powermock-facescontext</artifactId>
    <version>1.0</version>
    <packaging>jar</packaging>

    <name>Mockito - Mocking FacesContext using PowerMock</name>
    <url>http://www.source4code.info/2014/11/mockito-mocking-facescontext-using.html</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.6</java.version>

        <junit.version>4.11</junit.version>
        <mockito.version>1.10.8</mockito.version>
        <powermock.version>1.5.6</powermock.version>

        <el.version>2.2.1-b04</el.version>
        <jsf.version>2.2.8-02</jsf.version>

        <maven-compiler-plugin.version>3.1</maven-compiler-plugin.version>
    </properties>

    <dependencies>
        <!-- JUnit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <!-- Mockito -->
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <version>${mockito.version}</version>
            <scope>test</scope>
        </dependency>
        <!-- PowerMock -->
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-module-junit4</artifactId>
            <version>${powermock.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-api-mockito</artifactId>
            <version>${powermock.version}</version>
            <scope>test</scope>
        </dependency>
        <!-- EL (Unified Expression Language) -->
        <dependency>
            <groupId>javax.el</groupId>
            <artifactId>el-api</artifactId>
            <version>${el.version}</version>
            <scope>test</scope>
        </dependency>
        <!-- JSF -->
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-api</artifactId>
            <version>${jsf.version}</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven-compiler-plugin.version}</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


text:
Tuenti for Android TV [![Android Arsenal](https://img.shields.io/badge/Android%20Arsenal-TuentiTV-brightgreen.svg?style=flat)](https://android-arsenal.com/details/3/1465)
=====================

Sample project created to show some of the most important features related to Android TV projects. This little sample uses mocked data to simulate an application working with information from Tuenti servers.

In this repository you are going to find some interesting samples to work with Android TV like:

* How to configure Android dependencies to create an Android TV application. **Leanback** is the most important dependency.
* Hos to configure an Activity to work as **Launcher Activity** for Android TV projects.
* How to extend from **Leanback BrowseFragment** to create the main view of this project.
* How to extend from **Leanback DetailsFragment** to create the detail view of this project.
* How to extend from **Leanback SearchFragment** to create the search view of this project.
* How to show Android TV **recommendations**.
* How to create a **custom Activity/Fragment without Leanback** library help for Android TV.
* How to use **View Focus** to create custom Activities/Fragments for Android TV and different focus features added for Android TV like **nextFocusDown**.
* How to use **<requestFocus/>** xml tag inside your layouts.
* How to use **State List Animators** to improve your application UI/UX.
* How to change **Activities/Fragments background** to improve your views.
* How to capture Android TV **DPAD events**.
* How to **create your own presenters** to use with **ArrayObjectAdapter**.

Implementation description
--------------------------

[Tuenti for Android TV - Blog Post][1]

[Working with Android TV Slides - English][2]

Video Demo
----------

[Tuenti TV Project - Video] [3]

Screenshots
------------

![Demo Screenshot 1][4]
![Demo Screenshot 2][5]
![Demo Screenshot 3][6]
![Demo Screenshot 4][7]
![Demo Screenshot 5][8]
![Demo Screenshot 6][9]
![Demo Screenshot 7][10]
![Demo Screenshot 8][11]

Libraries used on the sample project
------------------------------------

* [Dagger][12]
* [Butterknife][13]
* [Picasso][14]

Developed By
------------

* Pedro Vicente Gómez Sánchez - <pedrovicente.gomez@gmail.com>

License
-------

    Copyright 2014 Pedro Vicente Gómez Sánchez

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

[1]: http://corporate.tuenti.com/es/dev/blog/Tuenti-for-Android-TV
[2]: http://www.slideshare.net/PedroVicenteGmezSnch/working-with-android-tv-english
[3]: https://www.youtube.com/watch?v=cHrFp69qZVA
[4]: ./art/screenshot1.png
[5]: ./art/screenshot2.png
[6]: ./art/screenshot3.png
[7]: ./art/screenshot4.png
[8]: ./art/screenshot5.png
[9]: ./art/screenshot6.png
[10]: ./art/screenshot7.png
[11]:  ./art/screenshot8.png
[12]: https://github.com/square/dagger
[13]: https://github.com/JakeWharton/butterknife
[14]: https://github.com/square/picasso


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

<meta http-equiv="Content-Type" content="text/html; charset=utf8">
<title>A-Index</title>
<meta name="date" content="2017-06-01">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D E F G K L M N P R S T U V

A

actionPerformed(ActionEvent) - Method in class projet_POO.ButtonKit

Capture et comportement à adopter suite à un clic souris sur un
 des boutons.

actionPerformed(ActionEvent) - Method in class projet_POO.Export

actionPerformed(ActionEvent) - Method in class projet_POO.MenuPrincipal

Réponse à l'action de l'utilisation sur le menu.

activerB() - Method in class projet_POO.ButtonKit

Activation de l'ensemble des boutons.

activerB1() - Method in class projet_POO.ButtonKit

Activation du bouton de lancement de graphique.

activerB2() - Method in class projet_POO.ButtonKit

Activation du bouton d'export.

activerB3() - Method in class projet_POO.ButtonKit

Activation de la checkbox.

afficher() - Method in class projet_POO.CompoundCaracteristic

Retourne un texte contenant la description du composé.

afficher() - Method in class projet_POO.ReactionCaracteristic

Retourne un texte contenant la description de la réaction.

A B C D E F G K L M N P R S T U V

Skip navigation links

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes