text:
package fi.csc.microarray.client.operation;

import java.awt.Color;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import org.apache.log4j.Logger;

import fi.csc.microarray.client.operation.OperationDefinition.Suitability;
import fi.csc.microarray.client.operation.parameter.Parameter;
import fi.csc.microarray.databeans.DataBean;
import fi.csc.microarray.description.SADLSyntax.InputType;
import fi.csc.microarray.exception.MicroarrayException;

/**
 * Operation is a concrete representative of an OperationDefinition, one with
 * unique parameters and a dataset associated to it. The parameters for a new
 * Operation are cloned from its definition object. Much other data is obtained
 * directly from the definition.
 *
 * @author Janne Käki, Aleksi Kallio, hupponen
 *
 */
public class Operation implements ExecutionItem {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(Operation.class);

	public static class DataBinding {

		private DataBean data;
		private String name;
		private InputType inputType;

		public DataBinding(DataBean data, String name, InputType inputType) {
			this.data = data;
			this.name = name;
			this.inputType = inputType;
		}

		public DataBean getData() {
			return data;
		}

		public String getName() {
			return name;
		}

		public InputType getInputType() {
			return inputType;
		}
	}

	private OperationDefinition definition;
	private LinkedList<DataBinding> bindings = new LinkedList<DataBinding>();
	private LinkedList<Parameter> parameters;
	private ResultListener resultListener;

	public static interface ResultListener {
		public void resultData(Iterable<DataBean> results);
		public void noResults();
	}

	/**
	 * Creates a new operation from the given definition and binds the given
	 * beans.
	 *
	 * @param definition
	 * @param data
	 * @throws MicroarrayException
	 * @throws MicroarrayException
	 */
	public Operation(OperationDefinition definition, DataBean[] beans) throws MicroarrayException {
		logger.debug("created operation from definition " + definition.getID());
		this.definition = definition;
		this.parameters = Parameter.cloneParameters(definition.getParameters());
		bindInputs(beans);
	}

	/**
	 * Creates a clone of the given operation, with initially identical yet
	 * distinct attributes (such as parameters, which in turn are clones of the
	 * originals) but without a ParameterPanel.
	 *
	 * @param o
	 *            The operation to be cloned.
	 * @throws MicroarrayException
	 */
	public Operation(Operation o) throws MicroarrayException {
		logger.debug("cloned operation from " + o.getID());
		this.definition = o.definition;
		if (o.bindings != null) {
			this.bindings = o.bindings;
		} else {
			this.bindings = new LinkedList<DataBinding>();
		}
		this.parameters = Parameter.cloneParameters(o.getParameters());
	}

	/**
	 * @return The OperationDefinition from which this operation is derived.
	 */
	public OperationDefinition getDefinition() {
		return definition;
	}

	/**
	 * @return An array of this operation's parameters.
	 */
	public LinkedList<Parameter> getParameters() {
		return parameters;
	}

	/**
	 * @param beans operation input beans to bind
	 * @throws MicroarrayException
	 */
	public void bindInputs(DataBean[] beans) throws MicroarrayException {
		this.bindings = definition.bindInputs(Arrays.asList(beans)).bindings;
		if (bindings == null) {
			bindings = new LinkedList<DataBinding>();
		}

		// update bindings to parameters
		for (Parameter parameter : parameters) {
			parameter.setDataBindings(this.bindings);
		}
	}

	public void clearBindings() {
		this.bindings.clear();
	}

	public List<DataBinding> getBindings() {
		return bindings;
	}

	/**
	 *
	 * @param name
	 * @return null if a binding with the given name does not exist
	 */
	public DataBinding getBinding(String name) {
		for (DataBinding binding : bindings) {
			if (binding.getName().equals(name)) {
				return binding;
			}
		}
		return null;
	}

	/**
	 * Set new input file bindings.
	 */
	public void setBindings(List<DataBinding> currentBindings) {
	    if (currentBindings != null) {
	    	this.bindings = new LinkedList<>(currentBindings);
	    } else {
	    	this.bindings = new LinkedList<DataBinding>();
	    }
	}

	/**
	 * @return The name of this operation (actually, of its definition).
	 */
	public String getID() {
		return definition.getID();
	}

	/**
	 * @return A String description of this operation's purpose (actually taken
	 *         directly from its definition).
	 */
	public String getDescription() {
		return definition.getDescription();
	}

	/**
	 * @return The name of the operation category to which this belongs.
	 */
	public String getCategoryName() {
		return definition.getCategory().getName();
	}

	/**
	 * @return The visualization color of the category
	 */
	public Color getCategoryColor() {
		return definition.getCategory().getColor();
	}

	/**
	 * @return A short String representation of this operation, consisting of
	 *         operation (definition's) name and the eventual dataset for which
	 *         it is assigned.
	 */
	public String toString() {
		return definition.getID();
	}

	/**
	 * Evaluates the suitability of this operation for the given dataset
	 * and current parameter values.
	 *
	 * @param data
	 *            The dataset for which to evaluate.
	 * @return One of the OperationDefinition.Suitability enumeration, depending
	 *         on how suitable the operation is judged.
	 */
	@Override
	public Suitability evaluateSuitabilityFor(Iterable<DataBean> data, List<DataBinding> bindings) {

	    // Check parameters and inputs
	    Suitability parameterSuitability =
	        OperationDefinition.evaluateParameterSuitability(getParameters());
	    Suitability inputSuitability = definition.evaluateSuitabilityFor(data, bindings);

	    // Return ok suitability only when both are ok
	    if (inputSuitability.isOk()) {
	    	return parameterSuitability;
	    }  else {
	    	return inputSuitability;
	    }
	}

	/**
	 * Used in client scripting.
	 */
	public void setParameter(String name, Object value) {
		getParameter(name).setValue(value);
	}

	public void parseParameter(String name, String stringValue) {
		getParameter(name).parseValue(stringValue);
	}

	public Parameter getParameter(String name) {
		for (Parameter parameter : parameters) {
			if (parameter.getID().equals(name)) {
				return parameter;
			}
		}
		return null;
	}

	public int getColorCount() {
		return definition.getColorCount();
	}

	public ResultListener getResultListener() {
		return resultListener;
	}

	public void setResultListener(ResultListener resultListener) {
		this.resultListener = resultListener;
	}

	public String getDisplayName() {
		return definition.getDisplayName();
	}
}


text:
```sh
git remote add rest-app git@github.com:owl-framework/rest-app.git
git subtree push --prefix=examples/rest-app/ rest-app master
```

```sh
git remote add mvc-app git@github.com:owl-framework/mvc-app.git
git subtree push --prefix=examples/mvc-app/ mvc-app master
```

redpajama_set_name: RedPajamaGithub


text:
package org.jasig.portal.events.aggr.dao;

import java.util.List;
import java.util.Set;

import org.jasig.portal.events.aggr.AcademicTermDetail;
import org.jasig.portal.events.aggr.AggregatedGroupConfig;
import org.jasig.portal.events.aggr.AggregatedIntervalConfig;
import org.jasig.portal.events.aggr.IEventAggregatorStatus;
import org.jasig.portal.events.aggr.IPortalEventAggregator;
import org.jasig.portal.events.aggr.QuarterDetail;
import org.joda.time.DateMidnight;

/**
 * Operations central to the management of portal event aggregation
 *
 * @author Eric Dalquist
 * @version $Revision$
 */
public interface IEventAggregationManagementDao {
    /**
     * Get the aggregation status for the specified processing type
     */
    IEventAggregatorStatus getEventAggregatorStatus(IEventAggregatorStatus.ProcessingType processingType, boolean create);

    /**
     * Update changes to the aggregation status object
     */
    void updateEventAggregatorStatus(IEventAggregatorStatus eventAggregatorStatus);

    /**
     * All aggregated group configurations
     */
    Set<AggregatedGroupConfig> getAggregatedGroupConfigs();

    /**
     * Default group includes/excludes, applied to all aggregators that do not have specific configurations.
     */
    AggregatedGroupConfig getDefaultAggregatedGroupConfig();

    /**
     * Get the aggregated group configuration for the specified aggregator
     */
    AggregatedGroupConfig getAggregatedGroupConfig(Class<? extends IPortalEventAggregator> aggregatorType);

    /**
     * Create config for specified aggregator
     */
    AggregatedGroupConfig createAggregatedGroupConfig(Class<? extends IPortalEventAggregator> aggregatorType);

    /**
     * Store changes made to the specified config
     */
    void updateAggregatedGroupConfig(AggregatedGroupConfig aggregatedGroupConfig);

    /**
     * Delete the specified configuration
     */
    void deleteAggregatedGroupConfig(AggregatedGroupConfig aggregatedGroupConfig);

    /**
     * @return All aggregated interval configurations
     */
    Set<AggregatedIntervalConfig> getAggregatedIntervalConfigs();

    /**
     * Default interval includes/excludes, applied to all aggregators that do not have specific configurations.
     */
    AggregatedIntervalConfig getDefaultAggregatedIntervalConfig();

    /**
     * Get the aggregated interval configuration for the specified aggregator
     */
    AggregatedIntervalConfig getAggregatedIntervalConfig(Class<? extends IPortalEventAggregator> aggregatorType);

    /**
     * Create config for specified aggregator
     */
    AggregatedIntervalConfig createAggregatedIntervalConfig(Class<? extends IPortalEventAggregator> aggregatorType);

    /**
     * Store changes made to the specified config
     */
    void updateAggregatedIntervalConfig(AggregatedIntervalConfig aggregatedIntervalConfig);

    /**
     * Delete the specified configuration
     */
    void deleteAggregatedIntervalConfig(AggregatedIntervalConfig aggregatedIntervalConfig);

    /**
     * An immutable list of the configured quarter details sorted by its natural ordering
     */
    List<QuarterDetail> getQuartersDetails();

    /**
     * Erase the existing quarter configuration and use the provided.
     * @param quarterDetail Must contain four sequential quarters with no gaps between dates
     */
    void setQuarterDetails(List<QuarterDetail> quarterDetail);

    /**
     * An immutable list of the currently configured academic terms sorted by its natural ordering
     */
    List<AcademicTermDetail> getAcademicTermDetails();

    /**
     * Adds a new academic term, if the term overlaps with an existing term an exception
     * will be thrown.
     */
    void addAcademicTermDetails(DateMidnight start, DateMidnight end, String termName);

    /**
     * Update the specified term details
     */
    void updateAcademicTermDetails(AcademicTermDetail academicTermDetail);

    /**
     * Delete the specified term details
     */
    void deleteAcademicTermDetails(AcademicTermDetail academicTermDetail);
}


text:
<?php
/*
	This file is part of Authake.

	Author: Jérôme Combaz (jakecake/velay.greta.fr)
	Contributors: Mutlu Tevfik Kocak (mtkocak.net)

	Authake is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	Authake is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with Foobar.  If not, see <http://www.gnu.org/licenses/>.
*/
App::uses('AppController', 'Controller');
//App::uses('PagesController', 'Controller');
class AuthakeAppController extends AppController {
	var $helpers = array('Time', 'Authake.Htmlbis');
	function __makePassword($password1, $password2) {

		if ($password1 != $password2)
		{
			$this->Session->setFlash(__('The two passwords do not match!'), 'error');
			return false;
		}

		return md5($password1);
	}

	function beforeFilter(){
		parent::beforeFilter();
		$this->layout = 'authake';
	}
}


text:
require 'rails/generators/base'
require 'rails/generators/resource_helpers'

module SunshineRailsGenerators
  module Admin
    class LayoutGenerator < Rails::Generators::Base

      namespace "su:admin:layout"
      source_root File.expand_path("../templates", __FILE__)

      def create_admin_layout
        template "admin.html.erb.tt", File.join('app/views/layouts', "admin.html.erb")
      end

      protected

      def app_name
        File.basename(destination_root).tr('\\', '').tr(". ", "_")
      end

      def app_const_base
        app_name.gsub(/\W/, '_').squeeze('_').camelize
      end

      def app_const_base_upcased
        app_name.gsub(/\W/, '_').squeeze('_').upcase
      end

      alias :camelized :app_const_base
      alias :upcased :app_const_base_upcased
    end
  end
end


text:
#ifndef SVGPointList_h
#define SVGPointList_h

#if ENABLE(SVG)
#include "QualifiedName.h"
#include "SVGPropertyTraits.h"
#include <wtf/Vector.h>

namespace WebCore {

class FloatPoint;

class SVGPointList : public Vector<FloatPoint> {
public:
    SVGPointList() { }

    String valueAsString() const;
};

template<>
struct SVGPropertyTraits<SVGPointList> {
    static SVGPointList initialValue() { return SVGPointList(); }
    typedef FloatPoint ListItemType;
};

} // namespace WebCore

#endif // ENABLE(SVG)
#endif


text:
package com.nickname;

public class Main {

    public static void main(String[] args) {
	// write your code here
    }
}


text:
import json
from jsonschema import validate

class JsonUtils:

    @classmethod
    def loads(cls, _str):
        return json.loads(_str)

    @classmethod
    def to_json(cls, obj):
        return json.dumps(obj, indent=2)

    @classmethod
    def validate_json(cls, json_obj, json_schema_obj):
        validate(json_obj, json_schema_obj)


text:
/*
 * As omapdss panel drivers are omapdss specific, but we want to define the
 * DT-data in generic manner, we convert the compatible strings of the panel and
 * encoder nodes from "panel-foo" to "omapdss,panel-foo". This way we can have
 * both correct DT data and omapdss specific drivers.
 *
 * When we get generic panel drivers to the kernel, this file will be removed.
 */

#include <linux/kernel.h>
#include <linux/of.h>
#include <linux/of_graph.h>
#include <linux/slab.h>
#include <linux/list.h>

static struct list_head dss_conv_list __initdata;

static const char prefix[] __initconst = "omapdss,";

struct dss_conv_node {
	struct list_head list;
	struct device_node *node;
	bool root;
};

static int __init omapdss_count_strings(const struct property *prop)
{
	const char *p = prop->value;
	int l = 0, total = 0;
	int i;

	for (i = 0; total < prop->length; total += l, p += l, i++)
		l = strlen(p) + 1;

	return i;
}

static void __init omapdss_update_prop(struct device_node *node, char *compat,
	int len)
{
	struct property *prop;

	prop = kzalloc(sizeof(*prop), GFP_KERNEL);
	if (!prop)
		return;

	prop->name = "compatible";
	prop->value = compat;
	prop->length = len;

	of_update_property(node, prop);
}

static void __init omapdss_prefix_strcpy(char *dst, int dst_len,
	const char *src, int src_len)
{
	size_t total = 0;

	while (total < src_len) {
		size_t l = strlen(src) + 1;

		strcpy(dst, prefix);
		dst += strlen(prefix);

		strcpy(dst, src);
		dst += l;

		src += l;
		total += l;
	}
}

/* prepend compatible property strings with "omapdss," */
static void __init omapdss_omapify_node(struct device_node *node)
{
	struct property *prop;
	char *new_compat;
	int num_strs;
	int new_len;

	prop = of_find_property(node, "compatible", NULL);

	if (!prop || !prop->value)
		return;

	if (strnlen(prop->value, prop->length) >= prop->length)
		return;

	/* is it already prefixed? */
	if (strncmp(prefix, prop->value, strlen(prefix)) == 0)
		return;

	num_strs = omapdss_count_strings(prop);

	new_len = prop->length + strlen(prefix) * num_strs;
	new_compat = kmalloc(new_len, GFP_KERNEL);

	omapdss_prefix_strcpy(new_compat, new_len, prop->value, prop->length);

	omapdss_update_prop(node, new_compat, new_len);
}

static void __init omapdss_add_to_list(struct device_node *node, bool root)
{
	struct dss_conv_node *n = kmalloc(sizeof(struct dss_conv_node),
		GFP_KERNEL);
	if (n) {
		n->node = node;
		n->root = root;
		list_add(&n->list, &dss_conv_list);
	}
}

static bool __init omapdss_list_contains(const struct device_node *node)
{
	struct dss_conv_node *n;

	list_for_each_entry(n, &dss_conv_list, list) {
		if (n->node == node)
			return true;
	}

	return false;
}

static void __init omapdss_walk_device(struct device_node *node, bool root)
{
	struct device_node *n;

	omapdss_add_to_list(node, root);

	/*
	 * of_graph_get_remote_port_parent() prints an error if there is no
	 * port/ports node. To avoid that, check first that there's the node.
	 */
	n = of_get_child_by_name(node, "ports");
	if (!n)
		n = of_get_child_by_name(node, "port");
	if (!n)
		return;

	of_node_put(n);

	n = NULL;
	while ((n = of_graph_get_next_endpoint(node, n)) != NULL) {
		struct device_node *pn;

		pn = of_graph_get_remote_port_parent(n);

		if (!pn)
			continue;

		if (!of_device_is_available(pn) || omapdss_list_contains(pn)) {
			of_node_put(pn);
			continue;
		}

		omapdss_walk_device(pn, false);
	}
}

static const struct of_device_id omapdss_of_match[] __initconst = {
	{ .compatible = "ti,omap2-dss", },
	{ .compatible = "ti,omap3-dss", },
	{ .compatible = "ti,omap4-dss", },
	{ .compatible = "ti,omap5-dss", },
	{ .compatible = "ti,dra7-dss", },
	{},
};

static int __init omapdss_boot_init(void)
{
	struct device_node *dss, *child;

	INIT_LIST_HEAD(&dss_conv_list);

	dss = of_find_matching_node(NULL, omapdss_of_match);

	if (dss == NULL || !of_device_is_available(dss))
		return 0;

	omapdss_walk_device(dss, true);

	for_each_available_child_of_node(dss, child) {
		if (!of_find_property(child, "compatible", NULL))
			continue;

		omapdss_walk_device(child, true);
	}

	while (!list_empty(&dss_conv_list)) {
		struct dss_conv_node *n;

		n = list_first_entry(&dss_conv_list, struct dss_conv_node,
			list);

		if (!n->root)
			omapdss_omapify_node(n->node);

		list_del(&n->list);
		of_node_put(n->node);
		kfree(n);
	}

	return 0;
}

subsys_initcall(omapdss_boot_init);


text:
#ifndef ALI_MP_SEGMENTATION_H
#define ALI_MP_SEGMENTATION_H

// $Id$
// $MpId: AliMpSegmentation.h,v 1.7 2006/05/24 13:58:16 ivana Exp $

/// \ingroup management
/// \class AliMpSegmentation
/// \brief Singleton container class for mapping segmentations
///
/// It provides access to mapping segmentations based on the
/// AliMpVSegmentation interface and to segmentations underlying
/// detectors (sector, slat, trigger).                                  \n
/// Mapping segmentations for all detection elements
/// are created at the first call to AliMpSegmentation::Instance().
/// The class is a singleton, it has all constructors
/// private, except for the special constructor for Root I/O.
///
/// \author Ivana Hrivnacova, IPN Orsay; Laurent Aphecetche, SUBATECH

#ifndef ROOT_TObject
#  include <TObject.h>
#endif

#ifndef ALI_MP_STRING_OBJ_MAP_H
#  include "AliMpStringObjMap.h"
#endif

#ifndef ALI_MP_EX_MAP_H
#  include "AliMpExMap.h"
#endif

#ifndef ALI_MP_CATHOD_TYPE_H
#  include "AliMpCathodType.h"
#endif

class AliMpDEStore;
class AliMpSegmentation;
class AliMpVSegmentation;
class AliMpSlatMotifMap;
class AliMpDataStreams;
class AliMpSector;
class AliMpSlat;
class AliMpTrigger;
class TRootIOCtor;

using std::ofstream;

class AliMpSegmentation : public  TObject {

  public:
    AliMpSegmentation(TRootIOCtor* ioCtor);
    virtual ~AliMpSegmentation();

    // static methods
    static AliMpSegmentation* Instance(Bool_t warn = true);
    static AliMpSegmentation* ReadData(const AliMpDataStreams& dataStreams,
                                       Bool_t warn = true);

    // methods

    //
    // Access to segmentations
    //

    const AliMpVSegmentation* GetMpSegmentation(
                                 Int_t detElemId, AliMp::CathodType cath,
			         Bool_t warn = true) const;

    const AliMpVSegmentation* GetMpSegmentationByElectronics(
                                 Int_t detElemId, Int_t elCardID,
			         Bool_t warn = true) const;
    //
    // Access to sectors, slats, triggers
    //

    const AliMpSector*  GetSector(const AliMpVSegmentation* kSegmentation,
                                  Bool_t warn = true) const;
    const AliMpSector*  GetSector(Int_t detElemId, AliMp::CathodType cath,
                                  Bool_t warn = true) const;
    const AliMpSector*  GetSectorByElectronics(Int_t detElemId, Int_t elCardID,
                                  Bool_t warn = true) const;

    const AliMpSlat*    GetSlat(const AliMpVSegmentation* kSegmentation,
                                  Bool_t warn = true) const;
    const AliMpSlat*    GetSlat(Int_t detElemId, AliMp::CathodType cath,
                                  Bool_t warn = true) const;
    const AliMpSlat*    GetSlatByElectronics(Int_t detElemId, Int_t elCardID,
                                  Bool_t warn = true) const;

    const AliMpTrigger* GetTrigger(const AliMpVSegmentation* kSegmentation,
                                  Bool_t warn = true) const;
    const AliMpTrigger* GetTrigger(Int_t detElemId, AliMp::CathodType cath,
                                  Bool_t warn = true) const;
    const AliMpTrigger* GetTriggerByElectronics(Int_t detElemId, Int_t elCardID,
                                  Bool_t warn = true) const;

  private:
    AliMpSegmentation(const AliMpDataStreams& dataStreams);
    /// Not implemented
    AliMpSegmentation(const AliMpSegmentation& rhs);
    /// Not implemented
    AliMpSegmentation& operator=(const AliMpSegmentation& rhs);

    AliMpVSegmentation* CreateMpSegmentation(
                              const AliMpDataStreams& dataStreams,
                              Int_t detElemId, AliMp::CathodType cath);

    AliMpExMap* FillElCardsMap(Int_t detElemId);

    // static data members
    static AliMpSegmentation* fgInstance; ///< Singleton instance

    // data members
    AliMpDEStore*      fDetElements;    ///< Detection element store
    AliMpStringObjMap  fMpSegmentations;///< Map of mapping segmentations to DE seg names
    AliMpExMap         fElCardsMap;     ///< Map of el. cards IDs to segmentations
    AliMpSlatMotifMap* fSlatMotifMap;   ///< Map of motif, motifTypes to avoid duplications and allow proper deletion

  ClassDef(AliMpSegmentation,3)  // The factory for building mapping segmentations
};

#endif //ALI_MP_SEGMENTATION_H


text:
layout: post
title: UPSC Advt. No. 16 of 2015 for various Job last date 12th Nov-2015
date: 2015-10-24 17:11
comments: true
tags:  Chemist Director Engineer Geologist Geology Medical Officer Online Operations PSC Scientific Specialist UPSC
archive: false
---
UPSC invites Online application by 12/11/2015 for following  various posts in various Government of India Ministries and Departments in the prescribed format. The posts are :

- Assistant  Directors  of  Operations : 11 posts (SC-01,  ST-01, OBC-01, UR-08)  in  the Directorate  General  of  Civil  Aviation,  Ministry  of Civil  Aviation
- Senior  Scientific  Officers  Grade-  II (Electronics) : 04 posts (SC-01, OBC-01 & UR- 02) in Junior Time Scale of Defence Quality Assurance   Service  in the Directorate  General    of    Quality  Assurance,  Ministry  of  Defence,  Department  of Defence Production
- Specialist  Grade  III  Assistant  Professors (Cardiology) : 07 posts (SC-02, ST-01, OBC-01 & UR- 03) in Teaching Specialist Sub-cadre of Central Health Services, Ministry of Health & Family Welfare
- Specialist  Grade-III  Assistant  Professor {Cardio Vascular and Thoracic Surgery (CTVS)}) : 01 post in Teaching Specialist Sub-cadre of  Central  Health  Services,  Ministry  of  Health  &  Family  Welfare
- Assistant Chemists : 04 posts (SC-01,  OBC-01  &  UR-02) in Geological Survey of India,  Ministry  of  Mines
- Assistant Geologists : 139 posts (SC-21, ST-11, OBC-38 & UR- 69) in Geological Survey of India, Ministry of Mines
- Deputy  Director (ER) : 02 posts in  the  Office  of  the  Union  Public  Service  Commission
- Executive  Engineer  (Civil)/  Surveyor  of Works (Civil) : 01 post in  Government of National Capital Territory of Delhi, Irrigation & Flood Control Department

**How to Apply** :  Apply Online at UPSC Online website at <http://upsconline.nic.in/ora/VacancyNoticePub.php> on or before 12/11/2015 for advt. no. 15/2015.

For Details of posts, qualification, instructions and application format relating to Advt. No. 15/2015  please view <http://upsc.gov.in/recruitment/advt/2015/Advt_15_15_Emp_ORA.pdf>


text:
/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/util/utilfile.C $                                     */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* COPYRIGHT International Business Machines Corp. 2003,2014              */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
/**
  * @file utilfile.C
  *
  * @brief      Stream manipulation
  *
  * Used for creating and manipulating streams
  */

/*****************************************************************************/
// I n c l u d e s
/*****************************************************************************/

#include <util/utilfile.H>
#include <util/utilmem.H>
#include <errl/errlentry.H>
#include <vfs/vfs.H>

#include "utilbase.H"

using namespace Util;
using namespace ERRORLOG;

static const char UTIL_FILE_INVALID_NM[] = "";

/*****************************************************************************/
// Default Constructor
/*****************************************************************************/
UtilFile::UtilFile()
: iv_filePathName(NULL), iv_contents()
{
    UTIL_DT("UtilFile: Default Constructor, no filename yet");
    FileName(UTIL_FILE_INVALID_NM);
}

/*****************************************************************************/
// Constructor
/*****************************************************************************/
UtilFile::UtilFile(const char * i_filePathName)
: iv_filePathName(NULL), iv_contents()
{
    UTIL_DT("UtilFile: File name constructor invoked");
    FileName(i_filePathName);
}

/*****************************************************************************/
// Destructor
/*****************************************************************************/
UtilFile::~UtilFile()
{
    UTIL_DT("UtilFile: Destructor invoked on file: %s",iv_filePathName);

    // Eliminate prior errors
    // - this is done bcs close will abort if there are prior errors
    delete getLastError();

    // Close it up: only if it was created by us
    if ( strcmp( iv_filePathName, UTIL_FILE_INVALID_NM ) != 0 )
    {
        Close();
    }

    delete[] iv_filePathName;

    // Note: a lingering iv_lastError will be trashed
    //       by the base destructor

}

/*****************************************************************************/
// Does the file exist?
/*****************************************************************************/
bool UtilFile::exists( void ) const
{
    return VFS::module_exists(iv_filePathName);
}

/*****************************************************************************/
// Does the file exist?
/*****************************************************************************/
bool UtilFile::exists( const char *i_fileName )
{
    return VFS::module_exists(i_fileName);
}

/*****************************************************************************/
// Open the file opening the file in flash by default.
/*****************************************************************************/
void UtilFile::Open(
    const char * i_mode
    )
{
    do
    {
        if (iv_lastError)
        {
            UTIL_FT("E> UtilFile: Stream Operations Suspended on %s",
            iv_filePathName);
            break;
        }

        // Load module.
        iv_lastError = VFS::module_load(iv_filePathName);
        if (iv_lastError)
        {
            break;
        }

        // Get module address / size.
        const char* l_address = NULL;
        size_t      l_size = 0;

        iv_lastError = VFS::module_address(iv_filePathName, l_address, l_size);
        if (iv_lastError)
        {
            break;
        }

        // Create UtilMem object to overlay module location in memory.
        iv_contents.~UtilMem();
        new (&iv_contents) UtilMem(const_cast<char*>(l_address), l_size);

        iv_eof = iv_contents.eof();
        iv_lastError = iv_contents.getLastError();

    } while(0);
}

/*****************************************************************************/
// Open the file
/*****************************************************************************/
void UtilFile::Open(
    const char * i_file,
    const char * i_mode
)
{
    do
    {
        if (iv_lastError)
        {
            UTIL_FT("E> UtilFile: Stream Operations Suspended on %s",
                    iv_filePathName);
            break;
        }

        if (isOpen())
        {
            Close();
        }
        if (iv_lastError)
        {
            break;
        }

        FileName(i_file);
        Open(i_mode);

    } while(0);
}

/*****************************************************************************/
// Close the file
/*****************************************************************************/
void UtilFile::Close()
{
    do
    {

        if ( iv_lastError )
        {
            UTIL_FT("E> UtilFile: Stream operations suspended on %s",
                    iv_filePathName);
            break;
        }

        if (!isOpen())
        {
            UTIL_DT("E> UtilFile: %s not open", iv_filePathName);
            break;
        }

        // Reset underlying UtilMem.
        iv_contents = UtilMem();
        iv_eof = iv_contents.eof();

        // Unload module.
        iv_lastError = VFS::module_unload(iv_filePathName);

    } while(0);

}

/*****************************************************************************/
// Read the file
/*****************************************************************************/
uint32_t UtilFile::read(
    void *   o_buffer,
    uint32_t i_size
    )
{
    size_t l_rc = 0;

    do
    {
        if (iv_lastError)
        {
            UTIL_FT("E> UtilFile: Stream operations suspended on %s",
                    iv_filePathName);
            break;
        }

        l_rc = iv_contents.read(o_buffer, i_size);

        iv_eof = iv_contents.eof();
        iv_lastError = iv_contents.getLastError();

    } while(0);

    return l_rc;
}

/*****************************************************************************/
// Write the file
/*****************************************************************************/
uint32_t UtilFile::write(
    const void *i_buffer,
    uint32_t    i_size
    )
{
    assert(false, "E> UtilFile: Write attempted in Hostboot on %s",
           iv_filePathName);
    return 0;
}

/*****************************************************************************/
// Seek the file
/*****************************************************************************/
uint32_t UtilFile::seek(
    int     i_pos,
    whence  i_whence
    )
{
    uint32_t l_rc = 0;

    do
    {
        if (iv_lastError)
        {
            UTIL_FT("E> UtilFile: Stream operations suspended on %s",
                    iv_filePathName);
            break;
        }

        l_rc = iv_contents.seek(i_pos, i_whence);

        iv_eof = iv_contents.eof();
        iv_lastError = iv_contents.getLastError();

    } while(0);

    return l_rc;
}

/*****************************************************************************/
// Query the file size
/*****************************************************************************/
uint32_t UtilFile::size() const
{
    return iv_contents.size();
}

/*****************************************************************************/
// Set/Get the object's filename
/*****************************************************************************/
void UtilFile::FileName( const char * i_name )
{
    // Cleanup
    delete[] iv_filePathName;

    iv_filePathName = new char[strlen(i_name) + 1];

    strcpy(iv_filePathName, i_name);
}


text:
var angular = require('angular');

angular.module('tile', [require('./../appProvider/appProvider.module'), 'oc.lazyLoad', 'angularLoad'])
    .directive('tile', require('./tile.directive'));

module.exports = 'tile';


text:
require 'docker'

module Kontena::Launchers
  class Cadvisor
    include Celluloid
    include Celluloid::Notifications
    include Kontena::Logging

    CADVISOR_VERSION = ENV['CADVISOR_VERSION'] || '0.23.0'
    CADVISOR_IMAGE = ENV['CADVISOR_IMAGE'] || 'kontena/cadvisor'

    def initialize(autostart = true)
      info 'initialized'

      async.start if autostart
    end

    def start
      retries = 0
      begin
        start_cadvisor
      rescue Docker::Error::ServerError => exc
        if retries < 4
          retries += 1
          sleep 0.25
          retry
        end
        log_error(exc)
      rescue => exc
        log_error(exc)
      end
    end

    def start_cadvisor
      pull_image(image)
      create_container(image)
    end

    def image
      @image ||= "#{CADVISOR_IMAGE}:#{CADVISOR_VERSION}"
    end

    # @param [String] image
    def pull_image(image)
      return if Docker::Image.exist?(image)
      info "pulling image #{image}"
      Docker::Image.create('fromImage' => image)
      sleep 1 until Docker::Image.exist?(image)
    end

    # @param [String] image
    def create_container(image)
      container = Docker::Container.get('kontena-cadvisor') rescue nil
      if container && container.info['Config']['Image'] != image
        container.delete(force: true)
      elsif container && container.running?
        info "cadvisor is already running"
        return
      end

      info "starting cadvisor service"
      container = Docker::Container.create(
        'name' => 'kontena-cadvisor',
        'Image' => image,
        'Cmd' => [
          '--docker_only',
          '--listen_ip=127.0.0.1',
          '--port=8989',
          '--storage_duration=2m',
          '--housekeeping_interval=30s'
        ],
        'Volumes' => {
          '/host' => {},
        },
        'HostConfig' => {
          'Binds' => [
            '/:/host:rw'
          ],
          'PidMode' => 'host',
          'Privileged' => true,
          'RestartPolicy' => {'Name' => 'always'}
        }
      )
      container.start
    end

    # @param [Exception] exc
    def log_error(exc)
      error "#{exc.class.name}: #{exc.message}"
      error exc.backtrace.join("\n")
    end
  end
end


text:
package io.github.josehsantos.hack.lang.psi;

import com.intellij.psi.PsiElement;

/**
 * Created by josesantos on 15/11/14.
 */
public abstract class HackRecursiveVisitor extends HackVisitor {
    @Override
    public void visitElement(PsiElement element) {
        element.acceptChildren(this);
    }
}


text:
<?xml version='1.0' encoding='UTF-8' standalone='no'?>
<doxygen xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="compound.xsd" version="1.8.6">
  <compounddef id="classboost_1_1geometry_1_1strategy_1_1centroid_1_1average" kind="class" prot="public">
    <compoundname>boost::geometry::strategy::centroid::average</compoundname>
    <includes local="no">centroid_average.hpp</includes>
    <innerclass refid="classboost_1_1geometry_1_1strategy_1_1centroid_1_1average_1_1sum" prot="private">boost::geometry::strategy::centroid::average::sum</innerclass>
    <templateparamlist>
      <param>
        <type>typename PointCentroid</type>
      </param>
      <param>
        <type>typename Point</type>
        <defval>PointCentroid</defval>
      </param>
    </templateparamlist>
      <sectiondef kind="public-type">
      <memberdef kind="typedef" id="classboost_1_1geometry_1_1strategy_1_1centroid_1_1average_1a60b35abbf7882345dfc2edb2bb9e3026" prot="public" static="no">
        <type>PointCentroid</type>
        <definition>typedef PointCentroid boost::geometry::strategy::centroid::average< PointCentroid, Point >::centroid_point_type</definition>
        <argsstring></argsstring>
        <name>centroid_point_type</name>
        <briefdescription>
        </briefdescription>
        <detaileddescription>
        </detaileddescription>
        <inbodydescription>
        </inbodydescription>
        <location file="/home/ubuntu/boost/boost/geometry/strategies/cartesian/centroid_average.hpp" line="69" column="1" bodyfile="/home/ubuntu/boost/boost/geometry/strategies/cartesian/centroid_average.hpp" bodystart="69" bodyend="-1"/>
      </memberdef>
      <memberdef kind="typedef" id="classboost_1_1geometry_1_1strategy_1_1centroid_1_1average_1ac0f36137983c57820815b3abaf042ea9" prot="public" static="no">
        <type>Point</type>
        <definition>typedef Point boost::geometry::strategy::centroid::average< PointCentroid, Point >::point_type</definition>
        <argsstring></argsstring>
        <name>point_type</name>
        <briefdescription>
        </briefdescription>
        <detaileddescription>
        </detaileddescription>
        <inbodydescription>
        </inbodydescription>
        <location file="/home/ubuntu/boost/boost/geometry/strategies/cartesian/centroid_average.hpp" line="70" column="1" bodyfile="/home/ubuntu/boost/boost/geometry/strategies/cartesian/centroid_average.hpp" bodystart="70" bodyend="-1"/>
      </memberdef>
      <memberdef kind="typedef" id="classboost_1_1geometry_1_1strategy_1_1centroid_1_1average_1ac143d6508f627077f1adfd7de2c7a500" prot="public" static="no">
        <type>sum</type>
        <definition>typedef sum boost::geometry::strategy::centroid::average< PointCentroid, Point >::state_type</definition>
        <argsstring></argsstring>
        <name>state_type</name>
        <briefdescription>
        </briefdescription>
        <detaileddescription>
        </detaileddescription>
        <inbodydescription>
        </inbodydescription>
        <location file="/home/ubuntu/boost/boost/geometry/strategies/cartesian/centroid_average.hpp" line="68" column="1" bodyfile="/home/ubuntu/boost/boost/geometry/strategies/cartesian/centroid_average.hpp" bodystart="68" bodyend="-1"/>
      </memberdef>
      </sectiondef>
      <sectiondef kind="public-static-func">
      <memberdef kind="function" id="classboost_1_1geometry_1_1strategy_1_1centroid_1_1average_1ae9834e97a7b54299dddcde4d93d91656" prot="public" static="yes" const="no" explicit="no" inline="yes" virt="non-virtual">
        <type>void</type>
        <definition>static void boost::geometry::strategy::centroid::average< PointCentroid, Point >::apply</definition>
        <argsstring>(Point const &p, sum &state)</argsstring>
        <name>apply</name>
        <param>
          <type>Point const &</type>
          <declname>p</declname>
        </param>
        <param>
          <type>sum &</type>
          <declname>state</declname>
        </param>
        <briefdescription>
        </briefdescription>
        <detaileddescription>
        </detaileddescription>
        <inbodydescription>
        </inbodydescription>
        <location file="/home/ubuntu/boost/boost/geometry/strategies/cartesian/centroid_average.hpp" line="72" column="1" bodyfile="/home/ubuntu/boost/boost/geometry/strategies/cartesian/centroid_average.hpp" bodystart="72" bodyend="76"/>
      </memberdef>
      <memberdef kind="function" id="classboost_1_1geometry_1_1strategy_1_1centroid_1_1average_1a96417ccd4ad5999c00606e4d93f69ea1" prot="public" static="yes" const="no" explicit="no" inline="yes" virt="non-virtual">
        <type>bool</type>
        <definition>static bool boost::geometry::strategy::centroid::average< PointCentroid, Point >::result</definition>
        <argsstring>(sum const &state, PointCentroid &centroid)</argsstring>
        <name>result</name>
        <param>
          <type>sum const &</type>
          <declname>state</declname>
        </param>
        <param>
          <type>PointCentroid &</type>
          <declname>centroid</declname>
        </param>
        <briefdescription>
        </briefdescription>
        <detaileddescription>
        </detaileddescription>
        <inbodydescription>
        </inbodydescription>
        <location file="/home/ubuntu/boost/boost/geometry/strategies/cartesian/centroid_average.hpp" line="78" column="1" bodyfile="/home/ubuntu/boost/boost/geometry/strategies/cartesian/centroid_average.hpp" bodystart="78" bodyend="87"/>
      </memberdef>
      </sectiondef>
    <briefdescription>
<para>Centroid calculation taking average of points. </para>    </briefdescription>
    <detaileddescription>
    </detaileddescription>
    <location file="/home/ubuntu/boost/boost/geometry/strategies/cartesian/centroid_average.hpp" line="49" column="1" bodyfile="/home/ubuntu/boost/boost/geometry/strategies/cartesian/centroid_average.hpp" bodystart="48" bodyend="89"/>
    <listofallmembers>
      <member refid="classboost_1_1geometry_1_1strategy_1_1centroid_1_1average_1ae9834e97a7b54299dddcde4d93d91656" prot="public" virt="non-virtual"><scope>boost::geometry::strategy::centroid::average</scope><name>apply</name></member>
      <member refid="classboost_1_1geometry_1_1strategy_1_1centroid_1_1average_1a60b35abbf7882345dfc2edb2bb9e3026" prot="public" virt="non-virtual"><scope>boost::geometry::strategy::centroid::average</scope><name>centroid_point_type</name></member>
      <member refid="classboost_1_1geometry_1_1strategy_1_1centroid_1_1average_1ac0f36137983c57820815b3abaf042ea9" prot="public" virt="non-virtual"><scope>boost::geometry::strategy::centroid::average</scope><name>point_type</name></member>
      <member refid="classboost_1_1geometry_1_1strategy_1_1centroid_1_1average_1a96417ccd4ad5999c00606e4d93f69ea1" prot="public" virt="non-virtual"><scope>boost::geometry::strategy::centroid::average</scope><name>result</name></member>
      <member refid="classboost_1_1geometry_1_1strategy_1_1centroid_1_1average_1ac143d6508f627077f1adfd7de2c7a500" prot="public" virt="non-virtual"><scope>boost::geometry::strategy::centroid::average</scope><name>state_type</name></member>
    </listofallmembers>
  </compounddef>
</doxygen>


text:
var mainNav = document.querySelector('.main-nav'),
    navToggle = document.querySelector('.main-nav__toggle');

if(window.innerWidth >= 1200)
  mainNav.classList.remove('main-nav--closed');

window.addEventListener('resize', function() {
  if(window.innerWidth >= 1200)
    mainNav.classList.remove('main-nav--closed');
  else
    mainNav.classList.add('main-nav--closed');
});

navToggle.addEventListener('click', function() {
  if(mainNav.classList.contains('main-nav--closed')) {
    mainNav.classList.remove('main-nav--closed');
    mainNav.classList.add('main-nav--opened');
  } else {
    mainNav.classList.remove('main-nav--opened');
    mainNav.classList.add('main-nav--closed');
  }
});


text:
package systems.jarvis.fybr.providers;

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

public abstract class Model {

    public Model() {
        type = this.getClass().getSimpleName().toLowerCase();
        id = System.currentTimeMillis() + "";
        created = new Date();
    }

    public String type;

    public String id;

    public Date created;

}


text:
class CreditCardDraft
  def initialize(n)

    @creditCardNum = n
    credit_string = @creditCardNum.to_s
    credit_length = credit_string.length
    # p credit_length
    if credit_length > 16
      # p 'entered greater than'
      raise ArgumentError.new("Credit card number is too long")
    elsif credit_length < 16
      # p 'entered less than'
      raise ArgumentError.new("Credit card number is too short")
    end
  end

  def check_card
    num_string = @creditCardNum.to_s
    rev_string = num_string.reverse
    total_sum = 0
    p rev_string
    for x in 0..(rev_string.length-1)
      #turn double digit integer into string, separate string elements, turn those elements back into strings, and add them together with others
      if x%2 != 0
        p 'entered'
        doubled = rev_string[x].to_i * 2
        doubled_string = doubled.to_s
        for y in 0..(doubled_string.length - 1)

          total_sum = total_sum + doubled_string[y].to_i
          p doubled_string[y]

        end

      else
        p 'not entered'
        total_sum = total_sum + rev_string[x].to_i
        p rev_string[x]

      end
    end
    p total_sum
    if total_sum % 10 == 0
      p 'true'
      return true

    else
      p 'false'
      return false
    end
  end
end

# Don't forget to check on initialization for a card length
# of exactly 16 digits

# Refactored Solution

class CreditCard
  def initialize(n)
    @creditCardNum = n
    credit_string = @creditCardNum.to_s
    credit_length = credit_string.length
    if credit_length > 16
      raise ArgumentError.new("Credit card number is too long")
    elsif credit_length < 16
      raise ArgumentError.new("Credit card number is too short")
    end
  end

  def check_card
    num_string = @creditCardNum.to_s
    rev_string = num_string.reverse
    total_sum = 0
    for x in 0..(rev_string.length-1)
      if x%2 != 0
        doubled = rev_string[x].to_i * 2
        doubled_string = doubled.to_s
        for y in 0..(doubled_string.length - 1)
          total_sum = total_sum + doubled_string[y].to_i
        end
      else
        total_sum = total_sum + rev_string[x].to_i
      end
    end
    if total_sum % 10 == 0
      return true
    else
      return false
    end
  end
end

# Reflection

# What was the most difficult part of this challenge for you and your pair?

  #This was pretty straighforward. We got stuck becuase we didn't read the instructions correctly. I thought that we were doubling the first number from the end not the 2nd number. That cost us ~10 minutes or so.

# What new methods did you find to help you when you refactored?

  # None. We didn't separate this assignment into three methods like they asked. We initialized and checked, and that was it.

# What concepts or learnings were you able to solidify in this challenge?

  # As far as the material, it was pretty straighforward.


text:
class AlphabetController < UIViewController

  def init
    super
    self.tabBarItem = UITabBarItem.alloc.init
    self.tabBarItem.title = "Alphabet"
    self.tabBarItem.setFinishedSelectedImage(UIImage.imageNamed("icon-4.png"), withFinishedUnselectedImage:UIImage.imageNamed("icon-4.png"))
    self
  end

  def viewDidLoad
    super
    self.title = "Alphabet"

    @table = UITableView.alloc.initWithFrame(self.view.bounds)
    self.view.addSubview @table

    @table.dataSource = self
    @table.delegate = self

    @table.dataSource = self
    @data = ("A".."Z").to_a
  end

  def tableView(tableView, cellForRowAtIndexPath: indexPath)
    @reuseIdentifier ||= "CELL_IDENTIFIER"

    cell = tableView.dequeueReusableCellWithIdentifier(@reuseIdentifier) || begin
      UITableViewCell.alloc.initWithStyle(UITableViewCellStyleDefault, reuseIdentifier:@reuseIdentifier)
    end

    cell.textLabel.text = @data[indexPath.row]

    cell
  end

  def tableView(tableView, numberOfRowsInSection: section)
    @data.count
  end

  def tableView(tableView, didSelectRowAtIndexPath:indexPath)
    tableView.deselectRowAtIndexPath(indexPath, animated: true)
    App.alert("#{@data[indexPath.row]} tapped!", {cancel_button_title: "pshh...", message: "But why did you click that???"})
  end

end


text:
namespace boost {
namespace interprocess {
namespace ipcdetail {

// Greatest common divisor and least common multiple

//
// gcd is an algorithm that calculates the greatest common divisor of two
//  integers, using Euclid's algorithm.
//
// Pre: A > 0 && B > 0
// Recommended: A > B
template <typename Integer>
inline Integer gcd(Integer A, Integer B)
{
   do
   {
      const Integer tmp(B);
      B = A % B;
      A = tmp;
   } while (B != 0);

   return A;
}

//
// lcm is an algorithm that calculates the least common multiple of two
//  integers.
//
// Pre: A > 0 && B > 0
// Recommended: A > B
template <typename Integer>
inline Integer lcm(const Integer & A, const Integer & B)
{
   Integer ret = A;
   ret /= gcd(A, B);
   ret *= B;
   return ret;
}

template <typename Integer>
inline Integer log2_ceil(const Integer & A)
{
   Integer i = 0;
   Integer power_of_2 = 1;

   while(power_of_2 < A){
      power_of_2 <<= 1;
      ++i;
   }
   return i;
}

template <typename Integer>
inline Integer upper_power_of_2(const Integer & A)
{
   Integer power_of_2 = 1;

   while(power_of_2 < A){
      power_of_2 <<= 1;
   }
   return power_of_2;
}

//This function uses binary search to discover the
//highest set bit of the integer
inline std::size_t floor_log2 (std::size_t x)
{
   const std::size_t Bits = sizeof(std::size_t)*CHAR_BIT;
   const bool Size_t_Bits_Power_2= !(Bits & (Bits-1));
   BOOST_STATIC_ASSERT(((Size_t_Bits_Power_2)== true));

   std::size_t n = x;
   std::size_t log2 = 0;

   for(std::size_t shift = Bits >> 1; shift; shift >>= 1){
      std::size_t tmp = n >> shift;
      if (tmp)
         log2 += shift, n = tmp;
   }

   return log2;
}

} // namespace ipcdetail
} // namespace interprocess
} // namespace boost

#endif


text:
using System;

namespace Camunda.Api.Client.History
{
    public class HistoricIncident
    {
        /// <summary>
        /// The id of the incident.
        /// </summary>
        public string Id;
        /// <summary>
        /// The key of the process definition this incident is associated with.
        /// </summary>
        public string ProcessDefinitionKey;
        /// <summary>
        /// The id of the process definition this incident is associated with.
        /// </summary>
        public string ProcessDefinitionId;
        /// <summary>
        /// The id of the process instance this incident is associated with.
        /// </summary>
        public string ProcessInstanceId;
        /// <summary>
        /// The id of the execution this incident is associated with.
        /// </summary>
        public string ExecutionId;
        /// <summary>
        /// The time this incident happened.
        /// </summary>
        public DateTime CreateTime;
        /// <summary>
        /// The time this incident has been deleted or resolved.
        /// </summary>
        public DateTime? EndTime;
        /// <summary>
        /// The type of incident, for example: failedJobs will be returned in case of an incident which identified a failed job during
        /// </summary>
        public string IncidentType;
        /// <summary>
        /// The id of the activity this incident is associated with.
        /// </summary>
        public string ActivityId;
        /// <summary>
        /// The id of the associated cause incident which has been triggered.
        /// </summary>
        public string CauseIncidentId;
        /// <summary>
        /// The id of the associated root cause incident which has been triggered.
        /// </summary>
        public string RootCauseIncidentId;
        /// <summary>
        /// The payload of this incident.
        /// </summary>
        public string Configuration;
        /// <summary>
        /// The message of this incident.
        /// </summary>
        public string IncidentMessage;
        /// <summary>
        /// The id of the tenant this incident is associated with.
        /// </summary>
        public string TenantId;
        /// <summary>
        /// The job definition id the incident is associated with.
        /// </summary>
        public string JobDefinitionId;
        /// <summary>
        /// If true, this incident is open.
        /// </summary>
        public bool Open;
        /// <summary>
        /// If true, this incident has been deleted.
        /// </summary>
        public bool Deleted;
        /// <summary>
        /// If true, this incident has been resolved.
        /// </summary>
        public bool Resolved;

        public override string ToString() => Id;
    }
}


text: Extend Laravel 5 models in order to allow them to be taggable


text:
package com.ibuildapp.romanblack.CataloguePlugin.holders;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;

import com.ibuildapp.romanblack.CataloguePlugin.R;

public class RoundHolder extends RecyclerView.ViewHolder {
    public ImageView roundIcon;
    public RoundHolder(View itemView) {
        super(itemView);

        roundIcon = (ImageView) itemView.findViewById(R.id.details_round_image);
    }
}


text:
<?php
function generate_signature_panel_image($jsonData, $sizeX = 0, $sizeY = 0) {
    if ($sizeX < 0) {
        throw new InvalidArgumentException("$sizeX must be >= 0");
    }
    if ($sizeY < 0) {
        throw new InvalidArgumentException("$sizeY must be >= 0");
    }

    $data = json_decode($jsonData);

    if ($data->dataVersion != 1) {
        throw new Exception("Unsupported data version");
    }
    if ($data->canvasWidth <= 0) {
        throw new Exception("Invalid canvasWidth");
    }
    if ($data->canvasHeight <= 0) {
        throw new Exception("Invalid canvasHeight");
    }
    if ($sizeX == 0 || $sizeY == 0) {
        $sizeX = $data->canvasWidth;
        $sizeY = $data->canvasHeight;
    }

    $scalingFactor = min($sizeX / $data->canvasWidth, $sizeY / $data->canvasHeight);
    $penColor = $data->penColor;
    $penWidth = max($data->penWidth * $scalingFactor, 1);

    $polylines = array();
    $iPolyline = -1;
    $x = 0;
    $y = 0;

    foreach ($data->clickstream as $event) {
        $x = $event->x * $scalingFactor;
        $y = $event->y * $scalingFactor;
        switch ($event->action) {
            case "gestureStart":
            case "gestureResume":
                $iPolyline += 1;
                $polylines[$iPolyline] = array($x, $y);
                break;
            case "gestureContinue":
            case "gestureSuspend":
                if ($iPolyline >= 0) {
                    $polylines[$iPolyline][] = $x;
                    $polylines[$iPolyline][] = $y;
                }
                break;
        }
    }

    return draw_upsampled_polyline($sizeX, $sizeY, $penColor, $penWidth, $polylines);
}

function draw_upsampled_polyline($sizeX, $sizeY, $penColor, $penWidth, $polylines, $upsampleFactor=4) {
    /* GD lacks three things that we need to make the generated image match what the user saw
        * antialiased lines
        * round endcaps on lines
        * round mitred joins between lines

    We emulate antialising by drawing at a larger size (given by the upsample factor) and scaling down
    We emulate the endcaps and mitres by drawing circles at each vertex point.

    As an alternative, you could use a different library (e.g., ImageMagick) that handles these features natively.
    The emulation approach is attractive because GD is nearly ubiquitous whereas alternative graphic libraries
    are less common. */

    $image = imagecreatetruecolor($sizeX * $upsampleFactor, $sizeY * $upsampleFactor);
    imagealphablending($image, false);
    $transparentColor = imagecolorallocatealpha($image, 255, 255, 255, 0);
    imagefilledrectangle($image, 0, 0, $sizeX * $upsampleFactor, $sizeY * $upsampleFactor, $transparentColor);
    imagecolordeallocate($image, $transparentColor);
    imagealphablending($image, true);
    $penColorArray = rgbfromhtmlcolor($penColor);
    $imagePenColor = imagecolorallocate($image, $penColorArray[0], $penColorArray[1], $penColorArray[2]);

    if (count($polylines) > 0) {
        $p = $upsampleFactor * $penWidth / 2;
        $x1 = $upsampleFactor * $polylines[0][0];
        $y1 = $upsampleFactor * $polylines[0][1];
        imagefilledellipse($image, $x1, $y1, $p * 2, $p * 2, $imagePenColor);
        foreach ($polylines as $polyline) {
            for ($i = 0; $i < count($polyline) - 4; $i += 2) {
                $x1 = $upsampleFactor * $polyline[$i];
                $y1 = $upsampleFactor * $polyline[$i + 1];
                $x2 = $upsampleFactor * $polyline[$i + 2];
                $y2 = $upsampleFactor * $polyline[$i + 3];
                $dx = $x2 - $x1;
                $dy = $y2 - $y1;
                $d = hypot($dx, $dy);
                if ($d > 0) {
                    $s = $p / $d;
                    $newPoly = Array($x1 - $s * $dy, $y1 + $s * $dx,
                                     $x2 - $s * $dy, $y2 + $s * $dx,
                                     $x2 + $s * $dy, $y2 - $s * $dx,
                                     $x1 + $s * $dy, $y1 - $s * $dx);
                    imagefilledpolygon($image, $newPoly, 4, $imagePenColor);
                    imagefilledellipse($image, $x2, $y2, $p * 2, $p * 2, $imagePenColor);
                }
            }
        }
    }

    $resizedImage = imagecreatetruecolor($sizeX, $sizeY);
    imagealphablending($resizedImage, true);

    imagecopyresampled($resizedImage, $image, 0, 0, 0, 0, $sizeX, $sizeY, $sizeX * $upsampleFactor, $sizeY * $upsampleFactor);
    imagedestroy($image);

    return $resizedImage;
}

function rgbfromhtmlcolor($color) {
    if ($color[0] === '#') {
        $color = substr($color, 1);
    }

    if (strlen($color) === 6) {
        $rgb = array(hexdec($color[0].$color[1]), hexdec($color[2].$color[3]), hexdec($color[4].$color[5]));
    } elseif (strlen($color) === 3) {
        $rgb = array(hexdec($color[0].$color[0]), hexdec($color[1].$color[1]), hexdec($color[2].$color[2]));
    } else {
        $rgb = array(0, 0, 0);
    }

    return $rgb;
}

?>


text:
package com.jockeyjs.util;
import android.net.http.SslError;
import android.webkit.ValueCallback;
import android.webkit.WebResourceResponse;
import org.xwalk.core.XWalkResourceClient;
import org.xwalk.core.XWalkView;

public abstract class ForwardingWebViewClient extends XWalkResourceClient {

  public ForwardingWebViewClient (XWalkView view) {

    super(view);
  }

  protected abstract XWalkResourceClient delegate ();

  protected boolean hasDelegate () {

    return delegate() != null;
  }

  @Override public void onLoadFinished (XWalkView view, String url) {

    if (hasDelegate()) {
      delegate().onLoadFinished(view, url);
    } else {
      super.onLoadFinished(view, url);
    }
  }

  @Override public void onLoadStarted (XWalkView view, String url) {

    if (hasDelegate()) {
      delegate().onLoadStarted(view, url);
    } else {
      super.onLoadFinished(view, url);
    }
  }

  @Override public WebResourceResponse shouldInterceptLoadRequest (XWalkView view, String url) {

    if (hasDelegate()) {
      return delegate().shouldInterceptLoadRequest(view, url);
    } else {
      return super.shouldInterceptLoadRequest(view, url);
    }
  }

  @Override public void onReceivedSslError (XWalkView view, ValueCallback<Boolean> callback, SslError error) {

    super.onReceivedSslError(view, callback, error);
  }

  @Override public void onReceivedLoadError (XWalkView view, int errorCode, String description, String failingUrl) {

    super.onReceivedLoadError(view, errorCode, description, failingUrl);
  }

 }


text:
/**
 * Authentication, Authorization & Sessions.
 *
 * @class FB
 * @static
 * @access private
 */
FB.provide('', {
  /**
   * Find out the current status from the server, and get a session if the user
   * is connected.
   *
   * The user's status or the question of *who is the current user* is
   * the first thing you will typically start with. For the answer, we
   * ask facebook.com. Facebook will answer this question in one of
   * two ways:
   *
   * 1. Someone you don't know.
   * 2. Someone you know and have interacted with. Here's a session for them.
   *
   * Here's how you find out:
   *
   *     FB.getLoginStatus(function(response) {
   *       if (response.session) {
   *         // logged in and connected user, someone you know
   *       } else {
   *         // no user session available, someone you dont know
   *       }
   *     });
   *
   * The example above will result in the callback being invoked **once**
   * on load based on the session from www.facebook.com. JavaScript applications
   * are typically written with heavy use of events, and the SDK **encourages**
   * this by exposing various events. These are fired by the various
   * interactions with authentication flows, such as [FB.login()][login] or
   * [[wiki:fb:login-button]]. Widgets such as [[wiki:fb:comments (XFBML)]]
   * may also trigger authentication.
   *
   * **Events**
   *
   * #### auth.login
   * This event is fired when your application first notices the user (in other
   * words, gets a session when it didn't already have a valid one).
   * #### auth.logout
   * This event is fired when your application notices that there is no longer
   * a valid user (in other words, it had a session but can no longer validate
   * the current user).
   * #### auth.sessionChange
   * This event is fired for **any** auth related change as they all affect the
   * session: login, logout, session refresh. Sessions are refreshed over time
   * as long as the user is active with your application.
   * #### auth.statusChange
   * Typically you will want to use the auth.sessionChange event. But in rare
   * cases, you want to distinguish between these three states:
   *
   * - Connected
   * - Logged into Facebook but not connected with your application
   * - Not logged into Facebook at all.
   *
   * The [FB.Event.subscribe][subscribe] and
   * [FB.Event.unsubscribe][unsubscribe] functions are used to subscribe to
   * these events. For example:
   *
   *     FB.Event.subscribe('auth.login', function(response) {
   *       // do something with response
   *     });
   *
   * The response object returned to all these events is the same as the
   * response from [FB.getLoginStatus][getLoginStatus], [FB.login][login] or
   * [FB.logout][logout]. This response object contains:
   *
   * status
   * : The status of the User. One of `connected`, `notConnected` or `unknown`.
   *
   * session
   * : The session object.
   *
   * perms
   * : The comma separated permissions string. This is specific to a
   *   permissions call. It is not persistent.
   *
   * [subscribe]: /docs/reference/javascript/FB.Event.subscribe
   * [unsubscribe]: /docs/reference/javascript/FB.Event.unsubscribe
   * [getLoginStatus]: /docs/reference/javascript/FB.getLoginStatus
   * [login]: /docs/reference/javascript/FB.login
   * [logout]: /docs/reference/javascript/FB.logout
   *
   * @access public
   * @param cb {Function} The callback function.
   * @param force {Boolean} Force reloading the login status (default `false`).
   */
  getLoginStatus: function(cb, force) {
    if (!FB._apiKey) {
      FB.log('FB.getLoginStatus() called before calling FB.init().');
      return;
    }

    // we either invoke the callback right away if the status has already been
    // loaded, or queue it up for when the load is done.
    if (cb) {
      if (!force && FB.Auth._loadState == 'loaded') {
        cb({ status: FB._userStatus, session: FB._session });
        return;
      } else {
        FB.Event.subscribe('FB.loginStatus', cb);
      }
    }

    // if we're already loading, and this is not a force load, we're done
    if (!force && FB.Auth._loadState == 'loading') {
      return;
    }

    FB.Auth._loadState = 'loading';

    // invoke the queued sessionLoad callbacks
    var lsCb = function(response) {
      // done
      FB.Auth._loadState = 'loaded';

      // invoke callbacks
      FB.Event.fire('FB.loginStatus', response);
      FB.Event.clear('FB.loginStatus');
    };

    // finally make the call to login status
    FB.ui({ method: 'auth.status', display: 'hidden' }, lsCb);
  },

  /**
   * *Synchronous* accessor for the current Session. The **synchronous**
   * nature of this method is what sets it apart from the other login methods.
   * It is similar in nature to [FB.getLoginStatus()][FB.getLoginStatus], but
   * it just **returns** the session. Many parts of your application already
   * *assume* the user is connected with your application. In such cases, you
   * may want to avoid the overhead of making asynchronous calls.
   *
   * NOTE: You should never use this method at *page load* time. Generally, it
   * is safer to use [FB.getLoginStatus()][FB.getLoginStatus] if you are
   * unsure.
   *
   * [FB.getLoginStatus]: /docs/reference/javascript/FB.getLoginStatus
   *
   * @access public
   * @return {Object} the current Session if available, `null` otherwise
   */
  getSession: function() {
    return FB._session;
  },

  /**
   * Login/Authorize/Permissions.
   *
   * Once you have determined the user's status, you may need to
   * prompt the user to login. It is best to delay this action to
   * reduce user friction when they first arrive at your site. You can
   * then prompt and show them the "Connect with Facebook" button
   * bound to an event handler which does the following:
   *
   *     FB.login(function(response) {
   *       if (response.session) {
   *         // user successfully logged in
   *       } else {
   *         // user cancelled login
   *       }
   *     });
   *
   * You should **only** call this on a user event as it opens a
   * popup. Most browsers block popups, _unless_ they were initiated
   * from a user event, such as a click on a button or a link.
   *
   *
   * Depending on your application's needs, you may need additional
   * permissions from the user. A large number of calls do not require
   * any additional permissions, so you should first make sure you
   * need a permission. This is a good idea because this step
   * potentially adds friction to the user's process. Another point to
   * remember is that this call can be made even _after_ the user has
   * first connected. So you may want to delay asking for permissions
   * until as late as possible:
   *
   *     FB.login(function(response) {
   *       if (response.session) {
   *         if (response.perms) {
   *           // user is logged in and granted some permissions.
   *           // perms is a comma separated list of granted permissions
   *         } else {
   *           // user is logged in, but did not grant any permissions
   *         }
   *       } else {
   *         // user is not logged in
   *       }
   *     }, {perms:'read_stream,publish_stream,offline_access'});
   *
   * @access public
   * @param cb {Function} The callback function.
   * @param opts {Object} (_optional_) Options to modify login behavior.
   *
   * Name                     | Type    | Description
   * ------------------------ | ------- | --------------------------------------------------------------------------------
   * perms                    | String  | Comma separated list of [Extended permissions](/docs/authentication/permissions)
   * enable_profile_selector  | Boolean | When true, prompt the user to grant permission for one or more Pages.
   * profile_selector_ids     | String  | Comma separated list of IDs to display in the profile selector.
   */
  login: function(cb, opts) {
    opts = FB.copy({ method: 'auth.login', display: 'popup' }, opts || {});
    FB.ui(opts, cb);
  },

  /**
   * Logout the user in the background.
   *
   * Just like logging in is tied to facebook.com, so is logging out -- and
   * this call logs the user out of both Facebook and your site. This is a
   * simple call:
   *
   *     FB.logout(function(response) {
   *       // user is now logged out
   *     });
   *
   * NOTE: You can only log out a user that is connected to your site.
   *
   * @access public
   * @param cb {Function} The callback function.
   */
  logout: function(cb) {
    FB.ui({ method: 'auth.logout', display: 'hidden' }, cb);
  }
});

/**
 * Internal Authentication implementation.
 *
 * @class FB.Auth
 * @static
 * @access private
 */
FB.provide('Auth', {
  // pending callbacks for FB.getLoginStatus() calls
  _callbacks: [],

  /**
   * Set a new session value. Invokes all the registered subscribers
   * if needed.
   *
   * @access private
   * @param session {Object}  the new Session
   * @param status  {String}  the new status
   * @return       {Object}  the "response" object
   */
  setSession: function(session, status) {
    // detect special changes before changing the internal session
    var
      login         = !FB._session && session,
      logout        = FB._session && !session,
      both          = FB._session && session && FB._session.uid != session.uid,
      sessionChange = login || logout || (FB._session && session &&
                         FB._session.session_key != session.session_key),
      statusChange  = status != FB._userStatus;

    var response = {
      session : session,
      status  : status
    };

    FB._session = session;
    FB._userStatus = status;

    // If cookie support is enabled, set the cookie. Cookie support does not
    // rely on events, because we want the cookie to be set _before_ any of the
    // event handlers are fired. Note, this is a _weak_ dependency on Cookie.
    if (sessionChange && FB.Cookie && FB.Cookie.getEnabled()) {
      FB.Cookie.set(session);
    }

    // events
    if (statusChange) {
      /**
       * Fired when the status changes.
       *
       * @event auth.statusChange
       */
      FB.Event.fire('auth.statusChange', response);
    }
    if (logout || both) {
      /**
       * Fired when a logout action is performed.
       *
       * @event auth.logout
       */
      FB.Event.fire('auth.logout', response);
    }
    if (login || both) {
      /**
       * Fired when a login action is performed.
       *
       * @event auth.login
       */
      FB.Event.fire('auth.login', response);
    }
    if (sessionChange) {
      /**
       * Fired when the session changes. This includes a session being
       * refreshed, or a login or logout action.
       *
       * @event auth.sessionChange
       */
      FB.Event.fire('auth.sessionChange', response);
    }

    // re-setup a timer to refresh the session if needed. we only do this if
    // FB.Auth._loadState exists, indicating that the application relies on the
    // JS to get and refresh session information (vs managing it themselves).
    if (FB.Auth._refreshTimer) {
      window.clearTimeout(FB.Auth._refreshTimer);
      delete FB.Auth._refreshTimer;
    }
    if (FB.Auth._loadState && session && session.expires) {
      // refresh every 20 minutes. we don't rely on the expires time because
      // then we would also need to rely on the local time available in JS
      // which is often incorrect.
      FB.Auth._refreshTimer = window.setTimeout(function() {
        FB.getLoginStatus(null, true); // force refresh
      }, 1200000); // 20 minutes
    }

    return response;
  },

  /**
   * This handles receiving a session from:
   *  - login_status.php
   *  - login.php
   *  - tos.php
   *
   * It also (optionally) handles the ``xxRESULTTOKENxx`` response from:
   *  - prompt_permissions.php
   *
   * And calls the given callback with::
   *
   *   {
   *     session: session or null,
   *     status: 'unknown' or 'notConnected' or 'connected',
   *     perms: comma separated string of perm names
   *   }
   *
   * @access private
   * @param cb        {Function} the callback function
   * @param frame     {String}   the frame id for the callback is tied to
   * @param target    {String}   parent or opener to indicate window relation
   * @param isDefault {Boolean}  is this the default callback for the frame
   * @param status    {String}   the connect status this handler will trigger
   * @param session   {Object}   backup session, if none is found in response
   * @return         {String}   the xd url bound to the callback
   */
  xdHandler: function(cb, frame, target, isDefault, status, session) {
    return FB.UIServer._xdNextHandler(function(params) {
      try {
        session = FB.JSON.parse(params.session);
      } catch (x) {
        // ignore parse errors
      }
      var response = FB.Auth.setSession(session || null, status);

      // incase we were granted some new permissions
      response.perms = (
        params.result != 'xxRESULTTOKENxx' && params.result || '');

      // user defined callback
      cb && cb(response);
    }, frame, target, isDefault) + '&result=xxRESULTTOKENxx';
  }
});

FB.provide('UIServer.Methods', {
  'auth.login': {
    size      : { width: 627, height: 326 },
    url       : 'login.php',
    transform : function(call) {
      //FIXME
      if (!FB._apiKey) {
        FB.log('FB.login() called before calling FB.init().');
        return;
      }

      // if we already have a session and permissions are not being requested,
      // we just fire the callback
      if (FB._session && !call.params.perms) {
        FB.log('FB.login() called when user is already connected.');
        call.cb && call.cb({ status: FB._userStatus, session: FB._session });
        return;
      }

      var
        xdHandler = FB.Auth.xdHandler,
        cb        = call.cb,
        id        = call.id,
        session   = FB._session,
        cancel    = xdHandler(
          cb,
          id,
          'opener',
          true, // isDefault
          FB._userStatus,
          session),
        next      = xdHandler(
          cb,
          id,
          'opener',
          false, // isDefault
          'connected',
          session);

      FB.copy(call.params, {
        cancel_url              : cancel,
        channel_url             : window.location.toString(),
        next                    : next,
        fbconnect               : FB._inCanvas ? 0 : 1,
        req_perms               : call.params.perms,
        enable_profile_selector : call.params.enable_profile_selector,
        profile_selector_ids    : call.params.profile_selector_ids,
        return_session          : 1,
        session_version         : 3,
        v                       : '1.0'
      });
      delete call.cb;
      delete call.params.perms; //TODO fix name to be the same on server

      return call;
    }
  },

  'auth.logout': {
    url       : 'logout.php',
    transform : function(call) {
      //FIXME make generic
      if (!FB._apiKey) {
        FB.log('FB.logout() called before calling FB.init().');
      } else if (!FB._session) {
        FB.log('FB.logout() called without a session.');
      } else {
        call.params.next = FB.Auth.xdHandler(
          call.cb, call.id, 'parent', false, 'unknown');
        return call;
      }
    }
  },

  'auth.status': {
    url       : 'extern/login_status.php',
    transform : function(call) {
      var
        cb = call.cb,
        id = call.id,
        xdHandler = FB.Auth.xdHandler;
      delete call.cb;
      FB.copy(call.params, {
        no_session : xdHandler(cb, id, 'parent', false, 'notConnected'),
        no_user    : xdHandler(cb, id, 'parent', false, 'unknown'),
        ok_session : xdHandler(cb, id, 'parent', false, 'connected'),
        session_version : 3,
        extern: FB._inCanvas ? 0 : 2
      });
      return call;
    }
  }
});


text:
"""
@name:      Modules/House/Family/insteon/insteon_button.py
@author:    D. Brian Kimmel
@contact:   D.BrianKimmel@gmail.com
@copyright: (c) 2019-2020 by D. Brian Kimmel
@note:      Created on Aug 18, 2019
@license:   MIT License
@summary:

We get these .

"""

__updated__ = '2020-02-18'

#  Import system type stuff

#  Import PyMh files

from Modules.Core import logging_pyh as Logger
LOG = Logger.getLogger('PyHouse.Insteon_Button ')

class LocalConfig:
    """
    """

class Discovery:
    """
    """

class ButtonActions:
    """
    """

    def initial_button_load(self):
        """
        """
        if p_obj.Family.Name.lower() == 'insteon':
            self._get_engine_version(p_controller_obj, p_obj)
            self._get_id_request(p_controller_obj, p_obj)
            self._get_one_device_status(p_controller_obj, p_obj)
        else:
            LOG.warning('Skipping "{}" "{}" device "{}"'.format(p_obj.DeviceType, p_obj.DeviceSubType, p_obj.Name))
            pass

# ## END DBK


text:
using namespace lightstep;
using namespace opentracing;

TEST_CASE("auto_recorder") {
  Logger logger{};
  auto metrics_observer = new CountingMetricsObserver{};
  LightStepTracerOptions options;
  const auto reporting_period = std::chrono::milliseconds{2};
  std::atomic<size_t> max_buffered_spans{5};
  options.reporting_period = reporting_period;
  options.max_buffered_spans =
      std::function<size_t()>{[&] { return size_t{max_buffered_spans}; }};
  options.metrics_observer.reset(metrics_observer);
  auto in_memory_transporter = new InMemorySyncTransporter{};
  auto condition_variable = new TestingConditionVariableWrapper{};
  auto recorder = new AutoRecorder{
      logger, std::move(options),
      std::unique_ptr<SyncTransporter>{in_memory_transporter},
      std::unique_ptr<ConditionVariableWrapper>{condition_variable}};
  auto tracer = std::shared_ptr<opentracing::Tracer>{new LegacyTracerImpl{
      PropagationOptions{}, std::unique_ptr<Recorder>{recorder}}};
  CHECK(tracer);

  // Ensure that the writer thread is waiting.
  REQUIRE_NOTHROW(condition_variable->WaitTillNextEvent());

  SECTION(
      "The writer thread waits until `now() + reporting_period` to "
      "send a report") {
    auto now = condition_variable->Now();
    REQUIRE_NOTHROW(condition_variable->WaitTillNextEvent());
    auto event = condition_variable->next_event();
    CHECK(dynamic_cast<const TestingConditionVariableWrapper::WaitEvent*>(
              event) != nullptr);
    CHECK(event->timeout() == now + reporting_period);
  }

  SECTION(
      "If the writer thread takes longer than `reporting_period` to run, then "
      "it runs again immediately upon finishing.") {
    auto now = condition_variable->Now() + 2 * reporting_period;
    REQUIRE_NOTHROW(condition_variable->WaitTillNextEvent());
    auto span = tracer->StartSpan("abc");
    span->Finish();
    condition_variable->set_now(now);
    REQUIRE_NOTHROW(condition_variable->Step());
    REQUIRE_NOTHROW(condition_variable->WaitTillNextEvent());
    auto event = condition_variable->next_event();
    CHECK(dynamic_cast<const TestingConditionVariableWrapper::WaitEvent*>(
              event) != nullptr);
    CHECK(condition_variable->Now() == now);
    CHECK(event->timeout() == now);
  }

  SECTION(
      "If the writer thread takes time between 0 and `reporting_period` to "
      "run, then it subtracts the elapse time from the next timeout") {
    auto now = condition_variable->Now() + 3 * reporting_period / 2;
    REQUIRE_NOTHROW(condition_variable->WaitTillNextEvent());
    auto span = tracer->StartSpan("abc");
    span->Finish();
    condition_variable->set_now(now);
    REQUIRE_NOTHROW(condition_variable->Step());
    REQUIRE_NOTHROW(condition_variable->WaitTillNextEvent());
    auto event = condition_variable->next_event();
    CHECK(dynamic_cast<const TestingConditionVariableWrapper::WaitEvent*>(
              event) != nullptr);
    CHECK(condition_variable->Now() == now);
    CHECK(event->timeout() == now + reporting_period / 2);
  }

  SECTION(
      "If the transporter's SendReport function throws, we drop all subsequent "
      "spans.") {
    logger.set_level(LogLevel::off);
    in_memory_transporter->set_should_throw(true);
    condition_variable->set_block_notify_all(true);

    auto span = tracer->StartSpan("abc");
    span->Finish();
    REQUIRE_NOTHROW(condition_variable->Step());
    REQUIRE_NOTHROW(condition_variable->WaitTillNextEvent());
    condition_variable->set_block_notify_all(false);
    REQUIRE_NOTHROW(condition_variable->Step());
    CHECK(!recorder->is_writer_running());
  }

  SECTION(
      "Dropped spans counts get sent in the next ReportRequest, and cleared in "
      "the following ReportRequest.") {
    condition_variable->set_block_notify_all(true);
    for (size_t i = 0; i < max_buffered_spans + 1; ++i) {
      auto span = tracer->StartSpan("abc");
      CHECK(span);
      span->Finish();
    }
    // Check that a NotifyAllEvent gets added when the buffer overflows.
    CHECK(dynamic_cast<const TestingConditionVariableWrapper::NotifyAllEvent*>(
              condition_variable->next_event()) != nullptr);

    // Wait until the first report gets sent.
    REQUIRE_NOTHROW(condition_variable->Step());
    REQUIRE_NOTHROW(condition_variable->Step());
    condition_variable->set_block_notify_all(false);

    auto span = tracer->StartSpan("xyz");
    CHECK(span);
    span->Finish();
    // Ensure that the second report gets sent.
    REQUIRE_NOTHROW(condition_variable->Step());
    REQUIRE_NOTHROW(condition_variable->Step());
    REQUIRE_NOTHROW(condition_variable->WaitTillNextEvent());

    auto reports = in_memory_transporter->reports();
    CHECK(reports.size() == 2);
    CHECK(LookupSpansDropped(reports.at(0)) == 1);
    CHECK(reports.at(0).spans_size() == max_buffered_spans);
    CHECK(LookupSpansDropped(reports.at(1)) == 0);
    CHECK(reports.at(1).spans_size() == 1);
  }

  SECTION(
      "MetricsObserver::OnFlush gets called whenever the recorder is "
      "successfully flushed.") {
    auto span = tracer->StartSpan("abc");
    span->Finish();
    REQUIRE_NOTHROW(condition_variable->Step());
    REQUIRE_NOTHROW(condition_variable->WaitTillNextEvent());
    CHECK(metrics_observer->num_flushes == 1);
  }

  SECTION(
      "MetricsObserver::OnSpansSent gets called with the number of spans "
      "transported") {
    auto span1 = tracer->StartSpan("abc");
    span1->Finish();
    auto span2 = tracer->StartSpan("abc");
    span2->Finish();
    REQUIRE_NOTHROW(condition_variable->Step());
    REQUIRE_NOTHROW(condition_variable->WaitTillNextEvent());
    CHECK(metrics_observer->num_spans_sent == 2);
  }

  SECTION(
      "MetricsObserver::OnSpansDropped gets called when spans are dropped.") {
    condition_variable->set_block_notify_all(true);
    for (size_t i = 0; i < max_buffered_spans + 1; ++i) {
      auto span = tracer->StartSpan("abc");
      CHECK(span);
      span->Finish();
    }
    condition_variable->set_block_notify_all(false);
    REQUIRE_NOTHROW(condition_variable->Step());
    REQUIRE_NOTHROW(condition_variable->WaitTillNextEvent());
    CHECK(metrics_observer->num_spans_sent == max_buffered_spans);
    CHECK(metrics_observer->num_spans_dropped == 1);
  }

  SECTION(
      "If `max_buffered_spans` is changed dynamically, it will take effect "
      "after the next Flush") {
    condition_variable->set_block_notify_all(true);
    size_t max_buffered_spans_old = max_buffered_spans;
    size_t max_buffered_spans_new = max_buffered_spans_old - 1;
    max_buffered_spans = max_buffered_spans_new;
    for (size_t i = 0; i < max_buffered_spans_new; ++i) {
      auto span = tracer->StartSpan("abc");
      CHECK(span);
      span->Finish();
    }

    // Check that no NotifyAllEvent was added.
    CHECK(dynamic_cast<const TestingConditionVariableWrapper::NotifyAllEvent*>(
              condition_variable->next_event()) == nullptr);
    condition_variable->set_block_notify_all(false);
    REQUIRE_NOTHROW(condition_variable->Step());
    REQUIRE_NOTHROW(condition_variable->WaitTillNextEvent());
    condition_variable->set_block_notify_all(true);

    for (size_t i = 0; i < max_buffered_spans_new; ++i) {
      auto span = tracer->StartSpan("abc");
      CHECK(span);
      span->Finish();
    }

    // Check that a NotifyAllEvent was added.
    CHECK(dynamic_cast<const TestingConditionVariableWrapper::NotifyAllEvent*>(
              condition_variable->next_event()) != nullptr);
    condition_variable->set_block_notify_all(false);
    REQUIRE_NOTHROW(condition_variable->Step());
    REQUIRE_NOTHROW(condition_variable->WaitTillNextEvent());
  }
}


text:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using XenAPI;

namespace XenAdmin.Controls.CheckableDataGridView
{
    public abstract class CheckableDataGridViewRow : DataGridViewRow
    {
        public virtual IXenObject XenObject { get; private set; }

        public delegate void CellTextUpdatedEvent(object sender, EventArgs e);
        public event CellTextUpdatedEvent CellDataUpdated;

        public CheckableDataGridViewRow() : this(null)
        {
        }

        protected CheckableDataGridViewRow(IXenObject xenObject)
        {
            XenObject = xenObject;
        }

        public abstract Queue<object> CellText { get; }

        public bool Checked { get; set; }

        public bool Highlighted { get; set; }

        private bool disabled;
        public bool Disabled
        {
            get { return disabled; }
            set
            {
                if(LockDisabledState)
                    return;
                disabled = value;
            }
        }

        private string disabledReason;
        public string DisabledReason
        {
            get { return disabledReason; }
            set
            {
                if(LockDisabledState)
                    return;
                disabledReason = value;
            }
        }

        public bool LockDisabledState { get; set; }

        public abstract bool WarningRequired { get; }

        public abstract string WarningText { get; }

        /// <summary>
        /// Override this if you cells data is loaded after it is first drawn
        /// </summary>
        public virtual bool CellDataLoaded
        {
            get { return true; }
        }

        public virtual void BeginCellUpdate(){}

        public bool Equals(CheckableDataGridViewRow other)
        {
            if (ReferenceEquals(null, other)) return false;
            if (ReferenceEquals(this, other)) return true;
            return XenObject.Equals(other.XenObject);
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            CheckableDataGridViewRow other = obj as CheckableDataGridViewRow;
            if (other == null) return false;
            return Equals(other);
        }

        public override int GetHashCode()
        {
            return (XenObject != null ? XenObject.GetHashCode() : 0);
        }

        public static bool operator ==(CheckableDataGridViewRow left, CheckableDataGridViewRow right)
        {
            return Equals(left, right);
        }

        public static bool operator !=(CheckableDataGridViewRow left, CheckableDataGridViewRow right)
        {
            return !Equals(left, right);
        }

        protected void TriggerCellTextUpdatedEvent()
        {
            if (CellDataUpdated != null)
                CellDataUpdated(this, EventArgs.Empty);
        }
    }
}


text:
package org.nebulae2us.stardust.translate.domain;

import org.junit.Test;

/**
 * @author Trung Phan
 *
 */
public class LikeTranslatorTest extends BaseTranslatorTest {

	private LikeTranslator likeTranslator = new LikeTranslator();

	@Test
	public void like__wildcard() {
		new TestCase().withTranslator(likeTranslator).translate("age like ?", "12%")
			.expectResult("mockedAttribute_age like ?")
			.expectValues("12%");
	}

	@Test
	public void not_like__wildcard() {
		new TestCase().withTranslator(likeTranslator).translate("age not like ?", "12%")
			.expectResult("mockedAttribute_age not like ?")
			.expectValues("12%");
	}

	@Test
	public void negated_like__wildcard() {
		new TestCase().withTranslator(likeTranslator).translateNegationOf("age like ?", "12%")
			.expectResult("mockedAttribute_age not like ?")
			.expectValues("12%");
	}

	@Test
	public void negated_not_like__wildcard() {
		new TestCase().withTranslator(likeTranslator).translateNegationOf("age not like ?", "12%")
			.expectResult("mockedAttribute_age like ?")
			.expectValues("12%");
	}

}


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

<title>Uses of Package net.alexanderdev.lightdrive.util.math.geom</title>
<meta name="date" content="2016-05-25">
<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

Next

Frames

No Frames

All Classes

Uses of Package
net.alexanderdev.lightdrive.util.math.geom

Packages that use net.alexanderdev.lightdrive.util.math.geom

Package
Description

net.alexanderdev.lightdrive.graphics

net.alexanderdev.lightdrive.input.gamepad

net.alexanderdev.lightdrive.util.math.geom

Classes in net.alexanderdev.lightdrive.util.math.geom used by net.alexanderdev.lightdrive.graphics

Class and Description

RectangleD

A simple wrapper class for Rectangle2D.Double.

RectangleF

A simple wrapper class for Rectangle2D.Float.

Classes in net.alexanderdev.lightdrive.util.math.geom used by net.alexanderdev.lightdrive.input.gamepad

Class and Description

VectorF

A class which represents a 2D vector with float precision.

Classes in net.alexanderdev.lightdrive.util.math.geom used by net.alexanderdev.lightdrive.util.math.geom

Class and Description

EllipseD

A simple wrapper class for Ellipse2D.Double.

EllipseF

A simple wrapper class for Ellipse2D.Float.

LineD

A simple wrapper class for Line2D.Double.

LineF

A simple wrapper class for Line2D.Float.

RectangleD

A simple wrapper class for Rectangle2D.Double.

RectangleF

A simple wrapper class for Rectangle2D.Float.

VectorD

A class which represents a 2D vector with float precision.

VectorF

A class which represents a 2D vector with float precision.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
package com.intellij.util.xml.impl;

import com.intellij.codeInsight.completion.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.util.Computable;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiReference;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.xml.XmlAttribute;
import com.intellij.psi.xml.XmlAttributeValue;
import com.intellij.psi.xml.XmlTag;
import com.intellij.util.ProcessingContext;
import com.intellij.util.containers.HashSet;
import com.intellij.xml.util.XmlUtil;
import com.intellij.xml.XmlAttributeDescriptor;

/**
 * @author peter
 */
public class DomCompletionContributor extends CompletionContributor{
  private final GenericValueReferenceProvider myProvider = new GenericValueReferenceProvider();

  @Override
  public void fillCompletionVariants(final CompletionParameters parameters, final CompletionResultSet result) {
    if (parameters.getCompletionType() != CompletionType.BASIC) return;

    if (domKnowsBetter(parameters, result)) {
      result.stopHere();
    }
  }

  private boolean domKnowsBetter(final CompletionParameters parameters, final CompletionResultSet result) {
    final PsiElement element = PsiTreeUtil.getParentOfType(parameters.getPosition(), XmlTag.class, XmlAttributeValue.class);
    return element != null && ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() {
      public Boolean compute() {
        if (isSchemaEnumerated(element)) {
          return false;
        }
        final PsiReference[] references = myProvider.getReferencesByElement(element, new ProcessingContext());
        if (references.length > 0) {
          return LegacyCompletionContributor.completeReference(parameters, result, new XmlCompletionData());
        }
        return false;
      }
    }).booleanValue();
  }

  public static boolean isSchemaEnumerated(final PsiElement element) {
    if (element instanceof XmlTag) {
      final XmlTag simpleContent = XmlUtil.getSchemaSimpleContent((XmlTag)element);
      if (simpleContent != null && XmlUtil.collectEnumerationValues(simpleContent, new HashSet<String>())) {
        return true;
      }
    }
    if (element instanceof XmlAttributeValue) {
      final PsiElement parent = element.getParent();
      if (parent instanceof XmlAttribute) {
        final XmlAttributeDescriptor descriptor = ((XmlAttribute)parent).getDescriptor();
        if (descriptor != null && descriptor.isEnumerated()) return true;
      }
    }
    return false;
  }
}


text:
namespace media {

class CameraDeviceContext;

// BufferInfo is used to store information about the buffer that is needed when
// building buffers.
struct BufferInfo {
  uint64_t ipc_id;
  gfx::Size dimension;
  gfx::GpuMemoryBufferHandle gpu_memory_buffer_handle;
  uint32_t drm_format;
  cros::mojom::HalPixelFormat hal_pixel_format;
};

// RequestBuilder is used to build capture request that will be sent to camera
// HAL process.
class CAPTURE_EXPORT RequestBuilder {
 public:
  using RequestBufferCallback = base::RepeatingCallback<
      absl::optional<BufferInfo>(StreamType, absl::optional<uint64_t>)>;

  RequestBuilder(CameraDeviceContext* device_context,
                 // Callback to request buffer from StreamBufferManager. Having
                 // this callback, we do not need to include StreamBufferManager
                 // when requesting buffer.
                 RequestBufferCallback request_buffer_callback);
  ~RequestBuilder();

  // Builds a capture request by given streams and settings. The
  // |input_buffer_id| is used for reprocess request.
  cros::mojom::Camera3CaptureRequestPtr BuildRequest(
      std::set<StreamType> stream_types,
      cros::mojom::CameraMetadataPtr settings,
      absl::optional<uint64_t> input_buffer_id);

 private:
  cros::mojom::CameraBufferHandlePtr CreateCameraBufferHandle(
      StreamType stream_type,
      BufferInfo buffer_info);

  cros::mojom::Camera3StreamBufferPtr CreateStreamBuffer(
      StreamType stream_type,
      uint64_t buffer_id,
      cros::mojom::CameraBufferHandlePtr buffer_handle);

  CameraDeviceContext* device_context_;

  // The frame number. Increased by one for each capture request sent.
  uint32_t frame_number_;

  RequestBufferCallback request_buffer_callback_;
};
}  // namespace media

#endif  // MEDIA_CAPTURE_VIDEO_CHROMEOS_REQUEST_BUILDER_H_


text:
COMPONENT=TestApp
MCTORRENT_ROOTDIR=../../..
include $(MCTORRENT_ROOTDIR)/tos/lib/McTorrent/Makefile.include
include $(MAKERULES)