text:
The purpose of this plugin is to provide a generic type in a blueprint in order
to integrate with REST based systems. The plugin is suitable for REST API's which
expose a relatively high level of abstraction. The general concept is to use JINJA
templates that will be evaluated as the content of several independent REST calls.
Very often it happens that certian intent requires several REST calls - therefore
we can put them in a single template to make blueprint much cleaner to read.

Features:

- JINJA templates
- selective update of runtime properties with REST response content
- configurable recoverable errors
- context sensitive "response expectation"

Action inputs in `cloudify.rest.Requests`:
* `params`: Template parameters. Default is empty dictionary.
* `params_attributes`: dictionary with list based path to values in
  `runtime_prioperties`.
* `template_file`: Template path in blueprint directory. Default is ''.
* `save_path`: Save result to runtime properties key. Default is directly
  save to runtime properties.
* `prerender`: Prerender template before run calls `jinja render` =>
  `yaml parse`. Default is `yaml parse` => `jinja render`.
* `remove_calls`: Remove calls list from results. Default: save calls in
  runtime properties.

Action inputs in `cloudify.rest.BunchRequests` is list of inputs from
`cloudify.rest.Requests`.

Node properties for `cloudify.rest.Requests` and `cloudify.rest.BunchRequests`:
* `hosts`: list of hosts name or IP addresses of Rest Servers
* `host`: host name or IP addresses of Rest Servers if list of hosts is not
  needed single host can be provided by this property. NOTE: the 'hosts'
  property overwirte the 'host' property
* `port`: port number. When -1 default ports are used (80 for ssl = false
  and 443 for ssl = true). Default: -1
* `ssl`: http or https. Default: `false`
* `verify`: A boolean which controls whether we verify the server's TLS
  certificate. Default: `true`
* `params`: Common params for all calls, will be merged with params from
each call/action.

### Blueprint

**Example Node Template single call:**

```yaml
  user:
    type: cloudify.rest.Requests
    properties:
      hosts:
      - { get_input: rest_endpoint }
      port: 443
      ssl: true
      verify: false
    interfaces:
      cloudify.interfaces.lifecycle:
        start:
          inputs:
            template_file: templates/get-user-all-properties-template.yaml
```

**Example Node Template bunch calls:**

```yaml
  user:
    cloudify.rest.BunchRequests
    properties:
      # hosts:
      # - { get_input: rest_endpoint }
      port: 443
      ssl: true
      verify: false
    interfaces:
      cloudify.interfaces.lifecycle:
        start:
          inputs:
            auth: # combine with properties
              hosts:
                - { get_input: rest_endpoint }
            templates:
            - template_file: templates/get-user-all-properties-template.yaml
```

### Templates

Templates are a place where we can place multiple
[REST template](https://github.com/cloudify-incubator/cloudify-utilities-plugins-sdk/blob/master/README.md#rest-yaml-template-format)
calls.

**Example content of REST template:**

```
rest_calls:
   - path: /users/10
    method: GET
    headers:
      Content-type: application/json
    payload:
    response_format: json
    recoverable_codes: [400]
    response_translation: [user]
    response_expectation:
        - ['id', '10']

  - path: /posts/{{POST_ID}}
    method: PUT
    headers:
      Content-type: application/json
    payload:
      title: '{{ USERNAME }}'
      body: '{{ WEBSITE }}'
      userId: '{{ USER_ID }}'
    response_format: json
    recoverable_codes: [400]
    response_expectation:
      - ['id', '{{POST_ID}}']

```

### Example

blueprint: [example-1-blueprint.yaml](examples/example-1-blueprint.yaml)

The example is a REST API from test website: https://jsonplaceholder.typicode.com/.

The purpose of blueprint is to demonstrate how **response_translation** work.

For example, suppose that you were to use a simple GET call, such as:

`GET https://jsonplaceholder.typicode.com/users/10**`

This returns the following JSON:

```json
{
    "id": 10,
    "name": "Clementina DuBuque",
    "username": "Moriah.Stanton",
    "email": "Rey.Padberg@karina.biz",
    "address": {
        "street": "Kattie Turnpike",
        "suite": "Suite 198",
        "city": "Lebsackbury",
        "zipcode": "31428-2261",
        "geo": {
            "lat": "-38.2386",
            "lng": "57.2232"
        }
    },
    "phone": "024-648-3804",
    "website": "ambrose.net",
    "company": {
        "name": "Hoeger LLC",
        "catchPhrase": "Centralized empowering task-force",
        "bs": "target end-to-end models"
    }
}
```

In the blueprint there are two nodes:

  * user10-all-properties - in this node we'will put complete response under
    **user** runtime property
  * user10-some-properties - in this node we'll selectively put response values
    under given keys

```shell
(cfy-4.2) $ cfy node-instances list
Listing all instances...

Node-instances:
+-------------------------------+---------------+---------+------------------------+---------+--------------+----------------+------------+
|               id              | deployment_id | host_id |        node_id         |  state  | availability |  tenant_name   | created_by |
+-------------------------------+---------------+---------+------------------------+---------+--------------+----------------+------------+
|  user10-all-properties_31b1sn |    example    |         | user10-all-properties  | started |    tenant    | default_tenant |   admin    |
| user10-some-properties_jbckbv |    example    |         | user10-some-properties | started |    tenant    | default_tenant |   admin    |
+-------------------------------+---------------+---------+------------------------+---------+--------------+----------------+------------+

(cfy-4.2) rest-plugin-examples$ cfy node-instances get user10-all-properties_31b1sn
Retrieving node instance user10-all-properties_31b1sn

Node-instance:
+------------------------------+---------------+---------+-----------------------+---------+--------------+----------------+------------+
|              id              | deployment_id | host_id |        node_id        |  state  | availability |  tenant_name   | created_by |
+------------------------------+---------------+---------+-----------------------+---------+--------------+----------------+------------+
| user10-all-properties_31b1sn |    example    |         | user10-all-properties | started |    tenant    | default_tenant |   admin    |
+------------------------------+---------------+---------+-----------------------+---------+--------------+----------------+------------+

Instance runtime properties:
    user: {'username': 'Moriah.Stanton', 'website': 'ambrose.net', 'name': 'Clementina DuBuque', 'company': {'bs': 'target end-to-end models', 'catchPhrase': 'Centralized empowering task-force', 'name': 'Hoeger LLC'}, 'id': 10, 'phone': '024-648-3804', 'address': {'suite': 'Suite 198', 'street': 'Kattie Turnpike', 'geo': {'lat': '-38.2386', 'lng': '57.2232'}, 'zipcode': '31428-2261', 'city': 'Lebsackbury'}, 'email': 'Rey.Padberg@karina.biz'}

(cfy-4.2) rest-plugin-examples$ cfy node-instances get user10-some-properties_jbckbv
Retrieving node instance user10-some-properties_jbckbv

Node-instance:
+-------------------------------+---------------+---------+------------------------+---------+--------------+----------------+------------+
|               id              | deployment_id | host_id |        node_id         |  state  | availability |  tenant_name   | created_by |
+-------------------------------+---------------+---------+------------------------+---------+--------------+----------------+------------+
| user10-some-properties_jbckbv |    example    |         | user10-some-properties | started |    tenant    | default_tenant |   admin    |
+-------------------------------+---------------+---------+------------------------+---------+--------------+----------------+------------+

Instance runtime properties:
    user-city-zip: 31428-2261
    user-email: Rey.Padberg@karina.biz
    user-city-geo: {'latitude': '-38.2386', 'longnitude': '57.2232'}
    user-full-name: Clementina DuBuque
    user-city: Lebsackbury

(cfy-4.2) rest-plugin-examples$

```

### Example 2

blueprint: [example-2-blueprint.yaml](examples/example-2-blueprint.yaml)

Same as above we're using test REST API but this time we'll demonstrate how we
can combine multiple REST calls in a single template. Overall idea is that
we'll first query REST API to provide user details and later on we'll use this
details in order to create user post with POST method.

### Example 3

blueprint: [example-2-blueprint.yaml](examples/example-2-blueprint.yaml)

Real life example how F5 BigIP can be provisioned with REST API

### Example 4

blueprint: [example-5-blueprint.yaml](examples/example-5-blueprint.yaml)

Example for get users list, create new user based on first result and than
remove new created user. Have used `cloudify.rest.BunchRequests` with
`params_attributes`.


text:
<?php

namespace CodeGenerationUtilsTest\Visitor;

use CodeGenerationUtils\Visitor\ClassExtensionVisitor;
use PHPParser_Node_Name;
use PHPParser_Node_Stmt_Class;
use PHPParser_Node_Stmt_Namespace;
use PHPUnit_Framework_TestCase;

/**
 * Tests for {@see \CodeGenerationUtils\Visitor\ClassClonerVisitor}
 *
 * @author Marco Pivetta <ocramius@gmail.com>
 * @license MIT
 *
 * @covers \CodeGenerationUtils\Visitor\ClassExtensionVisitor
 */
class ClassExtensionVisitorTest extends PHPUnit_Framework_TestCase
{
    public function testRenamesNodesOnMatchingClass()
    {
        $visitor   = new ClassExtensionVisitor('Foo\\Bar', 'Baz\\Tab');
        $class     = new PHPParser_Node_Stmt_Class('Bar');
        $namespace = new PHPParser_Node_Stmt_Namespace(new PHPParser_Node_Name('Foo'));

        $visitor->beforeTraverse(array());
        $this->assertSame($namespace, $visitor->enterNode($namespace));
        $this->assertNull($visitor->enterNode($class));
        $this->assertSame($class, $visitor->leaveNode($class));
        $this->assertNull($visitor->leaveNode($namespace));

        $this->assertNotNull($class->extends);
        $this->assertSame('Baz\\Tab', $class->extends->toString());
    }

    public function testIgnoresNodesOnNonMatchingClass()
    {
        $visitor   = new ClassExtensionVisitor('Foo\\Bar', 'Baz\\Tab');
        $class     = new PHPParser_Node_Stmt_Class('Tab');
        $namespace = new PHPParser_Node_Stmt_Namespace(new PHPParser_Node_Name('Foo'));

        $visitor->beforeTraverse(array());
        $this->assertSame($namespace, $visitor->enterNode($namespace));
        $this->assertNull($visitor->enterNode($class));
        $this->assertSame($class, $visitor->leaveNode($class));
        $this->assertNull($visitor->leaveNode($namespace));

        $this->assertNull($class->extends);
    }

    public function testIgnoresNodesOnNonMatchingNamespace()
    {
        $visitor   = new ClassExtensionVisitor('Foo\\Bar', 'Baz\\Tab');
        $class     = new PHPParser_Node_Stmt_Class('Bar');
        $namespace = new PHPParser_Node_Stmt_Namespace(new PHPParser_Node_Name('Tab'));

        $visitor->beforeTraverse(array());
        $this->assertSame($namespace, $visitor->enterNode($namespace));
        $this->assertNull($visitor->enterNode($class));
        $this->assertSame($class, $visitor->leaveNode($class));
        $this->assertNull($visitor->leaveNode($namespace));

        $this->assertNull($class->extends);
    }

    public function testMatchOnEmptyNamespace()
    {
        $visitor   = new ClassExtensionVisitor('Foo', 'Baz\\Tab');
        $class     = new PHPParser_Node_Stmt_Class('Foo');

        $visitor->beforeTraverse(array());
        $this->assertNull($visitor->enterNode($class));
        $this->assertSame($class, $visitor->leaveNode($class));

        $this->assertNotNull($class->extends);
        $this->assertSame('Baz\\Tab', $class->extends->toString());
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php $attributes = array('id' =>'drugPack_update_form' , 'class' =>'form-horizontal'); ?>

<?php if($this->session->flashdata('errorsUpdatedrugPack')): ?>

<?php echo ($this->session->flashdata('errorsUpdatedrugPack')); ?>
<?php endif; ?>

<?php if($this->session->flashdata('drugPack_update_unsuccess')): ?>
<?php echo ($this->session->flashdata('drugPack_update_unsuccess')); ?>
<?php endif; ?>

<?php echo form_open('DrugPack/drugPack_Update',$attributes);?>

            DrugPackId :

              <input type="text" class="form-control" id="UDrugPackId" name="UDrugPackId" placeholder="Enter DrugPack Id">

            DrugPack Name:

              <input type="text" class="form-control" id="UDrugPackName" name="UDrugPackName" placeholder="Enter DrugPack Name">

            UnitPrice:

              <input type="number" class="form-control" id="UUnitPrice" name="UUnitPrice" placeholder="Enter UnitPrice">

            Instruction:

              <input type="text" class="form-control" id="UInstruction" name="UInstruction" placeholder="Enter Instruction">

            Image:

                <input class="form-control" type="file" name="filename" accept="image/gif, image/jpeg, image/png" placeholder="Upload Image">

            Drug Items:

                <button type="button" class="btn btn-danger" data-toggle="modal" data-target="#UpdatedrugModal">Drugs</button>

              <button type="submit" class="btn btn-success">Submit</button>

                <?php
                $data['drugPackNames']=$drugPackNames;
                $data['drugPackItems']=$drugPackItems;
                $this->load->view('forms/CustomerDrug_update',$data);

                ?>

<?php echo form_close();?>


text:
local time = require("lib/time-master/time")
local RingBuffer = require("ringbuffer")

local meta = ngx.shared.meta
local states = ngx.shared.states

RingBuffer.new(states, 100)

meta:set("next_player_id", 0)
meta:set("current_tick", 0)
-- TODO add a secret here to make guessing random numbers harder
math.randomseed(ngx.time())


text:
PYTHONDONTWRITEBYTECODE=" " \
python -m bottle --debug --reload mikan:app


text:
package org.locationtech.geowave.core.store.query.aggregate;

import java.util.List;
import org.locationtech.geowave.core.index.persist.Persistable;
import org.locationtech.geowave.core.index.persist.PersistenceUtils;
import org.locationtech.geowave.core.store.api.Aggregation;
import org.locationtech.geowave.core.store.api.DataTypeAdapter;

public abstract class AbstractAggregationTest {

  /**
   * Aggregate given objects into a given aggregation.
   *
   * Internally, this splits the objectsToAggregate and gives it to separate aggregations, and
   * returns the merged results.
   *
   * @param aggregation The aggregation to give data to for testing.
   * @param objectsToAggregate The test data to feed into the aggregation
   * @return The results of aggregating the data.
   */
  @SuppressWarnings({"unchecked", "rawtypes"})
  protected <P extends Persistable, R, T> R aggregateObjects(
      final DataTypeAdapter<T> adapter,
      final Aggregation<P, R, T> aggregation,
      final List<T> objectsToAggregate) {
    final byte[] aggregationBytes = PersistenceUtils.toBinary(aggregation);
    final byte[] aggregationParameters = PersistenceUtils.toBinary(aggregation.getParameters());
    final Aggregation<P, R, T> agg1 = (Aggregation) PersistenceUtils.fromBinary(aggregationBytes);
    final Aggregation<P, R, T> agg2 = (Aggregation) PersistenceUtils.fromBinary(aggregationBytes);
    agg1.setParameters((P) PersistenceUtils.fromBinary(aggregationParameters));
    agg2.setParameters((P) PersistenceUtils.fromBinary(aggregationParameters));
    for (int i = 0; i < objectsToAggregate.size(); i++) {
      if ((i % 2) == 0) {
        agg1.aggregate(adapter, objectsToAggregate.get(i));
      } else {
        agg2.aggregate(adapter, objectsToAggregate.get(i));
      }
    }
    final byte[] agg1ResultBinary = agg1.resultToBinary(agg1.getResult());
    final byte[] agg2ResultBinary = agg2.resultToBinary(agg2.getResult());
    final R agg1Result = agg1.resultFromBinary(agg1ResultBinary);
    final R agg2Result = agg2.resultFromBinary(agg2ResultBinary);

    return aggregation.merge(agg1Result, agg2Result);
  }
}


text:
ALTER TABLE 'table1' CHANGE 'id' 'id' integer NOT NULL PRIMARY KEY AUTOINCREMENT;
CREATE UNIQUE INDEX 'table2_pri' ON 'table2' ( 'id' );


text:
$(document).ready(function(){

	$("#invite-form").on("submit", function(e){
		e.preventDefault();
		var $target = $(event.target)
		$.ajax({
			method: "post",
			url: $target.attr("action"),
			data: $target.serialize()

		}).done(function(resp){
			$("#invite-message").html("")
			$("#invite-message").prepend("

" + resp.responseText + "

")
		}).error(function(err){
			$("#invite-message").html("")
			$("#invite-message").prepend("

" + err.responseText + "

")
			$("#invite_invitee").val("")
			})
	});
})


text:
package adapt.resources;

import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.restlet.Context;
import org.restlet.data.CharacterSet;
import org.restlet.data.Encoding;
import org.restlet.data.MediaType;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.ext.freemarker.TemplateRepresentation;
import org.restlet.resource.Representation;
import org.restlet.resource.Resource;
import org.restlet.resource.Variant;

import adapt.core.AdaptApplication;
import adapt.core.AppCache;
import adapt.exceptions.EntityAttributeNotFoundException;
import adapt.model.ejb.AbstractAttribute;
import adapt.model.ejb.ColumnAttribute;
import adapt.model.ejb.EntityBean;
import adapt.model.ejb.JoinColumnAttribute;
import adapt.model.panel.AdaptStandardPanel;
import adapt.util.converters.ConverterUtil;
import adapt.util.ejb.EntityHelper;
import adapt.util.ejb.PersisenceHelper;
import adapt.util.resolvers.ComponentTypeResolver;
import adapt.util.staticnames.Settings;
import adapt.util.xml_readers.PanelReader;
import freemarker.template.Configuration;

public class BaseResource extends Resource {

	protected Map<String, Object> dataModel = new LinkedHashMap<String, Object>();
	String NULL = Settings.NULL_VALUE;

	public BaseResource(Context context, Request request, Response response) {
		super(context, request, response);
		setModifiable(true);
		getVariants().add(new Variant(MediaType.TEXT_HTML));
	}

	protected Representation getTemplateRepresentation(String templateName,
			Map<String, Object> dataModel, MediaType mt) {
		// The template representation is based on Freemarker.
		return new TemplateRepresentation(templateName, getFmcConfiguration(), dataModel, mt);
	}

	public Representation getHTMLTemplateRepresentation(String templateName,
			Map<String, Object> dataModel) {
		TemplateRepresentation represntation = new TemplateRepresentation(File.separator + "pages" + File.separator + templateName, getFmcConfiguration(), dataModel, MediaType.TEXT_HTML);
		Encoding enc = new Encoding("UTF-8");
		List<Encoding> encodings = new ArrayList<Encoding>();
		encodings.add(enc);
		represntation.setCharacterSet(CharacterSet.UTF_8);
		represntation.setEncodings(encodings);
		return represntation;
	}

	private Configuration getFmcConfiguration() {
		final AdaptApplication application = (AdaptApplication) getApplication();
		return application.getFmc();
	}

	@Override
	public void handlePost() {
		handleGet();
	}

	// -------------------------------------------------------------------------| COMMON UTIL METHODS

	public void addToDataModel(String key, Object val) {
		dataModel.put(key, val);
	}

	protected Object getObjectFromDB(String className, String id) {
		EntityManager em = PersisenceHelper.createEntityManager();
		try {
			Class claz = Class.forName(className);
			return em.find(claz, Long.parseLong(id));
		} catch (Exception e) {
			return null;
		}
	}

	public void prepareInputForm(AdaptStandardPanel panel) {
		Map<String, String> inputForm = new LinkedHashMap<String, String>();
		EntityBean bean = panel.getEntityBean();
		LinkedHashMap<String, String> zoomMap = new LinkedHashMap<String, String>();

		for (AbstractAttribute attribute : bean.getAttributes()) {
			String fieldName = attribute.getFieldName();
			if(attribute instanceof ColumnAttribute) {
				if(!attribute.getHidden()) {
					ColumnAttribute colAttribute = (ColumnAttribute)attribute;
					String type = colAttribute.getDataType();
					if(colAttribute.getEnumeration() != null) {
						type += ":ComboBox";
					}
					String componentTemplate = ComponentTypeResolver.getTemplate(type);
					inputForm.put(fieldName, componentTemplate);
				}
			}else if(attribute instanceof JoinColumnAttribute){
				JoinColumnAttribute jcAttribute = (JoinColumnAttribute)attribute;
				String type = "kroki.joinColumn";
				String componentTemplate = ComponentTypeResolver.getTemplate(type);
				// For join columns first assign zoom filed template
				inputForm.put(fieldName, componentTemplate);
				// Then get data from database to fill the combo box
				// TODO Substitute combo box zoom with classic lookup fields
				/*LinkedHashMap<String, String> zoomValues = getZoomMap(jcAttribute);
				if(!zoomValues.isEmpty()) {
					zoomMap.put(fieldName, zoomValues);
				}else {
					AppCache.displayTextOnMainFrame("Error getting zoom values for: " + bean.getName() + "." + fieldName, 1);
				}*/
				Class<?> zoomClass = jcAttribute.getLookupClass();
				String panelId = AppCache.getInstance().getPanelId(zoomClass.getName());
				zoomMap.put(fieldName, panelId);

			}else {
				System.out.println("ELSE!");
			}
		}
		addToDataModel("inputForm", inputForm);
		addToDataModel("zoomMap", zoomMap);
	}

	/*
	 * Gets data for zoom UI component from database
	 * Data is feched in map which keys represent referenced entities ids, and values are refferenced columns values separated by comma
	 */
	protected LinkedHashMap<String, String> getZoomMap(JoinColumnAttribute jcAttribute) {
		LinkedHashMap<String, String> values = new LinkedHashMap<String, String>();
		ArrayList<ColumnAttribute> columnRefs = (ArrayList<ColumnAttribute>) jcAttribute.getColumns();
		String q = "FROM " + jcAttribute.getLookupClass().getSimpleName();
		EntityManager em = PersisenceHelper.createEntityManager();
		em.getTransaction().begin();
		Query query = em.createQuery(q);
		List<Object> results = query.getResultList();

		em.getTransaction().commit();
		em.close();

		// TODO check if zoom attribute is required before adding the NULL value
		values.put("null", "-- " + NULL + "--");

		// Get referenced entity class
		Class oClass = jcAttribute.getLookupClass();
		// For each returned object from database, get referenced attribute values using reflection
		for (Object object : results) {
			try {
				Field idField = oClass.getDeclaredField("id");
				idField.setAccessible(true);
				String idVal = idField.get(object).toString();
				String refValues = getZoomValues(columnRefs, oClass, object);
				values.put(idVal.toString(), refValues);
			} catch (NoSuchFieldException e1) {
				e1.printStackTrace();
			} catch (SecurityException e1) {
				e1.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		return values;
	}

	private String getZoomValues(ArrayList<ColumnAttribute> columnRefs, Class oClass, Object object) {
		String colRefs = "";
		for (ColumnAttribute columnAttribute : columnRefs) {
			try {
				Field field = oClass.getDeclaredField(columnAttribute.getFieldName());
				field.setAccessible(true);
				String fieldVal = field.get(object).toString();
				colRefs += fieldVal.toString() + ", ";
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
		}
		String stripComma = colRefs.substring(0, colRefs.length() -2);
		return stripComma;
	}

	// Get attribute values for given EJB bean using reflection
	protected ArrayList<String> getLookupValuesJSON(JoinColumnAttribute joinColumn, String id) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
		ArrayList<String> values = new ArrayList<String>();
		Class ejbClass = joinColumn.getLookupClass();

		String query = "FROM " + ejbClass.getSimpleName() + " x WHERE x.id = " + id;
		EntityManager em = PersisenceHelper.createEntityManager();
		em.getTransaction().begin();
		Query q = em.createQuery(query);
		Object result = q.getSingleResult();

		if(result != null) {
			//go trough referenced columns and get their values
			for (ColumnAttribute column : joinColumn.getColumns()) {
				try {
					Field columnField = ejbClass.getDeclaredField(column.getFieldName());
					columnField.setAccessible(true);
					String columnValue = ConverterUtil.convertForViewing(columnField.get(result), column);
					// FORMAT: "name": "State-id", "value": 1
					values.add("\"name\": \"" + joinColumn.getFieldName() + "-" + column.getFieldName() + "\", \"value\": \"" + columnValue + "\"");
				} catch (Exception e) {
					System.out.println("[getLookupValuesJSON] " + e.getClass().getSimpleName() + ": " + e.getMessage());
				}
			}
		}
		em.getTransaction().commit();
		em.close();
		return values;
	}

	protected JoinColumnAttribute getJoinByFieldName(EntityBean bean, String fieldName) throws EntityAttributeNotFoundException {
		Iterator<AbstractAttribute> it = bean.getAttributes().iterator();
		AbstractAttribute attr = null;
		while (it.hasNext()) {
			attr = it.next();
			if (attr instanceof JoinColumnAttribute) {
				if (((JoinColumnAttribute) attr).getFieldName().equals(fieldName)) {
					return (JoinColumnAttribute) attr;
				}
			}
		}
		throw new EntityAttributeNotFoundException(
				"Entity attribute not found with the field name '"
						+ fieldName + "' in entity class '"
						+ bean.getEntityClass().getName() + "'");
	}

	public Map<String, Object> getDataModel() {
		return dataModel;
	}

	public void setDataModel(Map<String, Object> dataModel) {
		this.dataModel = dataModel;
	}
}


text:
package pgsgo

import pgs "github.com/lyft/protoc-gen-star"

// Context resolves Go-specific language for Packages & Entities generated by
// protoc-gen-go. The rules that drive the naming behavior are complicated, and
// result from an interplay of the go_package file option, the proto package,
// and the proto filename itself. Therefore, it is recommended that all proto
// files that are targeting Go should include a fully qualified go_package
// option. These must be consistent for all proto files that are intended to be
// in the same Go package.
type Context interface {
	// Params returns the Parameters associated with this context.
	Params() pgs.Parameters

	// Name returns the name of a Node as it would appear in the generation output
	// of protoc-gen-go. For each type, the following is returned:
	//
	//     - Package: the Go package name
	//     - File: the Go package name
	//     - Message: the struct name
	//     - Field: the field name on the Message struct
	//     - OneOf: the field name on the Message struct
	//     - Enum: the type name
	//     - EnumValue: the constant name
	//     - Service: the server interface name
	//     - Method: the method name on the server and client interface
	//
	Name(node pgs.Node) pgs.Name

	// ServerName returns the name of the server interface for the Service.
	ServerName(service pgs.Service) pgs.Name

	// ClientName returns the name of the client interface for the Service.
	ClientName(service pgs.Service) pgs.Name

	// ServerStream returns the name of the grpc.ServerStream wrapper for this
	// method. This name is only used if client or server streaming is
	// implemented for this method.
	ServerStream(method pgs.Method) pgs.Name

	// OneofOption returns the struct name that wraps a OneOf option's value. These
	// messages contain one field, matching the value returned by Name for this
	// Field.
	OneofOption(field pgs.Field) pgs.Name

	// TypeName returns the type name of a Field as it would appear in the
	// generated message struct from protoc-gen-go. Fields from imported
	// packages will be prefixed with the package name.
	Type(field pgs.Field) TypeName

	// PackageName returns the name of the Node's package as it would appear in
	// Go source generated by the official protoc-gen-go plugin.
	PackageName(node pgs.Node) pgs.Name

	// ImportPath returns the Go import path for an entity as it would be
	// included in an import block in a Go file. This value is only appropriate
	// for Entities imported into a target file/package.
	ImportPath(entity pgs.Entity) pgs.FilePath

	// OutputPath returns the output path relative to the plugin's output destination
	OutputPath(entity pgs.Entity) pgs.FilePath
}

type context struct{ p pgs.Parameters }

// InitContext configures a Context that should be used for deriving Go names
// for all Packages and Entities.
func InitContext(params pgs.Parameters) Context {
	return context{params}
}

func (c context) Params() pgs.Parameters { return c.p }


text:
Bernoulli with `p = sigmoid(p)`.
- - -

#### `tf.contrib.distributions.BernoulliWithSigmoidP.__init__(p=None, dtype=tf.int32, validate_args=False, allow_nan_stats=True, name='BernoulliWithSigmoidP')` {#BernoulliWithSigmoidP.__init__}

- - -

#### `tf.contrib.distributions.BernoulliWithSigmoidP.allow_nan_stats` {#BernoulliWithSigmoidP.allow_nan_stats}

Python boolean describing behavior when a stat is undefined.

Stats return +/- infinity when it makes sense.  E.g., the variance
of a Cauchy distribution is infinity.  However, sometimes the
statistic is undefined, e.g., if a distribution's pdf does not achieve a
maximum within the support of the distribution, the mode is undefined.
If the mean is undefined, then by definition the variance is undefined.
E.g. the mean for Student's T for df = 1 is undefined (no clear way to say
it is either + or - infinity), so the variance = E[(X - mean)^2] is also
undefined.

##### Returns:

*  <b>`allow_nan_stats`</b>: Python boolean.

- - -

#### `tf.contrib.distributions.BernoulliWithSigmoidP.batch_shape(name='batch_shape')` {#BernoulliWithSigmoidP.batch_shape}

Shape of a single sample from a single event index as a 1-D `Tensor`.

The product of the dimensions of the `batch_shape` is the number of
independent distributions of this kind the instance represents.

##### Args:

*  <b>`name`</b>: name to give to the op

##### Returns:

*  <b>`batch_shape`</b>: `Tensor`.

- - -

#### `tf.contrib.distributions.BernoulliWithSigmoidP.cdf(value, name='cdf', **condition_kwargs)` {#BernoulliWithSigmoidP.cdf}

Cumulative distribution function.

Given random variable `X`, the cumulative distribution function `cdf` is:

```
cdf(x) := P[X <= x]
```

##### Args:

*  <b>`value`</b>: `float` or `double` `Tensor`.
*  <b>`name`</b>: The name to give this op.
*  <b>`**condition_kwargs`</b>: Named arguments forwarded to subclass implementation.

##### Returns:

*  <b>`cdf`</b>: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with
    values of type `self.dtype`.

- - -

#### `tf.contrib.distributions.BernoulliWithSigmoidP.copy(**override_parameters_kwargs)` {#BernoulliWithSigmoidP.copy}

Creates a deep copy of the distribution.

Note: the copy distribution may continue to depend on the original
intialization arguments.

##### Args:

*  <b>`**override_parameters_kwargs`</b>: String/value dictionary of initialization
    arguments to override with new values.

##### Returns:

*  <b>`distribution`</b>: A new instance of `type(self)` intitialized from the union
    of self.parameters and override_parameters_kwargs, i.e.,
    `dict(self.parameters, **override_parameters_kwargs)`.

- - -

#### `tf.contrib.distributions.BernoulliWithSigmoidP.dtype` {#BernoulliWithSigmoidP.dtype}

The `DType` of `Tensor`s handled by this `Distribution`.

- - -

#### `tf.contrib.distributions.BernoulliWithSigmoidP.entropy(name='entropy')` {#BernoulliWithSigmoidP.entropy}

Shannon entropy in nats.

- - -

#### `tf.contrib.distributions.BernoulliWithSigmoidP.event_shape(name='event_shape')` {#BernoulliWithSigmoidP.event_shape}

Shape of a single sample from a single batch as a 1-D int32 `Tensor`.

##### Args:

*  <b>`name`</b>: name to give to the op

##### Returns:

*  <b>`event_shape`</b>: `Tensor`.

- - -

#### `tf.contrib.distributions.BernoulliWithSigmoidP.get_batch_shape()` {#BernoulliWithSigmoidP.get_batch_shape}

Shape of a single sample from a single event index as a `TensorShape`.

Same meaning as `batch_shape`. May be only partially defined.

##### Returns:

*  <b>`batch_shape`</b>: `TensorShape`, possibly unknown.

- - -

#### `tf.contrib.distributions.BernoulliWithSigmoidP.get_event_shape()` {#BernoulliWithSigmoidP.get_event_shape}

Shape of a single sample from a single batch as a `TensorShape`.

Same meaning as `event_shape`. May be only partially defined.

##### Returns:

*  <b>`event_shape`</b>: `TensorShape`, possibly unknown.

- - -

#### `tf.contrib.distributions.BernoulliWithSigmoidP.is_continuous` {#BernoulliWithSigmoidP.is_continuous}

- - -

#### `tf.contrib.distributions.BernoulliWithSigmoidP.is_scalar_batch(name='is_scalar_batch')` {#BernoulliWithSigmoidP.is_scalar_batch}

Indicates that `batch_shape == []`.

##### Args:

*  <b>`name`</b>: The name to give this op.

##### Returns:

*  <b>`is_scalar_batch`</b>: `Boolean` `scalar` `Tensor`.

- - -

#### `tf.contrib.distributions.BernoulliWithSigmoidP.is_scalar_event(name='is_scalar_event')` {#BernoulliWithSigmoidP.is_scalar_event}

Indicates that `event_shape == []`.

##### Args:

*  <b>`name`</b>: The name to give this op.

##### Returns:

*  <b>`is_scalar_event`</b>: `Boolean` `scalar` `Tensor`.

- - -

#### `tf.contrib.distributions.BernoulliWithSigmoidP.log_cdf(value, name='log_cdf', **condition_kwargs)` {#BernoulliWithSigmoidP.log_cdf}

Log cumulative distribution function.

Given random variable `X`, the cumulative distribution function `cdf` is:

```
log_cdf(x) := Log[ P[X <= x] ]
```

Often, a numerical approximation can be used for `log_cdf(x)` that yields
a more accurate answer than simply taking the logarithm of the `cdf` when
`x << -1`.

##### Args:

*  <b>`value`</b>: `float` or `double` `Tensor`.
*  <b>`name`</b>: The name to give this op.
*  <b>`**condition_kwargs`</b>: Named arguments forwarded to subclass implementation.

##### Returns:

*  <b>`logcdf`</b>: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with
    values of type `self.dtype`.

- - -

#### `tf.contrib.distributions.BernoulliWithSigmoidP.log_pdf(value, name='log_pdf', **condition_kwargs)` {#BernoulliWithSigmoidP.log_pdf}

Log probability density function.

##### Args:

*  <b>`value`</b>: `float` or `double` `Tensor`.
*  <b>`name`</b>: The name to give this op.
*  <b>`**condition_kwargs`</b>: Named arguments forwarded to subclass implementation.

##### Returns:

*  <b>`log_prob`</b>: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with
    values of type `self.dtype`.

##### Raises:

*  <b>`TypeError`</b>: if not `is_continuous`.

- - -

#### `tf.contrib.distributions.BernoulliWithSigmoidP.log_pmf(value, name='log_pmf', **condition_kwargs)` {#BernoulliWithSigmoidP.log_pmf}

Log probability mass function.

##### Args:

*  <b>`value`</b>: `float` or `double` `Tensor`.
*  <b>`name`</b>: The name to give this op.
*  <b>`**condition_kwargs`</b>: Named arguments forwarded to subclass implementation.

##### Returns:

*  <b>`log_pmf`</b>: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with
    values of type `self.dtype`.

##### Raises:

*  <b>`TypeError`</b>: if `is_continuous`.

- - -

#### `tf.contrib.distributions.BernoulliWithSigmoidP.log_prob(value, name='log_prob', **condition_kwargs)` {#BernoulliWithSigmoidP.log_prob}

Log probability density/mass function (depending on `is_continuous`).

##### Args:

*  <b>`value`</b>: `float` or `double` `Tensor`.
*  <b>`name`</b>: The name to give this op.
*  <b>`**condition_kwargs`</b>: Named arguments forwarded to subclass implementation.

##### Returns:

*  <b>`log_prob`</b>: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with
    values of type `self.dtype`.

- - -

#### `tf.contrib.distributions.BernoulliWithSigmoidP.log_survival_function(value, name='log_survival_function', **condition_kwargs)` {#BernoulliWithSigmoidP.log_survival_function}

Log survival function.

Given random variable `X`, the survival function is defined:

```
log_survival_function(x) = Log[ P[X > x] ]
                         = Log[ 1 - P[X <= x] ]
                         = Log[ 1 - cdf(x) ]
```

Typically, different numerical approximations can be used for the log
survival function, which are more accurate than `1 - cdf(x)` when `x >> 1`.

##### Args:

*  <b>`value`</b>: `float` or `double` `Tensor`.
*  <b>`name`</b>: The name to give this op.
*  <b>`**condition_kwargs`</b>: Named arguments forwarded to subclass implementation.

##### Returns:

  `Tensor` of shape `sample_shape(x) + self.batch_shape` with values of type
    `self.dtype`.

- - -

#### `tf.contrib.distributions.BernoulliWithSigmoidP.logits` {#BernoulliWithSigmoidP.logits}

Log-odds of success.

- - -

#### `tf.contrib.distributions.BernoulliWithSigmoidP.mean(name='mean')` {#BernoulliWithSigmoidP.mean}

Mean.

- - -

#### `tf.contrib.distributions.BernoulliWithSigmoidP.mode(name='mode')` {#BernoulliWithSigmoidP.mode}

Mode.

Additional documentation from `Bernoulli`:

Returns `1` if `p > 1-p` and `0` otherwise.

- - -

#### `tf.contrib.distributions.BernoulliWithSigmoidP.name` {#BernoulliWithSigmoidP.name}

Name prepended to all ops created by this `Distribution`.

- - -

#### `tf.contrib.distributions.BernoulliWithSigmoidP.p` {#BernoulliWithSigmoidP.p}

Probability of success.

- - -

#### `tf.contrib.distributions.BernoulliWithSigmoidP.param_shapes(cls, sample_shape, name='DistributionParamShapes')` {#BernoulliWithSigmoidP.param_shapes}

Shapes of parameters given the desired shape of a call to `sample()`.

This is a class method that describes what key/value arguments are required
to instantiate the given `Distribution` so that a particular shape is
returned for that instance's call to `sample()`.

Subclasses should override class method `_param_shapes`.

##### Args:

*  <b>`sample_shape`</b>: `Tensor` or python list/tuple. Desired shape of a call to
    `sample()`.
*  <b>`name`</b>: name to prepend ops with.

##### Returns:

  `dict` of parameter name to `Tensor` shapes.

- - -

#### `tf.contrib.distributions.BernoulliWithSigmoidP.param_static_shapes(cls, sample_shape)` {#BernoulliWithSigmoidP.param_static_shapes}

param_shapes with static (i.e. `TensorShape`) shapes.

This is a class method that describes what key/value arguments are required
to instantiate the given `Distribution` so that a particular shape is
returned for that instance's call to `sample()`.  Assumes that
the sample's shape is known statically.

Subclasses should override class method `_param_shapes` to return
constant-valued tensors when constant values are fed.

##### Args:

*  <b>`sample_shape`</b>: `TensorShape` or python list/tuple. Desired shape of a call
    to `sample()`.

##### Returns:

  `dict` of parameter name to `TensorShape`.

##### Raises:

*  <b>`ValueError`</b>: if `sample_shape` is a `TensorShape` and is not fully defined.

- - -

#### `tf.contrib.distributions.BernoulliWithSigmoidP.parameters` {#BernoulliWithSigmoidP.parameters}

Dictionary of parameters used to instantiate this `Distribution`.

- - -

#### `tf.contrib.distributions.BernoulliWithSigmoidP.pdf(value, name='pdf', **condition_kwargs)` {#BernoulliWithSigmoidP.pdf}

Probability density function.

##### Args:

*  <b>`value`</b>: `float` or `double` `Tensor`.
*  <b>`name`</b>: The name to give this op.
*  <b>`**condition_kwargs`</b>: Named arguments forwarded to subclass implementation.

##### Returns:

*  <b>`prob`</b>: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with
    values of type `self.dtype`.

##### Raises:

*  <b>`TypeError`</b>: if not `is_continuous`.

- - -

#### `tf.contrib.distributions.BernoulliWithSigmoidP.pmf(value, name='pmf', **condition_kwargs)` {#BernoulliWithSigmoidP.pmf}

Probability mass function.

##### Args:

*  <b>`value`</b>: `float` or `double` `Tensor`.
*  <b>`name`</b>: The name to give this op.
*  <b>`**condition_kwargs`</b>: Named arguments forwarded to subclass implementation.

##### Returns:

*  <b>`pmf`</b>: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with
    values of type `self.dtype`.

##### Raises:

*  <b>`TypeError`</b>: if `is_continuous`.

- - -

#### `tf.contrib.distributions.BernoulliWithSigmoidP.prob(value, name='prob', **condition_kwargs)` {#BernoulliWithSigmoidP.prob}

Probability density/mass function (depending on `is_continuous`).

##### Args:

*  <b>`value`</b>: `float` or `double` `Tensor`.
*  <b>`name`</b>: The name to give this op.
*  <b>`**condition_kwargs`</b>: Named arguments forwarded to subclass implementation.

##### Returns:

*  <b>`prob`</b>: a `Tensor` of shape `sample_shape(x) + self.batch_shape` with
    values of type `self.dtype`.

- - -

#### `tf.contrib.distributions.BernoulliWithSigmoidP.q` {#BernoulliWithSigmoidP.q}

1-p.

- - -

#### `tf.contrib.distributions.BernoulliWithSigmoidP.reparameterization_type` {#BernoulliWithSigmoidP.reparameterization_type}

Describes how samples from the distribution are reparameterized.

Currently this is one of the static instances
`distributions.FULLY_REPARAMETERIZED`
or `distributions.NOT_REPARAMETERIZED`.

##### Returns:

  An instance of `ReparameterizationType`.

- - -

#### `tf.contrib.distributions.BernoulliWithSigmoidP.sample(sample_shape=(), seed=None, name='sample', **condition_kwargs)` {#BernoulliWithSigmoidP.sample}

Generate samples of the specified shape.

Note that a call to `sample()` without arguments will generate a single
sample.

##### Args:

*  <b>`sample_shape`</b>: 0D or 1D `int32` `Tensor`. Shape of the generated samples.
*  <b>`seed`</b>: Python integer seed for RNG
*  <b>`name`</b>: name to give to the op.
*  <b>`**condition_kwargs`</b>: Named arguments forwarded to subclass implementation.

##### Returns:

*  <b>`samples`</b>: a `Tensor` with prepended dimensions `sample_shape`.

- - -

#### `tf.contrib.distributions.BernoulliWithSigmoidP.stddev(name='stddev')` {#BernoulliWithSigmoidP.stddev}

Standard deviation.

- - -

#### `tf.contrib.distributions.BernoulliWithSigmoidP.survival_function(value, name='survival_function', **condition_kwargs)` {#BernoulliWithSigmoidP.survival_function}

Survival function.

Given random variable `X`, the survival function is defined:

```
survival_function(x) = P[X > x]
                     = 1 - P[X <= x]
                     = 1 - cdf(x).
```

##### Args:

*  <b>`value`</b>: `float` or `double` `Tensor`.
*  <b>`name`</b>: The name to give this op.
*  <b>`**condition_kwargs`</b>: Named arguments forwarded to subclass implementation.

##### Returns:

  `Tensor` of shape `sample_shape(x) + self.batch_shape` with values of type
    `self.dtype`.

- - -

#### `tf.contrib.distributions.BernoulliWithSigmoidP.validate_args` {#BernoulliWithSigmoidP.validate_args}

Python boolean indicated possibly expensive checks are enabled.

- - -

#### `tf.contrib.distributions.BernoulliWithSigmoidP.variance(name='variance')` {#BernoulliWithSigmoidP.variance}

Variance.


text:
package org.assertj.core.api.integer_;

import org.assertj.core.api.IntegerAssert;
import org.assertj.core.api.IntegerAssertBaseTest;

import static org.mockito.Mockito.verify;

/**
 * Tests for <code>{@link IntegerAssert#isOdd()}</code>.
 *
 * @author Cal027
 */
class IntegerAssert_isOdd_Test extends IntegerAssertBaseTest {

  @Override
  protected IntegerAssert invoke_api_method() {
    return assertions.isOdd();
  }

  @Override
  protected void verify_internal_effects() {
    verify(integers).assertIsOdd(getInfo(assertions), getActual(assertions));
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="PublishConfigData">
    <serverData>
      <paths name="cmm.mikeamato.org">
        <serverdata>
          <mappings>
            <mapping local="$PROJECT_DIR$" web="/" />
          </mappings>
        </serverdata>
      </paths>
      <paths name="cmmReact">
        <serverdata>
          <mappings>
            <mapping local="$PROJECT_DIR$" web="/" />
          </mappings>
        </serverdata>
      </paths>
      <paths name="listingpass">
        <serverdata>
          <mappings>
            <mapping local="$PROJECT_DIR$" web="/" />
          </mappings>
        </serverdata>
      </paths>
      <paths name="mikeamato.org">
        <serverdata>
          <mappings>
            <mapping local="$PROJECT_DIR$" web="/" />
          </mappings>
        </serverdata>
      </paths>
    </serverData>
  </component>
</project>


text:
using System.Windows;
using GalaSoft.MvvmLight;
using System;
using System.Collections.Generic;
using System.Windows.Controls;
using System.Windows.Input;
using WaveDev.ModelR.Communication;
using WaveDev.ModelR.Shared.Models;
using WaveDev.ModelR.Shared;
using System.Linq;
using GalaSoft.MvvmLight.Messaging;
using WaveDev.ModelR.Messages;

namespace WaveDev.ModelR.ViewModels
{
    public class LogonModel : ViewModelBase
    {
        #region Private Fields

        private RelayCommand _loginCommand;
        private ModelRHubClientProxy _proxy;
        private string _serverUrl;

        #endregion

        #region Construction

        public LogonModel()
        {
            _serverUrl = Constants.ModelRServerUrl;

            InitializeCommunicationCommand.Execute(null);
        }

        #endregion

        #region Public Members

        public string ServerUrl
        {
            get
            {
                return _serverUrl;
            }

            set
            {
                if (_serverUrl != value)
                {
                    Set(ref _serverUrl, value);

                    // [RS] Reinitialize connection because of changed server adress.
                    InitializeCommunicationCommand.Execute(null);
                }
            }
        }

        public string UserName
        {
            get;
            set;
        }

        public ICommand CancelLoginCommand
        {
            get
            {
                return new RelayCommand(parameter => Application.Current.Shutdown(), () => true);
            }
        }

        public ICommand LoginCommand
        {
            get
            {
                if (_loginCommand == null)
                {
                    // [RS] Log on takes place at startup only. So caching the login command is not needed. For the this time we cache it.
                    _loginCommand = new RelayCommand(parameter =>
                    {
                        // [RS] Break the MVVM pattern here, because the Password-property in the WPF PasswordBox cannot be data bound
                        //      due to security reasons. So we pass the control to the model for query the password from the control directly.
                        var passwordBox = parameter as PasswordBox;
                        var password = string.Empty;

                        if (passwordBox != null)
                            password = passwordBox.Password;

                        try
                        {
                            _proxy.Login(UserName, password, SelectedScene.Id);
                        }
                        catch (UserNotAuthorizedException exception)
                        {
                            Messenger.Default.Send<ExceptionCausedApplicationShutdownMessage>(
                                new ExceptionCausedApplicationShutdownMessage()
                            {
                                Exception = exception,
                                ShowMessageToUser = true
                            });
                        }

                    }, () => true);
                }

                return _loginCommand;
            }
        }

        public IEnumerable<SceneInfoModel> Scenes
        {
            get
            {
                return _proxy.Scenes;
            }
        }

        public SceneInfoModel SelectedScene
        {
            get;
            set;
        }

        #endregion

        #region Private Members

        private ICommand InitializeCommunicationCommand
        {
            get
            {
                return new RelayCommand(parameter =>
                {
                    try
                    {
                        _proxy = ModelRHubClientProxy.GetInstance(_serverUrl);

                        SelectedScene = _proxy.Scenes.FirstOrDefault();
                    }
                    catch (InvalidOperationException exception)
                    {
                        Messenger.Default.Send<ExceptionCausedApplicationShutdownMessage>(
                            new ExceptionCausedApplicationShutdownMessage()
                        {
                            Exception = exception,
                            ShowMessageToUser = true
                        });
                    }
                }, () => true);
            }
        }

        #endregion

    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using Monitor.Tests.Helpers;
using Microsoft.Azure.Management.Monitor;
using Microsoft.Azure.Management.Monitor.Models;
using Xunit;

namespace Monitor.Tests.BasicTests
{
    public class LogProfilesTests : TestBase
    {
        private const string ResourceId = "/subscriptions/0e44ac0a-5911-482b-9edd-3e67625d45b5/providers/microsoft.insights/logprofiles/default";

        private static string DefaultName = "default";

        [Fact]
        [Trait("Category", "Mock")]
        public void LogProfiles_CreateOrUpdateTest()
        {
            LogProfileResource expResponse = CreateLogProfile();
            var handler = new RecordedDelegatingHandler();
            var insightsClient = GetMonitorManagementClient(handler);
            var serializedObject = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(expResponse, insightsClient.SerializationSettings);
            var expectedResponse = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(serializedObject)
            };

            handler = new RecordedDelegatingHandler(expectedResponse);
            insightsClient = GetMonitorManagementClient(handler);

            var parameters = CreateLogProfileParams();

            LogProfileResource actualResponse = insightsClient.LogProfiles.CreateOrUpdate(logProfileName: DefaultName, parameters: parameters);

            AreEqual(expResponse, actualResponse);
        }

        [Fact]
        [Trait("Category", "Mock")]
        public void LogProfiles_DeleteTest()
        {
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(string.Empty)
            };

            var handler = new RecordedDelegatingHandler(response);
            MonitorManagementClient customClient = this.GetMonitorManagementClient(handler);

            customClient.LogProfiles.Delete(logProfileName: DefaultName);
        }

        [Fact]
        [Trait("Category", "Mock")]
        public void LogProfiles_GetTest()
        {
            var expResponse = CreateLogProfile();
            var handler = new RecordedDelegatingHandler();
            var insightsClient = GetMonitorManagementClient(handler);
            var serializedObject = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(expResponse, insightsClient.SerializationSettings);
            var expectedResponse = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(serializedObject)
            };

            handler = new RecordedDelegatingHandler(expectedResponse);
            insightsClient = GetMonitorManagementClient(handler);

            LogProfileResource actualResponse = insightsClient.LogProfiles.Get(logProfileName: DefaultName);
            AreEqual(expResponse, actualResponse);
        }

        [Fact]
        [Trait("Category", "Mock")]
        public void LogProfiles_ListTest()
        {
            var logProfile = CreateLogProfile();
            var expResponse = new List<LogProfileResource>
            {
                logProfile
            };

            var handler = new RecordedDelegatingHandler();
            var insightsClient = GetMonitorManagementClient(handler);
            var serializedObject = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(expResponse, insightsClient.SerializationSettings);
            var expectedResponse = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(string.Concat("{ \"value\":", serializedObject, "}"))
            };

            handler = new RecordedDelegatingHandler(expectedResponse);
            insightsClient = GetMonitorManagementClient(handler);

            IList<LogProfileResource> actualResponse = insightsClient.LogProfiles.List().ToList<LogProfileResource>();

            Assert.Equal(expResponse.Count, actualResponse.Count);
            AreEqual(expResponse[0], actualResponse[0]);
        }

        [Fact]
        [Trait("Category", "Mock")]
        public void LogProfiles_UpdateTest()
        {
            LogProfileResource resource = CreateLogProfile();
            var handler = new RecordedDelegatingHandler();
            var monitorManagementClient = GetMonitorManagementClient(handler);
            var serializedObject = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(resource, monitorManagementClient.SerializationSettings);
            var expectedResponse = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(serializedObject)
            };

            handler = new RecordedDelegatingHandler(expectedResponse);
            monitorManagementClient = GetMonitorManagementClient(handler);

            LogProfileResourcePatch patchResource = new LogProfileResourcePatch(
                locations: resource.Locations,
                categories: resource.Categories,
                retentionPolicy: resource.RetentionPolicy,
                tags: resource.Tags,
                serviceBusRuleId: resource.ServiceBusRuleId,
                storageAccountId: resource.StorageAccountId
                );

            LogProfileResource actualResponse = monitorManagementClient.LogProfiles.Update(logProfileName: DefaultName, logProfilesResource: patchResource);
            AreEqual(resource, actualResponse);
        }

        private static LogProfileResource CreateLogProfile()
        {
            return new LogProfileResource
            {
                StorageAccountId = "/subscriptions/4d7e91d4-e930-4bb5-a93d-163aa358e0dc/resourceGroups/Default-Web-westus/providers/microsoft.storage/storageaccounts/sa1",
                ServiceBusRuleId = "/subscriptions/4d7e91d4-e930-4bb5-a93d-163aa358e0dc/resourceGroups/Default-Web-westus/providers/microsoft.servicebus/namespaces/sb1/authorizationrules/ar1",
                Categories = new List<string> { "Delete", "Write" },
                Locations = new List<string> { "global", "eastus" },
                RetentionPolicy = new RetentionPolicy
                {
                    Days = 4,
                    Enabled = true,
                }
            };
        }

        private static LogProfileResource CreateLogProfileParams()
        {
            return new LogProfileResource
            {
                StorageAccountId = "/subscriptions/4d7e91d4-e930-4bb5-a93d-163aa358e0dc/resourceGroups/Default-Web-westus/providers/microsoft.storage/storageaccounts/sa1",
                ServiceBusRuleId = "/subscriptions/4d7e91d4-e930-4bb5-a93d-163aa358e0dc/resourceGroups/Default-Web-westus/providers/microsoft.servicebus/namespaces/sb1/authorizationrules/ar1",
                Categories = new List<string> { "Delete", "Write" },
                Locations = new List<string> { "global", "eastus" },
                RetentionPolicy = new RetentionPolicy
                {
                    Days = 4,
                    Enabled = true,
                },
                Location = ""
            };
        }

        private static void AreEqual(LogProfileResource exp, LogProfileResource act)
        {
            if (exp != null)
            {
                CompareListString(exp.Categories, act.Categories);
                CompareListString(exp.Locations, act.Locations);

                Assert.Equal(exp.RetentionPolicy.Enabled, act.RetentionPolicy.Enabled);
                Assert.Equal(exp.RetentionPolicy.Days, act.RetentionPolicy.Days);
                Assert.Equal(exp.ServiceBusRuleId, act.ServiceBusRuleId);
                Assert.Equal(exp.StorageAccountId, act.StorageAccountId);
            }
        }

        private static void CompareListString(IList<string> exp, IList<string> act)
        {
            if (exp == act)
            {
                return;
            }

            if (exp == null)
            {
                Assert.Null(act);
            }

            Assert.False(act == null, "List can't be null");

            for (int i = 0; i < exp.Count; i++)
            {
                if (i >= act.Count)
                {
                    Assert.Equal(exp.Count, act.Count);
                }

                string cat1 = exp[i];
                string cat2 = act[i];
                Assert.Equal(cat1, cat2);
            }

            Assert.Equal(exp.Count, act.Count);
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OKHOSTING.School
{
	public class Teacher
	{
		public Guid Id { get; set; }

		public string FirstName { get; set; }

		public string LastName { get; set; }

		public IEnumerable<Task> Tasks { get; set; }

		public IEnumerable<Student> Students { get; set; }

		public IEnumerable<Subject> Subjects { get; set; }

		public void sendTask()
		{

		}

		public override string ToString()
		{
			return FirstName + " " + LastName;
		}
	}
}


text:
<?php

abstract class controller {
    public $actions = array(), $model;
    protected static $nonce = null;

    public function __construct($options) {
        if (!is_array($options)) {
            throw new Exception("选项错误");
        }
    }

    protected function generate_nonce() {
        if (empty(self::$nonce)) {
            self::$nonce = base64_encode(uniqid(null, true));
            $_SESSION['nonce'] = self::$nonce;
        }
        return self::$nonce;
    }

    public function check_nonce() {
        if (isset($_SESSION['nonce']) && !empty($_SESSION['nonce']) && isset($_POST['nonce']) && !empty($_POST['nonce']) && $_SESSION['nonce'] === $_POST['nonce']) {
            $_SESSION['nonce'] = null;
            return true;
        } else {
            return false;
        }
    }

    protected function sanitize($dirty) {
        return htmlentities(strip_tags($dirty), ENT_QUOTES);
    }

    public function handle_form_submission($action) {
        if ($this->check_nonce()) {
            $output = $this->{$this->actions[$action]}();
            if (is_array($output) && isset($output['room_id'])) {
                $room_id = $output['room_id'];
            } else {
                throw new Exception('表单提交失败');
            }
            $pusher = new Pusher(PUSHER_KEY, PUSHER_SECRET, PUSHER_APPID);
            $channel = 'presence-room_' . $room_id;
            $pusher->trigger($channel, $action, $output);
            header('Location:' . APP_URI . 'room/' . $room_id);
            exit;
        } else {
            throw new Exception('无效的临时code');
        }
    }

    abstract public function get_title();

    abstract public function output_view();
}


text:
import os
import json
import settings
import sys
from watchdog.observers import Observer
from watchdog.observers.api import ObservedWatch

from kivy.app import App
from kivy.core.window import Window
from kivy.lang import Builder, Parser, ParserException
from kivy.properties import ListProperty, StringProperty, \
    ObjectProperty
from kivy.factory import Factory
from kivy.uix.gridlayout import GridLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.screenmanager import SlideTransition
from kivy.clock import Clock
from kivy.uix.progressbar import ProgressBar
from kivy.uix.spinner import Spinner
from kivy.uix.scatter import Scatter
from kivy.uix.widget import WidgetException
from kivy.uix.screenmanager import ScreenManagerException

from shortcuts import run_syscall, striptags, findparent
from checker import ChangeHandler
from buttons import *
from boxlayouts import *

Clock.max_iteration = 20

KVS = os.path.join(settings.PROJECT_PATH, "assets%sthemes" %
                   settings.PATH_SEPERATOR)
CLASSES = [c[:-3] for c in os.listdir(KVS) if c.endswith('.kv')]
ICON_PATH = os.path.join(settings.PROJECT_PATH, 'assets/GitWatcher.ico')

class MyScatter(Scatter):
    name = StringProperty("")
    sha = StringProperty("")
    text = StringProperty("")
    date = StringProperty("")

class CustomLabel(Label):

    def __del__(self, *args, **kwargs):
        pass

class ConfirmPopup(GridLayout):

    """
    ConfirmPopup is for to handle user input yes-no
    """
    text = StringProperty()

    def __del__(self, *args, **kwargs):
        pass

    def __init__(self, **kwargs):
        self.register_event_type('on_answer')
        super(ConfirmPopup, self).__init__(**kwargs)

    def on_answer(self, *args):
        pass

class RemotePopup(GridLayout):

    """
    RemotePopup is for listing all remote names and address for users
    """
    remotes = ListProperty([])
    branch = StringProperty("")

    def __init__(self, **kwargs):
        self.register_event_type('on_push')
        super(RemotePopup, self).__init__(**kwargs)

    def args_converter(self, row_index, item):
        return {
            'remote_path': item['path'],
            'remote_name': item['name']
        }

    def on_push(self, *args):
        pass

class CustomSpinner(Spinner):

    """
    Base Spinner class has _on_dropdown_select method which holds
    only change the text attribute of class which is not enough.

    CustomSpinner used to display local branch list so any changes
    of this is actually means changing current branch.
    """

    def __del__(self, *args, **kwargs):
        pass

    def _on_dropdown_select(self, instance, data, *largs):
        self.text = "[b]%s[/b]" % data
        self.is_open = False

        root = findparent(self, RepoWatcher)
        root.change_branch(data, self.path)

class Menu(BoxLayout):

    """
    .kv files are actually classes so each of them should be converted.
    Each .kv files are actually corresponded to a menu button base class
    name chosen as 'Menu'
    """

    def __del__(self, *args, **kwargs):
        pass

    def __init__(self, **kwargs):
        super(Menu, self).__init__(**kwargs)
        parser = Parser(content=open(self.kv_file).read())
        widget = Factory.get(parser.root.name)()
        Builder._apply_rule(widget, parser.root, parser.root)
        self.add_widget(widget)

    @property
    def kv_file(self):
        return os.path.join(KVS, self.__class__.__name__ + '.kv')

for class_name in CLASSES:
    globals()[class_name] = type(class_name, (Menu,), {})

class RepoWatcher(BoxLayout):

    """
    RepoWatcher is the based/main class all others generated under this class
    ::repos: repository list which contains all repositories required fields;
        names, paths
    ::active_menu_button: based on the active menu button which are history,
        change, settings and branch screen will change
    ::screen_manager: To handle screen management an attribute will be more
        efficient. By this way there will be no miss
    ::pb: progression can be dislayed

    methods: show_kv, load_repo, get_activebranch, get_branches, change_branch
    """
    repos = ListProperty()
    screen_manager = ObjectProperty()

    # Change control handler necessity
    observer = ObjectProperty(None)

    pb = ProgressBar()

    def __del__(self, *args, **kwargs):
        pass

    def __init__(self, *args, **kwargs):
        # Related kv will be return
        super(BoxLayout, self).__init__(*args, **kwargs)

        if 'initialize' in kwargs:
            screen_button = {
                'Changes': self.changes_button,
                'History': self.history_button,
                'Branches': self.branches_button,
                'Settings': self.settings_button
            }

            # previously selected repo should be found.
            try:
                reponame = settings.DB.store_get('current_repo').strip()
                repos = settings.DB.store_get('repos')
                repo = filter(
                    lambda x: x['name'].strip() == reponame, repos)[0]
                repo_path = repo['path']
            except:
                repo_path = ""

            # Previously selected button and related screen is taken
            screen = settings.DB.store_get('screen')
            if screen == "FileDiff":
                screen = "History"
            screen_button[screen].make_pressed()

            # Based on the screen base model will be taken
            related_box = getattr(
                self.screen_manager, screen.lower()).children[0].children[0]

            # Then related box'es processes will be called.
            # To know that the screen was loaded before all
            # related processes is called.
            function_name = ""
            for func in ['changes_check', 'branches_check',
                         'check_history', 'settings_check']:
                if hasattr(related_box, func):
                    function_name = func
                    break

            if function_name == 'changes_check':
                tasks = [self.show_kv(screen),
                         self.activate_sync(repo_path),
                         self.get_branches(repo_path),
                         related_box.get_userinfo(repo_path),
                         related_box.get_difffiles(repo_path),
                         related_box.get_unpushedcommits(repo_path),
                         related_box.get_current_branch(repo_path)]

            elif function_name == 'branches_check':
                tasks = [self.show_kv(screen),
                         self.activate_sync(repo_path),
                         self.get_branches(repo_path),
                         related_box.set_repopath(repo_path),
                         related_box.handle_merge_view(repo_path),
                         related_box.remove_newbranch_widget(repo_path),
                         related_box.remove_rename_widget(repo_path),
                         related_box.get_branches(repo_path),
                         related_box.clear_buttonactions(repo_path)]

            elif function_name == 'check_history':
                tasks = [self.show_kv(screen),
                         self.activate_sync(repo_path),
                         self.get_branches(repo_path),
                         related_box.get_history(repo_path),
                         related_box.get_diff_clear(repo_path)]

            elif function_name == 'settings_check':
                tasks = [self.show_kv(screen),
                         self.activate_sync(repo_path),
                         self.get_branches(repo_path),
                         related_box.set_repopath(repo_path),
                         related_box.get_remote(repo_path),
                         related_box.get_gitignore(repo_path)]

            # Processes will be called and displayed completed ones on
            # animation.
            ProgressAnimator(self.pb, tasks)
            os.chdir(settings.PROJECT_PATH)

            self.observer_restart(repo_path, self)

    def show_kv(self, value):
        """
        show_kv function is for handle the screen_manager changes
        default was called on init as 'Changes' the names of value
        are represented on main .kv file. Corresponded screen
        in other way to say .kv file displayed.

        ::value: String formatted as 'Changes', 'History', 'Branches',
                'Settings', 'FileDiff'

        In runtime, selected menu button checked for class name, by this way
        screen datas update or keep.
        """
        from boxlayouts import ChangesBox, BranchesBox, SettingsBox, HistoryBox

        settings.DB.store_put('screen', value)
        settings.DB.store_sync()

        def _wrapper(callback=None):
            try:
                # Transition handled
                if value == "FileDiff":
                    self.screen_manager.transition = SlideTransition(
                        direction='right')
                else:
                    self.screen_manager.transition = SlideTransition(
                        direction='left')

                # screen changes
                prev = self.screen_manager.current
                self.screen_manager.current = value
                child = self.screen_manager.current_screen.children[0]

                # Menu selection control and related repository tried to find
                selected_menu_class = child.children[0].__class__

                repolist = self.repolstview.children[0].children[0].children
                pressed_repo = filter(lambda x: x.repobut.pressed, repolist)
                repo_path = pressed_repo[0].repo_path if pressed_repo else ""

                # Related screen and repository data merged and screen datas
                # update.
                if repo_path:
                    if selected_menu_class == ChangesBox().__class__:
                        child.children[0].changes_check(repo_path)

                    elif selected_menu_class == HistoryBox().__class__:
                        keep_old = False
                        if prev == 'FileDiff':
                            keep_old = True
                        child.children[0].check_history(repo_path,
                                                        keep_old=keep_old)

                    elif selected_menu_class == BranchesBox().__class__:
                        child.children[0].branches_check(repo_path)

                    elif selected_menu_class == SettingsBox().__class__:
                        child.children[0].settings_check(repo_path)
                else:
                    if selected_menu_class == BranchesBox().__class__:
                        child.children[0].remove_newbranch_widget("")
                        child.children[0].remove_rename_widget("")
                        child.children[0].handle_merge_view("")
            except (WidgetException, ScreenManagerException):
                pass

            if callback:
                callback()

        return _wrapper

    def activate_sync(self, path):
        def _wrapper(callback=None):
            if path:
                self.syncbutton.text = self.syncbutton.text.\
                    replace(settings.HEX_COLOR1, '000000')
                self.syncbutton.path = path
            if callback:
                callback()
        return _wrapper

    def reset_screen(self):
        """
        reset_screen, if repo somehow removed from
            list then screens should be cleared.
        """
        child = self.screen_manager.current_screen.children[0]
        selected_menu_class = child.children[0].__class__

        if selected_menu_class == ChangesBox().__class__:
            child.children[0].changes_check("")

        elif selected_menu_class == HistoryBox().__class__:
            child.children[0].check_history("", keep_old=False)

        elif selected_menu_class == BranchesBox().__class__:
            child.children[0].branches_check("")

        elif selected_menu_class == SettingsBox().__class__:
            child.children[0].settings_check("")

    def theme_args_converter(self, row_index, item):
        """
        theme_args_converter; is for converting only color schemas
        """
        return {
            'name': item
        }

    def args_converter(self, row_index, item):
        """
        args_converter, for displaying repositories
        To display a list of data this convertion style is
        requested for kivy Factory method.
        """
        return {
            'repo_path': item['path'],
            'repo_name': item['name'],
            'init_pressed': item['init_pressed']}

    def load_repo(self, reset=True):
        """
        load_repo, for loading repository list from .json file (if exists).
        file path is found on settings. In any exception repos sets to empty list
        """
        try:
            self.repos = settings.DB.store_get('repos')
            settings.DB.store_sync()
            try:
                reponame = settings.DB.store_get('current_repo').strip()
                repo = filter(
                    lambda x: x['name'].strip() == reponame, self.repos)
                repo = repo and repo[0] or ""
                for rep in self.repos:
                    rep['init_pressed'] = True if rep == repo else False
            except Exception, e:
                print "BARBAROS", e
                pass
        except (TypeError, ValueError, KeyError):
            directory = os.path.dirname(settings.REPOFILE)
            if not os.path.exists(directory):
                os.makedirs(directory)
                settings.DB.store_put('repos', [])
                settings.DB.store_put('current_repo', "")
                settings.DB.store_sync()
            self.repos = []
        if reset:
            self.reset_screen()

    def remove_repo(self, path):
        try:
            repos = settings.DB.store_get('repos')
            self.repos = filter(lambda x: x['path'] != path, repos)
            settings.DB.store_put('repos', self.repos)
            settings.DB.store_sync()
        except (TypeError, ValueError):
            self.repos = []
        finally:
            self.reset_screen()

    def get_activebranch(self, path):
        """
        get_activebranch, to find the current branch of selected git repository.

        ::path: Repository path
        """
        os.chdir(path)
        out = run_syscall('git branch')
        text = filter(
            lambda x: x.find("* ") != -1, out.split("\n"))[0].replace("* ", "")
        os.chdir(settings.PROJECT_PATH)
        return text

    def get_branches(self, path):
        """
        get_branches, collects local branches of repository

        ::path: Repository path.
        ::callback: at the end method calls

        callback method is for to show the progression of bulk of method if any.
        """
        def _wrapper(callback=None):
            if path:
                os.chdir(path)
                out = run_syscall('git branch')
                values = map(
                    lambda x: x.replace("* ", "").strip(), out.split("\n"))
                text = self.get_activebranch(path)
                self.branchlist.text = "[color=%s][b]%s[/b][/color]" % (
                    settings.HEX_COLOR1, text)
                self.branchlist.values = values
                self.branchlist.path = path
                self.branchlist.font_name = settings.KIVY_DEFAULT_FONT
                os.chdir(settings.PROJECT_PATH)
            else:
                self.branchlist.text = ""
                self.branchlist.values = []
                self.branchlist.path = ""
                self.branchlist.font_name = settings.KIVY_DEFAULT_FONT
            if callback:
                callback()

        return _wrapper

    def change_branch(self, branch_name, path):
        """
        change_branch, handle changing current branches.

        ::branch_name: branch name which wanted to checkout
        ::path: related repository path

        branch name is marked up to use that markup should be cleared
        """
        try:
            branch_name = striptags(branch_name)
            os.chdir(path)
            out = run_syscall(
                'git stash clear;git stash;git checkout %s;git stash pop' % branch_name)
            screen = self.screen_manager.children[0].children[0].children[0]
            if self.screen_manager.current == "History":
                screen.check_history(path)
            elif self.screen_manager.current == "Changes":
                screen.changes_check(path)
            elif self.screen_manager.current == "Branches":
                screen.branches_check(path)
            elif self.screen_manager.current == 'Settings':
                screen.settings_check(path)
        except OSError:
            pass
        finally:
            os.chdir(settings.PROJECT_PATH)

    def refresh_required(self, path):
        repoitems = self.repolstview.children[0].children[0].children
        if path:
            for item in repoitems:
                if item.repobut.repo_path == path:
                    item.refreshbut.textcolor = settings.HEX_COLOR1
        else:
            for item in repoitems:
                if item.repobut.repo_path == path:
                    item.refreshbut.textcolor = settings.HEX_COLOR2

    def observer_start(self, repo_path, root):
        if repo_path:
            event_handler = ChangeHandler(path=repo_path, root=root)
            self.observer = Observer()
            self.observer.schedule(
                event_handler, path=repo_path, recursive=True)
            self.observer.start()

    def observer_stop(self):
        if self.observer:
            self.observer.stop()
            self.observer.join()

    def observer_restart(self, repo_path, root):
        self.observer_stop()
        self.observer_start(repo_path, root)

class RepoWatcherApp(App):

    def __init__(self, *args, **kwargs):
        super(RepoWatcherApp, self).__init__(*args, **kwargs)
        Builder.load_file('%(pp)s%(ps)sassets%(ps)sthemes%(ps)sCompact.kv' %
                          {'pp': settings.PROJECT_PATH,
                           'ps': settings.PATH_SEPERATOR})
        self.layout = RepoWatcher(initialize=True)
        self.icon = ICON_PATH
        self.title = "Git Watcher UI"

    def __del__(self, *args, **kwargs):
        pass

    def build(self):
        """
        Main application object creation, required calls handled
        such title, icon and repository list are sets and
        data collections taken

        ::title: set the title of project
        ::icon: to displayed icon is set

        Builder should be take style, on Mac the same name of
        main application on the same folder will be enough
        but on linux based OS this should be hold by developer
        ::Builder.load_file(...)

        main application 'RepoWatcher' should be hold all
        previously set repository datas, to do that 'load_repo' function called
        """

        self.layout.load_repo()

        return self.layout

    def restart(self):
        args = sys.argv[:]
        args.insert(0, sys.executable)
        os.execv(sys.executable, args)

    def on_stop(self):
        self.layout.observer_stop()

if __name__ == '__main__':
    RepoWatcherApp().run()


text:
\begin{tikzpicture}[node distance=10.5em]
    \node[relationship] (arrests) {Arrests};
    \node[entity] (person) [right of=arrests] {Person};
    \draw (person.165) edge [<-] node[auto,swap] {cop} (arrests.35)
          (person.-165) edge node[auto] {robber} (arrests.-35);
\end{tikzpicture}


text:
"""Tests for broadcast_to ops."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np

from tensorflow.python.eager import context
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors
from tensorflow.python.framework import test_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import gradient_checker_v2
from tensorflow.python.platform import test as test_lib

class BroadcastToTest(test_util.TensorFlowTestCase):

  def testBroadcastToBasic(self):
    for dtype in [np.uint8, np.uint16, np.int8, np.int16, np.int32, np.int64]:
      with self.session(use_gpu=True):
        x = np.array([1, 2, 3], dtype=dtype)
        v_tf = array_ops.broadcast_to(constant_op.constant(x), [3, 3])
        v_np = np.broadcast_to(x, [3, 3])
        self.assertAllEqual(v_tf, v_np)

  def testBroadcastToString(self):
    with self.session(use_gpu=True):
      x = np.array([b"1", b"2", b"3"])
      v_tf = array_ops.broadcast_to(constant_op.constant(x), [3, 3])
      v_np = np.broadcast_to(x, [3, 3])
      self.assertAllEqual(v_tf, v_np)

  def testBroadcastToBool(self):
    with self.session(use_gpu=True):
      x = np.array([True, False, True], dtype=np.bool)
      v_tf = array_ops.broadcast_to(constant_op.constant(x), [3, 3])
      v_np = np.broadcast_to(x, [3, 3])
      self.assertAllEqual(v_tf, v_np)

  def testBroadcastToShape(self):
    for input_dim in range(1, 6):
      for output_dim in range(input_dim, 6):
        with self.cached_session(use_gpu=True):
          input_shape = [2] * input_dim
          output_shape = [2] * output_dim
          x = np.array(np.random.randint(5, size=input_shape), dtype=np.int32)
          v_tf = array_ops.broadcast_to(constant_op.constant(x), output_shape)
          v_np = np.broadcast_to(x, output_shape)
          self.assertAllEqual(v_tf, v_np)

  def testBroadcastToShapeInnerDim(self):
    input_shape = [2, 1, 3]
    output_shape = [2, 5, 3]
    with self.cached_session(use_gpu=True):
      x = np.array(np.random.randint(5, size=input_shape), dtype=np.int32)
      v_tf = array_ops.broadcast_to(constant_op.constant(x), output_shape)
      v_np = np.broadcast_to(x, output_shape)
      self.assertAllEqual(v_tf, v_np)

  def testBroadcastToShapeLargerDim(self):
    input_shape = [2, 1, 3, 2, 2, 2]
    output_shape = [1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 15, 3, 2, 2, 2]
    with self.cached_session(use_gpu=True):
      x = np.array(np.random.randint(5, size=input_shape), dtype=np.int32)
      v_tf = array_ops.broadcast_to(constant_op.constant(x), output_shape)
      v_np = np.broadcast_to(x, output_shape)
      self.assertAllEqual(v_tf, v_np)

  def testBroadcastToShapeLargerDim2(self):
    input_shape = [2, 1, 3, 2, 2, 2, 1, 1, 1]
    output_shape = [1, 1, 1, 2, 5, 3, 2, 2, 2, 3, 3, 3]
    with self.cached_session(use_gpu=True):
      x = np.array(np.random.randint(5, size=input_shape), dtype=np.int32)
      v_tf = array_ops.broadcast_to(constant_op.constant(x), output_shape)
      v_np = np.broadcast_to(x, output_shape)
      self.assertAllEqual(v_tf, v_np)

  def testBroadcastToScalar(self):
    with self.session(use_gpu=True):
      x = np.array(1, dtype=np.int32)
      v_tf = array_ops.broadcast_to(constant_op.constant(x), [3, 3])
      v_np = np.broadcast_to(x, [3, 3])
      self.assertAllEqual(v_tf, v_np)

  def testBroadcastScalarToNonScalar(self):
    with self.session(use_gpu=True):
      x = np.array(1.0, dtype=np.float)
      v_tf = array_ops.broadcast_to(constant_op.constant(1.0), [2, 3, 4,
                                                                1, 1, 1])
      v_np = np.broadcast_to(x, [2, 3, 4, 1, 1, 1])
      self.assertAllEqual(v_tf, v_np)

  def testBroadcastToShapeTypeAndInference(self):
    for dtype in [dtypes.int32, dtypes.int64]:
      with self.cached_session(use_gpu=True):
        x = np.array([1, 2, 3])
        v_tf = array_ops.broadcast_to(
            constant_op.constant(x),
            constant_op.constant([3, 3], dtype=dtype))
        shape = v_tf.get_shape().as_list()
        v_np = np.broadcast_to(x, [3, 3])
        self.assertAllEqual(v_tf, v_np)
        # check shape inference when shape input is constant
        self.assertAllEqual(shape, v_np.shape)

  def testBroadcastToBadOutputShape(self):
    with context.eager_mode():
      with self.assertRaisesRegex(errors.InvalidArgumentError,
                                  "Unable to broadcast tensor of shape"):
        self.evaluate(
            array_ops.broadcast_to(
                constant_op.constant([0, 1]), constant_op.constant([2, 1])))

  def testGradientForScalar(self):
    x = constant_op.constant(1, dtype=dtypes.float32)

    def func(x):
      v = array_ops.broadcast_to(x, [2, 4, 3])
      return 2 * v

    with self.cached_session():
      err = gradient_checker_v2.max_error(
          *gradient_checker_v2.compute_gradient(func, [x]))

    self.assertLess(err, 1e-4)

  def testGradientWithSameRank(self):
    x = constant_op.constant(np.reshape(np.arange(6), (2, 1, 3)),
                             dtype=dtypes.float32)
    def func(x):
      v = array_ops.broadcast_to(x, [2, 5, 3])
      return 2 * v

    with self.cached_session():
      err = gradient_checker_v2.max_error(
          *gradient_checker_v2.compute_gradient(func, [x], delta=1e-2))

    self.assertLess(err, 1e-4)

  def testGradientWithIncreasingRank(self):
    x = constant_op.constant([[1], [2]],
                             dtype=dtypes.float32)
    def func(x):
      v = array_ops.broadcast_to(x, [5, 2, 3])
      return 2 * v

    with self.cached_session():
      err = gradient_checker_v2.max_error(
          *gradient_checker_v2.compute_gradient(func, [x]))

    self.assertLess(err, 1e-4)

  def testGradientWithBroadcastAllDimensions(self):
    x = constant_op.constant([1], dtype=dtypes.float32)
    def func(x):
      v = array_ops.broadcast_to(x, [5, 2, 3])
      return 2 * v

    with self.cached_session():
      err = gradient_checker_v2.max_error(
          *gradient_checker_v2.compute_gradient(func, [x]))

    self.assertLess(err, 1e-4)

  def testGradientWithLargeDim(self):
    input_shape = [2, 1, 3, 2, 2, 2, 1, 1, 1]
    output_shape = [1, 1, 1, 2, 5, 3, 2, 2, 2, 3, 3, 3]
    x = constant_op.constant(np.array(np.random.randn(*input_shape),
                                      dtype=np.float32))
    def func(x):
      v = array_ops.broadcast_to(x, output_shape)
      return 2 * v

    with self.cached_session():
      err = gradient_checker_v2.max_error(
          *gradient_checker_v2.compute_gradient(func, [x], delta=1e-2))

    self.assertLess(err, 1e-4)

  def testBroadcastToInvalidShape(self):
    with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError),
                                "110,53,104,147,157,123,5,24,188,40,5,2"):
      output_shape = [110, 53, 104, 147, 157, 123, 5, 24, 188, 40, 5, 2]
      x = np.array([1, 2, 3], dtype=np.int32)
      v = array_ops.broadcast_to(constant_op.constant(x), output_shape)
      self.evaluate(v)

if __name__ == "__main__":
  test_lib.main()


text:
namespace A4CoreBlog.Data.Common.Models
{
    public interface IOrderable
    {
        int OrderBy { get; set; }
    }
}


text:
require.ensure([], function(require) {
require("./26.async.js");
require("./52.async.js");
require("./104.async.js");
require("./208.async.js");
});
module.exports = 209;


text:
title: Entity.atName - detekt-api
---

[detekt-api](../../index.html) / [io.gitlab.arturbosch.detekt.api](../index.html) / [Entity](index.html) / [atName](./at-name.html)

# atName

`fun atName(element: KtNamedDeclaration): `[`Entity`](index.html)

Create an entity at the location of the identifier of given named declaration.


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

namespace ZKWeb.ORM.Dapper {
	///
	/// The non-generic interface for entity mapping

	/// 非泛型的实体映射定义的接口

	///
	public interface IDapperEntityMapping {
		///
		/// The entity type

		/// 实体类型

		///
		Type EntityType { get; }
		///
		/// The table name

		/// 表名

		///
		string TableName { get; }
		///
		/// Id member

		/// Id成员

		///
		MemberInfo IdMember { get; }
		///
		/// Ordinary members, not releated to other entities

		/// 普通成员, 与其他实体无关的成员

		///
		IEnumerable<MemberInfo> OrdinaryMembers { get; }
	}
}


text:
@import QuartzCore;

@interface UIView (WAdditionsPrivate)

- (void) dumpView:(UIView *) superView i:(int) i;

@end

@implementation UIView (WAdditions)

- (UIScrollView *) findScrollView
{
	if ([self isKindOfClass: [UIScrollView class]] || [self isKindOfClass: NSClassFromString(@"UIScroller")]) {
		return (UIScrollView *) self;
	}

	for (UIView *child in self.subviews) {
		UIScrollView *result = [child findScrollView];

		if (result) {
			return result;
		}
	}
	return nil;
}

- (UIImage *) takeScreenshot
{
	UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, [UIScreen mainScreen].scale);
	[self.layer renderInContext: UIGraphicsGetCurrentContext()];
	UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
	return viewImage;
}

- (void) dumpView
{
	NSLog(@"Dumping view:");

	if ([self isKindOfClass: [UIScrollView class]] || [self isKindOfClass: NSClassFromString(@"UIScroller")]) {
		UIScrollView *scrollView = (UIScrollView *) self;
		NSLog(@"|0 %li %@ f: %@ s: %@", (long)self.tag, NSStringFromClass([self class]), NSStringFromCGRect(self.frame), NSStringFromCGSize(scrollView.contentSize));
	} else {
		NSLog(@"|0 %li %@ f: %@", (long)self.tag, NSStringFromClass([self class]), NSStringFromCGRect(self.frame));
	}
	[self dumpView: self i: 1];
}

- (void) dumpView:(UIView *) superView i:(int) i
{
	int e = 0;
	for (UIView *view in [superView subviews]) {

		if ([view isKindOfClass: [UIImageView class]]) {
			UIImageView *imageView = (UIImageView *) view;
			NSLog(@"|%i%@ %li %@ f: %@ i: %@ ", i, [@"" stringByPaddingToLength: i withString: @"_" startingAtIndex: 0], (long)view.tag,
				  NSStringFromClass([view class]), imageView.image, NSStringFromCGRect(imageView.frame));
		} else if ([view isKindOfClass: [UIScrollView class]] || [view isKindOfClass: NSClassFromString(@"UIScroller")]) {
			UIScrollView *scrollView = (UIScrollView *) view;
			NSLog(@"|%i%@ %li %@ f: %@ s: %@", i, [@"" stringByPaddingToLength: i withString: @"_" startingAtIndex: 0], (long)view.tag,
				  NSStringFromClass([view class]), NSStringFromCGRect(view.frame), NSStringFromCGSize(scrollView.contentSize));
		} else {
			NSLog(@"|%i%@ %li %@ f: %@", i, [@"" stringByPaddingToLength: i withString: @"_" startingAtIndex: 0], (long)view.tag,
				  NSStringFromClass([view class]), NSStringFromCGRect(view.frame));
		}
		[self dumpView: view i: i + 1];
		e++;
	}
}

@end


text:
<?php
namespace Tqdev\PhpCrudApi\Middleware;

use Tqdev\PhpCrudApi\Column\ReflectionService;
use Tqdev\PhpCrudApi\Controller\Responder;
use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
use Tqdev\PhpCrudApi\Middleware\Router\Router;
use Tqdev\PhpCrudApi\Record\ErrorCode;
use Tqdev\PhpCrudApi\Record\RequestUtils;
use Tqdev\PhpCrudApi\Request;
use Tqdev\PhpCrudApi\Response;

class PageLimitsMiddleware extends Middleware
{
    private $reflection;

    public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
    {
        parent::__construct($router, $responder, $properties);
        $this->reflection = $reflection;
        $this->utils = new RequestUtils($reflection);
    }

    public function handle(Request $request): Response
    {
        $operation = $this->utils->getOperation($request);
        if ($operation == 'list') {
            $params = $request->getParams();
            $maxPage = (int) $this->getProperty('pages', '100');
            if (isset($params['page']) && $params['page'] && $maxPage > 0) {
                if (strpos($params['page'][0], ',') === false) {
                    $page = $params['page'][0];
                } else {
                    list($page, $size) = explode(',', $params['page'][0], 2);
                }
                if ($page > $maxPage) {
                    return $this->responder->error(ErrorCode::PAGINATION_FORBIDDEN, '');
                }
            }
            $maxSize = (int) $this->getProperty('records', '1000');
            if (!isset($params['size']) || !$params['size'] && $maxSize > 0) {
                $params['size'] = array($maxSize);
            } else {
                $params['size'] = array(min($params['size'][0], $maxSize));
            }
            $request->setParams($params);
        }
        return $this->next->handle($request);
    }
}


text:
#region License
// The MIT License (MIT)
//
// Copyright (c) 2017 João Simões
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#endregion

namespace SimpleSoft.Database.Migrator
{
    /// <summary>
    /// Normalizes names by only making a <see cref="string.Trim()"/>
    /// transformation.
    /// </summary>
    public class TrimNamingNormalizer : INamingNormalizer
    {
        /// <inheritdoc />
        public string Normalize(string name)
        {
            return name == null
                ? null
                : (string.IsNullOrWhiteSpace(name)
                    ? string.Empty
                    : name.Trim());
        }
    }

    /// <summary>
    /// Normalizes names by only making a <see cref="string.Trim()"/>
    /// transformation.
    /// </summary>
    /// <typeparam name="TContext">The context type</typeparam>
    public class TrimNamingNormalizer<TContext> : TrimNamingNormalizer, INamingNormalizer<TContext>
        where TContext : IMigrationContext
    {

    }
}


text:
/* ----------------------------------------------------------------------
 * Universidad Nacional de Costa Rica
 * Facultad de Ciencias Exactas y Naturales
 * Escuela de Informática
 * EIF400 Paradigmas de Programación
 * Proyecto programado II
 * Profesor: Dr.Carlos Loría-Sáenz
 * Estudiantes:
 *	Carlos Arroyo Villalobos
 *	Jean Carlo Campos Madrigal
 *      Andrés Navarro Durán
 *	Karina Rivera Solano
 *	Claudio Umaña Arías
 * Octubre,2016
 * ---------------------------------------------------------------------*/
package eightBit.asm;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;

public class AsmDataBlock implements AsmAst {

    AsmId nameFunc;
    List<AsmData> data = new ArrayList<>();

    public AsmDataBlock(String name) {
        nameFunc = new AsmId("." + name + "_data");
    }

    public boolean isName(String name) {
        return nameFunc.getValue().equals("." + name + "_data");
    }

    public AsmDataBlock add(AsmData dat) {
        data.add(dat);
        return this;
    }

    @Override
    public AST getType() {
        return AST.DATABLOCK;
    }

    @Override
    public void genCode(PrintStream out) {
        nameFunc.genCode(out);
        out.print(":\n");
        data.stream().forEach(dat -> dat.genCode(out));
        out.print("\n");
    }

}