text:
#include <kernel/static_ta.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <tee/tee_fs_key_manager.h>
#include <trace.h>

#define TA_NAME		"tee_fs_key_manager_tests.ta"

#define CMD_SELF_TESTS	0

#define ENC_FS_KEY_MANAGER_TEST_UUID \
		{ 0x17E5E280, 0xD12E, 0x11E4,  \
		{ 0xA4, 0x1A, 0x00, 0x02, 0xA5, 0xD5, 0xC5, 0x1B } }

#define DUMP_BUF_MAX	256

static uint8_t test_data[] = {
	0x00, 0x6E, 0x04, 0x57, 0x08, 0xFB, 0x71, 0x96,
	0x00, 0x2E, 0x55, 0x3D, 0x02, 0xC3, 0xA6, 0x92,
	0x00, 0xC3, 0xEF, 0x8A, 0xB2, 0x34, 0x53, 0xE6,
	0x00, 0x74, 0x9C, 0xD6, 0x36, 0xE7, 0xA8, 0x00
};

static char *print_buf(char *buf, size_t *remain_size, const char *fmt, ...)
	__attribute__((__format__(__printf__, 3, 4)));

static char *print_buf(char *buf, size_t *remain_size, const char *fmt, ...)
{
	va_list ap;
	size_t len;

	va_start(ap, fmt);
	len = vsnprintf(buf, *remain_size, fmt, ap);
	buf += len;
	*remain_size -= len;
	va_end(ap);
	return buf;
}

static void dump_hex(char *buf, size_t *remain_size, uint8_t *input_buf,
		size_t input_size)
{
	size_t i;

	for (i = 0; i < input_size; i++)
		buf = print_buf(buf, remain_size, "%02X ", input_buf[i]);
}

static void print_hex(uint8_t *input_buf, size_t input_size)
{
	char buf[DUMP_BUF_MAX];
	size_t remain = sizeof(buf);

	dump_hex(buf, &remain, input_buf, input_size);
	DMSG("%s", buf);
}

/*
 * Trusted Application Entry Points
 */

static TEE_Result create_ta(void)
{
	DMSG("create entry point for static ta \"%s\"", TA_NAME);
	return TEE_SUCCESS;
}

static void destroy_ta(void)
{
	DMSG("destroy entry point for static ta \"%s\"", TA_NAME);
}

static TEE_Result open_session(uint32_t nParamTypes __unused,
		TEE_Param pParams[4] __unused, void **ppSessionContext __unused)
{
	DMSG("open entry point for static ta \"%s\"", TA_NAME);
	return TEE_SUCCESS;
}

static void close_session(void *pSessionContext __unused)
{
	DMSG("close entry point for static ta \"%s\"", TA_NAME);
}

static TEE_Result test_file_decrypt_with_invalid_content(void)
{
	TEE_Result res = TEE_SUCCESS;
	size_t header_size;
	size_t encrypt_data_out_size;
	uint8_t *encrypt_data_out = NULL;
	size_t decrypt_data_out_size;
	uint8_t *decrypt_data_out = NULL;
	uint8_t tmp_byte;
	uint8_t encrypted_fek[TEE_FS_KM_FEK_SIZE];

	DMSG("Start");

	/* data encryption */
	header_size = tee_fs_get_header_size(META_FILE);

	encrypt_data_out_size = header_size + sizeof(test_data);
	encrypt_data_out = malloc(encrypt_data_out_size);
	if (!encrypt_data_out) {
		EMSG("malloc for encrypt data buffer failed");
		res = TEE_ERROR_OUT_OF_MEMORY;
		goto exit;
	}

	res = tee_fs_encrypt_file(META_FILE,
			test_data, sizeof(test_data),
			encrypt_data_out, &encrypt_data_out_size,
			encrypted_fek);
	if (res != TEE_SUCCESS) {
		EMSG("file encryption failed");
		goto exit;
	}

	/* data decryption */
	decrypt_data_out_size = sizeof(test_data);
	decrypt_data_out = malloc(decrypt_data_out_size);
	if (!decrypt_data_out) {
		EMSG("malloc for decrypt data buffer failed");
		res = TEE_ERROR_OUT_OF_MEMORY;
		goto exit;
	}

	/* case1: data decryption with modified encrypted_key */
	tmp_byte = *(encrypt_data_out + 4);
	*(encrypt_data_out + 4) = ~tmp_byte;

	DMSG("case1: decryption with modified encrypted FEK");

	res = tee_fs_decrypt_file(META_FILE,
			encrypt_data_out, encrypt_data_out_size,
			decrypt_data_out, &decrypt_data_out_size,
			encrypted_fek);
	if (res == TEE_ERROR_MAC_INVALID) {
		DMSG("case1: passed, return code=%x", res);
	} else {
		EMSG("case1: failed, return code=%x", res);
		res = TEE_ERROR_GENERIC;
		goto exit;
	}

	*(encrypt_data_out + 4) = tmp_byte;

	/* case2: data decryption with modified iv */
	tmp_byte = *(encrypt_data_out + 20);
	*(encrypt_data_out + 20) = ~tmp_byte;

	DMSG("case2: decryption with modified IV");

	res = tee_fs_decrypt_file(META_FILE,
			encrypt_data_out, encrypt_data_out_size,
			decrypt_data_out, &decrypt_data_out_size,
			encrypted_fek);
	if (res == TEE_ERROR_MAC_INVALID) {
		DMSG("case2: passed, return code=%x", res);
	} else {
		EMSG("case2: failed, return code=%x", res);
		res = TEE_ERROR_GENERIC;
		goto exit;
	}

	*(encrypt_data_out + 20) = tmp_byte;

	/* case3: data decryption with modified cipher text */
	tmp_byte = *(encrypt_data_out + encrypt_data_out_size - 5);
	*(encrypt_data_out + encrypt_data_out_size - 5) = ~tmp_byte;

	DMSG("case3: decryption with modified cipher text");

	res = tee_fs_decrypt_file(META_FILE,
			encrypt_data_out, encrypt_data_out_size,
			decrypt_data_out, &decrypt_data_out_size,
			encrypted_fek);
	if (res == TEE_ERROR_MAC_INVALID) {
		DMSG("case3: passed, return code=%x", res);
	} else {
		EMSG("case3: failed, return code=%x", res);
		res = TEE_ERROR_GENERIC;
		goto exit;
	}

	*(encrypt_data_out + encrypt_data_out_size - 5) = tmp_byte;

	/* case4: data decryption with shorter cipher text length */
	DMSG("case4: decryption with shorter cipher text length");

	res = tee_fs_decrypt_file(META_FILE,
			encrypt_data_out, encrypt_data_out_size - 1,
			decrypt_data_out, &decrypt_data_out_size,
			encrypted_fek);
	if (res == TEE_ERROR_MAC_INVALID) {
		DMSG("case4: passed, return code=%x", res);
	} else {
		EMSG("case4: failed, return code=%x", res);
		res = TEE_ERROR_GENERIC;
		goto exit;
	}

	/* case5: data decryption with shorter plain text buffer */
	decrypt_data_out_size = sizeof(test_data) - 1;

	DMSG("case5: decryption with shorter plain text buffer");

	res = tee_fs_decrypt_file(META_FILE,
			encrypt_data_out, encrypt_data_out_size,
			decrypt_data_out, &decrypt_data_out_size,
			encrypted_fek);
	if (res == TEE_ERROR_SHORT_BUFFER) {
		DMSG("case5: passed, return code=%x", res);
	} else {
		EMSG("case5: failed, return code=%x", res);
		res = TEE_ERROR_GENERIC;
		goto exit;
	}

	decrypt_data_out_size = encrypt_data_out_size;

	/* data decryption with correct encrypted data */
	DMSG("good path test - decryption with correct data");

	res = tee_fs_decrypt_file(META_FILE,
			encrypt_data_out, encrypt_data_out_size,
			decrypt_data_out, &decrypt_data_out_size,
			encrypted_fek);
	if (res != TEE_SUCCESS) {
		EMSG("failed to decrypted data, return code=%x", res);
		goto exit;
	}

	/* data comparison */
	if (memcmp(test_data, decrypt_data_out, sizeof(test_data)) != 0) {
		EMSG("decrypted data doest not correct");
		res = TEE_ERROR_GENERIC;
	} else {
		DMSG("good path test - passed");
	}

exit:
	if (encrypt_data_out != NULL)
		free(encrypt_data_out);

	if (decrypt_data_out != NULL)
		free(decrypt_data_out);

	DMSG("Finish");

	return res;
}

static TEE_Result test_file_decrypt_success(void)
{
	TEE_Result res = TEE_SUCCESS;
	size_t header_size;
	size_t encrypt_data_out_size;
	uint8_t *encrypt_data_out = NULL;
	size_t decrypt_data_out_size;
	uint8_t *decrypt_data_out = NULL;
	uint8_t encrypted_fek[TEE_FS_KM_FEK_SIZE];

	DMSG("Start");

	res = tee_fs_generate_fek(encrypted_fek, TEE_FS_KM_FEK_SIZE);
	if (res != TEE_SUCCESS)
		goto exit;

	/* data encryption */
	header_size = tee_fs_get_header_size(META_FILE);

	encrypt_data_out_size = header_size + sizeof(test_data);
	encrypt_data_out = malloc(encrypt_data_out_size);
	if (!encrypt_data_out) {
		EMSG("malloc for encrypt data buffer failed");
		res = TEE_ERROR_OUT_OF_MEMORY;
		goto exit;
	}

	res = tee_fs_encrypt_file(META_FILE,
			test_data, sizeof(test_data),
			encrypt_data_out, &encrypt_data_out_size,
			encrypted_fek);
	if (res != TEE_SUCCESS) {
		EMSG("file encryption failed");
		goto exit;
	}

	/* data decryption */
	decrypt_data_out_size = sizeof(test_data);
	decrypt_data_out = malloc(decrypt_data_out_size);
	if (!decrypt_data_out) {
		EMSG("malloc for decrypt data buffer failed");
		res = TEE_ERROR_OUT_OF_MEMORY;
		goto exit;
	}

	res = tee_fs_decrypt_file(META_FILE,
			encrypt_data_out, encrypt_data_out_size,
			decrypt_data_out, &decrypt_data_out_size,
			encrypted_fek);
	if (res != TEE_SUCCESS)
		goto exit;

	/* data comparison */
	if (memcmp(test_data, decrypt_data_out, sizeof(test_data)) != 0) {
		EMSG("Data compare failed");
		res = TEE_ERROR_GENERIC;
	}

exit:
	/* dump data for debug */
	if (res != TEE_SUCCESS)
		DMSG("return code = %x", res);
	else {
		DMSG("Test Data (%zu bytes)", sizeof(test_data));
		print_hex(test_data, sizeof(test_data));
		DMSG("Encrypted Data (%zu bytes)", encrypt_data_out_size);
		print_hex(encrypt_data_out, encrypt_data_out_size);
		DMSG("Decrypted Data (%zu bytes)", decrypt_data_out_size);
		print_hex(decrypt_data_out, decrypt_data_out_size);
	}

	if (encrypt_data_out != NULL)
		free(encrypt_data_out);

	if (decrypt_data_out != NULL)
		free(decrypt_data_out);

	DMSG("Finish");

	return res;
}

static TEE_Result self_tests(
			uint32_t nParamTypes __unused,
			TEE_Param pParams[TEE_NUM_PARAMS] __unused)
{
	TEE_Result res;

	res = test_file_decrypt_success();
	if (res != TEE_SUCCESS)
		return res;

	res = test_file_decrypt_with_invalid_content();
	if (res != TEE_SUCCESS)
		return res;

	return TEE_SUCCESS;
}

static TEE_Result invoke_command(void *pSessionContext __unused,
		uint32_t nCommandID, uint32_t nParamTypes, TEE_Param pParams[4])
{
	DMSG("command entry point for static ta \"%s\"", TA_NAME);

	switch (nCommandID) {
	case CMD_SELF_TESTS:
		return self_tests(nParamTypes, pParams);
	default:
		break;
	}
	return TEE_ERROR_BAD_PARAMETERS;
}

static_ta_register(.uuid = ENC_FS_KEY_MANAGER_TEST_UUID, .name = TA_NAME,
		   .create_entry_point = create_ta,
		   .destroy_entry_point = destroy_ta,
		   .open_session_entry_point = open_session,
		   .close_session_entry_point = close_session,
		   .invoke_command_entry_point = invoke_command);


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Metasphaeria depressula Sacc. & Roum.

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
/**
	_onyx.DatePicker_ is a group of onyx.Picker
	controls displaying the current date. The user may change the _day_,
	_month_, and _year_ values.

	By default, _DatePicker_ tries to determine the current locale and use its
	rules to format the date (including the month name). In order to do this
	successfully, the _ilib_ library must be loaded; if it is not loaded, the
	control defaults to using standard U.S. date format.

	The _day_ field is automatically populated with the proper number of days
	for the selected month and year.
 */
enyo.kind({
	name: "onyx.DatePicker",
	classes: "onyx-toolbar-inline",
	published: {
		//* If true, control is shown as disabled, and user can't select new values
		disabled: false,
		/**
			Current locale used for formatting. Can be set after control
			creation, in which case the control will be updated to reflect the
			new value.
		*/
		locale: "en-US",
		//* If true, the day field is hidden
		dayHidden: false,
		//* If true, the month field is hidden
		monthHidden: false,
		//* If true, the year field is hidden
		yearHidden: false,
		//* Optional minimum year value
		minYear: 1900,
		//* Optional maximum year value
		maxYear: 2099,
		/**
			The current Date object. When a Date object is passed to _setValue_,
			the control is updated to reflect the new value. _getValue_ returns
			a Date object.
		*/
		value: null
	},
	events: {
		/**
			Fires when one of the DatePicker's fields is selected.

			_inEvent.name_ contains the name of the DatePicker that generated
			the event.

			_inEvent.value_ contains the current Date value of the control.
		*/
		onSelect: ""
	},
	create: function() {
		this.inherited(arguments);
		if (ilib) {
			this.locale = ilib.getLocale();
		}
		this.initDefaults();
	},
	initDefaults: function() {
		var months;
		//Attempt to use the ilib library if it is loaded
		if (ilib) {
			months = [];
			this._tf = new ilib.DateFmt({locale:this.locale, timezone: "local"});
			months = this._tf.getMonthsOfYear({length: 'long'});
		}
		// Fall back to en_US as default
		else {
			months = [undefined, "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
			this.localeInfo.getMonthsOfYear = function() {
				return months;
			};
		}

		// use iLib's getTemplate as that returns locale-specific ordering
		this.setupPickers(this._tf ? this._tf.getTemplate() : 'mdy');

		this.dayHiddenChanged();
		this.monthHiddenChanged();
		this.yearHiddenChanged();

		//Fill month, year & day pickers with values
		var d = this.value = this.value || new Date();
		for (var i=0,m; (m=months[i + 1]); i++) {
			this.$.monthPicker.createComponent({content: m, value:i, active: i==d.getMonth()});
		}

		var y = d.getFullYear();
		this.$.yearPicker.setSelected(y-this.minYear);

		for (i=1; i<=this.monthLength(d.getYear(), d.getMonth()); i++) {
			this.$.dayPicker.createComponent({content:i, value:i, active: i==d.getDate()});
		}
	},
	monthLength: function(inYear, inMonth) {
		// determine number of days in a particular month/year
		return 32 - new Date(inYear, inMonth, 32).getDate();
	},
	setupYear: function(inSender, inEvent) {
		this.$.year.setContent(this.minYear+inEvent.index);
		return true;
	},
	setupPickers: function(ordering) {
		var orderingArr = ordering.split("");
		var o,f,l;
		var createdYear = false, createdMonth = false, createdDay = false;
		for(f = 0, l = orderingArr.length; f < l; f++) {
			o = orderingArr[f];
			switch (o.toLowerCase()){
			case 'd':
				if (!createdDay) {
					this.createDay();
					createdDay = true;
				}
				break;
			case 'm':
				if (!createdMonth) {
					this.createMonth();
					createdMonth = true;
				}
				break;
			case 'y':
				if (!createdYear) {
					this.createYear();
					createdYear = true;
				}
				break;
			default:
				break;
			}
		}
	},
	createYear: function() {
		var yearCount = this.maxYear - this.minYear;
		this.createComponent(
			{kind: "onyx.PickerDecorator", onSelect: "updateYear", components: [
				{classes:"onyx-datepicker-year", name: "yearPickerButton",  disabled: this.disabled},
				{name: "yearPicker", kind: "onyx.FlyweightPicker", count: ++yearCount, onSetupItem: "setupYear", components: [
					{name: "year"}
				]}
			]}
		);
	},
	createMonth: function() {
		this.createComponent(
			{kind: "onyx.PickerDecorator", onSelect: "updateMonth", components: [
				{classes:"onyx-datepicker-month", name: "monthPickerButton",  disabled: this.disabled},
				{name: "monthPicker", kind: "onyx.Picker"}
			]}
		);
	},
	createDay: function() {
		this.createComponent(
			{kind: "onyx.PickerDecorator", onSelect: "updateDay", components: [
				{classes:"onyx-datepicker-day", name: "dayPickerButton",  disabled: this.disabled},
				{name: "dayPicker", kind: "onyx.Picker"}
			]}
		);
	},
	localeChanged: function() {
		this.refresh();
	},
	dayHiddenChanged: function() {
		this.$.dayPicker.getParent().setShowing(this.dayHidden ? false : true);
	},
	monthHiddenChanged: function() {
		this.$.monthPicker.getParent().setShowing(this.monthHidden ? false : true);
	},
	yearHiddenChanged: function() {
		this.$.yearPicker.getParent().setShowing(this.yearHidden ? false : true);
	},
	minYearChanged: function() {
		this.refresh();
	},
	maxYearChanged: function() {
		this.refresh();
	},
	valueChanged: function(){
		this.refresh();
	},
	disabledChanged: function() {
		this.$.yearPickerButton.setDisabled(this.disabled);
		this.$.monthPickerButton.setDisabled(this.disabled);
		this.$.dayPickerButton.setDisabled(this.disabled);
	},
	updateDay: function(inSender, inEvent){
		var date = this.calcDate(this.value.getFullYear(),
								this.value.getMonth(),
								inEvent.selected.value);
		this.doSelect({name:this.name, value:date});
		this.setValue(date);
		return true;
	},
	updateMonth: function(inSender, inEvent){
		var date = this.calcDate(this.value.getFullYear(),
								inEvent.selected.value,
								this.value.getDate());
		this.doSelect({name:this.name, value:date});
		this.setValue(date);
		return true;
	},
	updateYear: function(inSender, inEvent){
		//if the node wasn't found (issue around FlyWeightRepeater/Picker) don't update the picker
		if (inEvent.originator.selected != -1) {
			var date = this.calcDate(this.minYear + inEvent.originator.selected,
									this.value.getMonth(),
									this.value.getDate());
			this.doSelect({name:this.name, value:date});
			this.setValue(date);
		}
		return true;
	},
	calcDate: function(year, month, day){
		return new Date(year,month,day,
						this.value.getHours(),
						this.value.getMinutes(),
						this.value.getSeconds(),
						this.value.getMilliseconds());
	},
	refresh: function(){
		this.destroyClientControls();
		this.initDefaults();
		this.render();
	}
});


text:
require 'ads_common/savon_service'
require 'dfp_api/v201411/publisher_query_language_service_registry'

module DfpApi; module V201411; module PublisherQueryLanguageService
  class PublisherQueryLanguageService < AdsCommon::SavonService
    def initialize(config, endpoint)
      namespace = 'https://www.google.com/apis/ads/publisher/v201411'
      super(config, endpoint, namespace, :v201411)
    end

    def select(*args, &block)
      return execute_action('select', args, &block)
    end

    def select_to_xml(*args)
      return get_soap_xml('select', args)
    end

    private

    def get_service_registry()
      return PublisherQueryLanguageServiceRegistry
    end

    def get_module()
      return DfpApi::V201411::PublisherQueryLanguageService
    end
  end
end; end; end


text:
@implementation MapTypeViewController

@synthesize mapTypeControl = _mapTypeControl;
@synthesize delegate = _delegate;
@synthesize mapType = _mapType;

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.mapTypeControl.selectedSegmentIndex = self.mapType;
}

- (IBAction)choseMapType:(id)sender {
    UISegmentedControl *control = (UISegmentedControl *)sender;
    NSNumber *mapType;
    switch (control.selectedSegmentIndex) {
        case MKMapTypeSatellite:
            mapType = [NSNumber numberWithInt:MKMapTypeSatellite];
            break;
        case MKMapTypeHybrid:
            mapType = [NSNumber numberWithInt:MKMapTypeHybrid];
            break;
        default:
            mapType = [NSNumber numberWithInt:MKMapTypeStandard];
            break;
    }
    if (self.delegate && [self.delegate respondsToSelector:@selector(mapTypeControllerDidChange:mapType:)]) {
        [self.delegate performSelector:@selector(mapTypeControllerDidChange:mapType:)
                            withObject:self
                            withObject:mapType];
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}
@end


text:
class RESO::ChangeType < RESO::Enumeration
end


text:
**Documentation**

* Updated demo to support private registries other than the official registry #528.
* General updates to documentation.
* Changed ELB health check thresholds in example CloudFormation stack to follow AWS defaults.

**Features**

* Implemented support for attached one-off commands #568.
* Added support for GitHub Deployments #602.
* Added support for deploying a docker image to a specific app #622.
* Added support for `emp info` command #619.
* Added pagination support for `/apps/{app}/releases` endpoint #591.

**Bugs**

* Fixes a bug that caused containers launched by one-off tasks to stay around if the client disconnected. #589.
* Fixed an issue where deploying an app to an AWS account with no ELB's would cause an infinite loop #623.
* Fixed a bug that prevented scaling a processes memory to more than 1GB #593.

## 0.9.0 (2015-06-16)

Initial public release


text:
layout: cs_course
---
{% capture class_name %}{{ page.categories[0] }}{% endcapture %}
{% if page.categories.size > 2 %}
  {% capture topic %}{{ page.categories[2] }}{% endcapture %}
  {% capture semester %}{{ page.categories[1] }}{% endcapture %}
{% else %}
  {% capture topic %}{{ page.categories[1] }}{% endcapture %}
  {% capture semester %}base{% endcapture %}
{% endif %}

{{ page.title }}

Notes:

{% if site.custom_posts[class_name][semester][topic].notes.size == 0 %}

    Looks like there currently aren't any notes (yet) about {{ page.name }}...if you'd like to see some, let me know.

{% else %}

  {% for cs_post in site.custom_posts[class_name][semester][topic].notes %}

{{ cs_post.name }}

    {{ cs_post.content | summarize }}
    (Read More!)
  {% endfor %}

{% endif %}

Practice Problems:

{% if site.custom_posts[class_name][semester][topic].problems.size == 0 %}

    Looks like there currently aren't any practice problems (yet) about {{ page.name }}...if you'd like to see some, let me know.

{% else %}

    Below are a list of practice problems, test what you've learned!

  {% for cs_post in site.custom_posts[class_name][semester][topic].problems %}

{{ cs_post.name }} {% if cs_post.type == 'Challenge' %} {{ cs_post.type | titleize }}{% endif %}

  {% endfor %}

{% endif %}


text:
package fr.javatronic.damapping.test.mapperreferences;

import fr.javatronic.damapping.test.AbstractMapperTest;

import org.testng.annotations.Test;

/**
 * ClassDTest -
 *
 * @author lesaint
 */
public class ClassDTest extends AbstractMapperTest {

  public ClassDTest() {
    super(ClassD.class);
  }

  @Test
  public void check_generated_mapper_file() throws Exception {
    testUtil.checkGeneratedFile(getClass(), "Mapper");
  }

  @Test
  public void check_generated_mapperImpl_file() throws Exception {
    testUtil.checkGeneratedFile(getClass(), "MapperImpl");
  }

}


text:
package android.util;

import java.util.Collection;
import java.util.Map;
import java.util.Set;

public class ArrayMap<K, V> implements Map<K, V>
{
    public ArrayMap(){}
    public ArrayMap(ArrayMap<K, V> p0){}
    public ArrayMap(int p0){}
    public Collection<V> values(){ return null; }
    public K keyAt(int p0){ return null; }
    public Set<K> keySet(){ return null; }
    public Set<Map.Entry<K, V>> entrySet(){ return null; }
    public String toString(){ return null; }
    public V get(Object p0){ return null; }
    public V put(K p0, V p1){ return null; }
    public V remove(Object p0){ return null; }
    public V removeAt(int p0){ return null; }
    public V setValueAt(int p0, V p1){ return null; }
    public V valueAt(int p0){ return null; }
    public boolean containsAll(Collection<? extends Object> p0){ return false; }
    public boolean containsKey(Object p0){ return false; }
    public boolean containsValue(Object p0){ return false; }
    public boolean equals(Object p0){ return false; }
    public boolean isEmpty(){ return false; }
    public boolean removeAll(Collection<? extends Object> p0){ return false; }
    public boolean retainAll(Collection<? extends Object> p0){ return false; }
    public int hashCode(){ return 0; }
    public int indexOfKey(Object p0){ return 0; }
    public int indexOfValue(Object p0){ return 0; }
    public int size(){ return 0; }
    public void clear(){}
    public void ensureCapacity(int p0){}
    public void putAll(ArrayMap<? extends K, ? extends V> p0){}
    public void putAll(Map<? extends K, ? extends V> p0){}
}


text:
"""Google Calendar Events object model.

Events object model for Google Calendar API responses.
"""
from appletea.exceptions import HTTPError
from appletea.utils import UnicodeMixin

class GCalendarEvents(UnicodeMixin):
    """GCalendarEvents data object.

    Google Calendar Events data object includes a list of events information.
    """
    def __init__(self, json):
        self._raise_for_status(json.get('error', ''))
        self.json = json
        self.events = [GEventData(item) for item in json.get('items', [])]

    def _raise_for_status(self, e):
        if e:
            status_code = e.get('code', None)
            reason = e.get('message', '')

            if 400 <= status_code < 500:
                http_error_msg = '%s Client Error: %s' % (status_code, reason)
            elif 500 <= status_code < 600:
                http_error_msg = '%s Server Error: %s' % (status_code, reason)
            else:
                http_error_msg = 'Undefined Error'

            raise HTTPError(http_error_msg)

    def __unicode__(self):
        return ('<GCalendarEvents instance with %d events>' % len(self.events))

class GEventData(UnicodeMixin):
    """GEventData data object.

    An event data object represents an Event Resource on a particular calendar.
    Such objects contain various properties. More information can be found at:

    https://developers.google.com/google-apps/calendar/v3/reference/events#resource-representations
    """
    def __init__(self, d={}, supitem=''):
        self.supitem = supitem
        self.d = d

    def __getattr__(self, name):
        try:
            v = self.d[name]
            if isinstance(v, dict):
                return GEventData(v, name)
            elif isinstance(v, list):
                return [GEventData(x, name) for x in v]
            else:
                return v
        except KeyError:
            raise ValueError(
                'Property "%s" not valid or is not available for event'
                ' %s.' % (
                    name,
                    'item "%s"' % self.supitem if self.supitem else 'item'))

    def __unicode__(self):
        return ('<GEventData instance: %s>' % self.supitem)


text:
.class Lcom/sprint/internal/htcsprintservice/IHtcSprintService$Stub$Proxy;
.super Ljava/lang/Object;
.source "IHtcSprintService.java"

# interfaces
.implements Lcom/sprint/internal/htcsprintservice/IHtcSprintService;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/sprint/internal/htcsprintservice/IHtcSprintService$Stub;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0xa
    name = "Proxy"
.end annotation

# instance fields
.field private mRemote:Landroid/os/IBinder;

# direct methods
.method constructor <init>(Landroid/os/IBinder;)V
    .locals 0
    .parameter "remote"

    .prologue
    .line 69
    invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V

    .line 70
    iput-object p1, p0, Lcom/sprint/internal/htcsprintservice/IHtcSprintService$Stub$Proxy;->mRemote:Landroid/os/IBinder;

    .line 71
    return-void
.end method

# virtual methods
.method public asBinder()Landroid/os/IBinder;
    .locals 1

    .prologue
    .line 74
    iget-object v0, p0, Lcom/sprint/internal/htcsprintservice/IHtcSprintService$Stub$Proxy;->mRemote:Landroid/os/IBinder;

    return-object v0
.end method

.method public getInterfaceDescriptor()Ljava/lang/String;
    .locals 1

    .prologue
    .line 78
    const-string v0, "com.sprint.internal.htcsprintservice.IHtcSprintService"

    return-object v0
.end method

.method public getString(I)Ljava/lang/String;
    .locals 6
    .parameter "id"
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    .prologue
    .line 96
    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v0

    .line 97
    .local v0, _data:Landroid/os/Parcel;
    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v1

    .line 100
    .local v1, _reply:Landroid/os/Parcel;
    :try_start_0
    const-string v3, "com.sprint.internal.htcsprintservice.IHtcSprintService"

    invoke-virtual {v0, v3}, Landroid/os/Parcel;->writeInterfaceToken(Ljava/lang/String;)V

    .line 101
    invoke-virtual {v0, p1}, Landroid/os/Parcel;->writeInt(I)V

    .line 102
    iget-object v3, p0, Lcom/sprint/internal/htcsprintservice/IHtcSprintService$Stub$Proxy;->mRemote:Landroid/os/IBinder;

    const/4 v4, 0x2

    const/4 v5, 0x0

    invoke-interface {v3, v4, v0, v1, v5}, Landroid/os/IBinder;->transact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z

    .line 103
    invoke-virtual {v1}, Landroid/os/Parcel;->readException()V

    .line 104
    invoke-virtual {v1}, Landroid/os/Parcel;->readString()Ljava/lang/String;
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    move-result-object v2

    .line 107
    .local v2, _result:Ljava/lang/String;
    invoke-virtual {v1}, Landroid/os/Parcel;->recycle()V

    .line 108
    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    .line 110
    return-object v2

    .line 107
    .end local v2           #_result:Ljava/lang/String;
    :catchall_0
    move-exception v3

    invoke-virtual {v1}, Landroid/os/Parcel;->recycle()V

    .line 108
    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    throw v3
.end method

.method public reboot()V
    .locals 5
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    .prologue
    .line 82
    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v0

    .line 83
    .local v0, _data:Landroid/os/Parcel;
    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v1

    .line 85
    .local v1, _reply:Landroid/os/Parcel;
    :try_start_0
    const-string v2, "com.sprint.internal.htcsprintservice.IHtcSprintService"

    invoke-virtual {v0, v2}, Landroid/os/Parcel;->writeInterfaceToken(Ljava/lang/String;)V

    .line 86
    iget-object v2, p0, Lcom/sprint/internal/htcsprintservice/IHtcSprintService$Stub$Proxy;->mRemote:Landroid/os/IBinder;

    const/4 v3, 0x1

    const/4 v4, 0x0

    invoke-interface {v2, v3, v0, v1, v4}, Landroid/os/IBinder;->transact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z

    .line 87
    invoke-virtual {v1}, Landroid/os/Parcel;->readException()V
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    .line 90
    invoke-virtual {v1}, Landroid/os/Parcel;->recycle()V

    .line 91
    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    .line 93
    return-void

    .line 90
    :catchall_0
    move-exception v2

    invoke-virtual {v1}, Landroid/os/Parcel;->recycle()V

    .line 91
    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    throw v2
.end method


text:
<?php

namespace CurrencyCloud\EntryPoint;

use CurrencyCloud\Model\Beneficiaries;
use CurrencyCloud\Model\Beneficiary;
use CurrencyCloud\Model\Pagination;
use DateTime;
use stdClass;

class BeneficiariesEntryPoint extends AbstractEntityEntryPoint
{

    /**
     * @param Beneficiary $beneficiary
     * @param null|string $onBehalfOf
     *
     * @return Beneficiary
     */
    public function validate(Beneficiary $beneficiary, $onBehalfOf = null)
    {
        $response = $this->request(
            'POST',
            'beneficiaries/validate',
            [],
            $this->convertBeneficiaryToRequest(
                $beneficiary,
                true,
                $onBehalfOf
            )
        );
        return $this->createBeneficiaryFromResponse($response, true);
    }

    /**
     * @param Beneficiary $beneficiary
     * @param null|string $onBehalfOf
     *
     * @return Beneficiary
     */
    public function create(Beneficiary $beneficiary, $onBehalfOf = null)
    {
        return $this->doCreate('beneficiaries/create', $beneficiary, function ($beneficiary) {
            return $this->convertBeneficiaryToRequest($beneficiary);
        }, function ($response) {
            return $this->createBeneficiaryFromResponse($response);
        }, $onBehalfOf);
    }

    /**
     * @param string $id
     * @param null $onBehalfOf
     *
     * @return Beneficiary
     */
    public function retrieve($id, $onBehalfOf = null)
    {
        return $this->doRetrieve(sprintf('beneficiaries/%s', $id), function ($response) {
            return $this->createBeneficiaryFromResponse($response);
        }, $onBehalfOf);
    }

    /**
     * @param Beneficiary $beneficiary
     * @param null $onBehalfOf
     *
     * @return Beneficiary
     */
    public function update(Beneficiary $beneficiary, $onBehalfOf = null)
    {
        return $this->doUpdate(sprintf(
            'beneficiaries/%s',
            $beneficiary->getId()
        ), $beneficiary, function ($entity, $onBehalfOf) {
            return $this->convertBeneficiaryToRequest($entity, $onBehalfOf, false, true);
        }, function ($response) {
            return $this->createBeneficiaryFromResponse($response);
        });
    }

    /**
     * @param Beneficiary|null $beneficiary
     * @param Pagination|null $pagination
     * @param null $onBehalfOf
     *
     * @return Beneficiaries
     */
    public function find(Beneficiary $beneficiary = null, Pagination $pagination = null, $onBehalfOf = null)
    {
        if (null === $beneficiary) {
            $beneficiary = new Beneficiary();
        }
        if (null === $pagination) {
            $pagination = new Pagination();
        }
        return $this->doFind('beneficiaries/find', $beneficiary, $pagination, function ($entity, $onBehalfOf) {
            return $this->convertBeneficiaryToRequest($entity, $onBehalfOf);
        }, function ($response) {
            return $this->createBeneficiaryFromResponse($response);
        }, function (array $entities, Pagination $pagination) {
            return new Beneficiaries($entities, $pagination);
        }, 'beneficiaries', $onBehalfOf);
    }

    /**
     * @param Beneficiary $beneficiary
     * @param null $onBehalfOf
     *
     * @return Beneficiary
     */
    public function delete(Beneficiary $beneficiary, $onBehalfOf = null)
    {
        return $this->doDelete(
            sprintf('beneficiaries/%s/delete', $beneficiary->getId()),
            $beneficiary,
            function ($response) {
                return $this->createBeneficiaryFromResponse($response);
            },
            $onBehalfOf
        );
    }

    /**
     * @param Beneficiary $beneficiary
     * @param bool $convertForValidate
     * @param bool $convertForUpdate
     *
     * @return array
     */
    protected function convertBeneficiaryToRequest(Beneficiary $beneficiary, $convertForValidate = false, $convertForUpdate = false)
	{
        $isDefaultBeneficiary = $beneficiary->isDefaultBeneficiary();
        $common = [
            'bank_country' => $beneficiary->getBankCountry(),
            'currency' => $beneficiary->getCurrency(),
            'beneficiary_country' => $beneficiary->getBeneficiaryCountry(),
            'account_number' => $beneficiary->getAccountNumber(),
            'routing_code_type_1' => $beneficiary->getRoutingCodeType1(),
            'routing_code_value_1' => $beneficiary->getRoutingCodeValue1(),
            'routing_code_type_2' => $beneficiary->getRoutingCodeType2(),
            'routing_code_value_2' => $beneficiary->getRoutingCodeValue2(),
            'bic_swift' => $beneficiary->getBicSwift(),
            'iban' => $beneficiary->getIban(),
            'bank_address' => $beneficiary->getBankAddress(),
            'bank_name' => $beneficiary->getBankName(),
            'default_beneficiary' => (null === $isDefaultBeneficiary) ? null :
                ($isDefaultBeneficiary ? 'true' : 'false'),
            'bank_account_type' => $beneficiary->getBankAccountType(),
            'beneficiary_entity_type' => $beneficiary->getBeneficiaryEntityType(),
            'beneficiary_company_name' => $beneficiary->getBeneficiaryCompanyName(),
            'beneficiary_address' => $beneficiary->getBeneficiaryAddress(),
            'beneficiary_first_name' => $beneficiary->getBeneficiaryFirstName(),
            'beneficiary_last_name' => $beneficiary->getBeneficiaryLastName(),
            'beneficiary_city' => $beneficiary->getBeneficiaryCity(),
            'beneficiary_postcode' => $beneficiary->getBeneficiaryPostCode(),
            'beneficiary_state_or_province' => $beneficiary->getBeneficiaryStateOrProvince(),
            'beneficiary_date_of_birth' => (null === $beneficiary->getBeneficiaryDateOfBirth()) ? null :
                $beneficiary->getBeneficiaryDateOfBirth()
                    ->format('Y-m-d'),
            'beneficiary_identification_type' => $beneficiary->getBeneficiaryIdentificationType(),
            'beneficiary_identification_value' => $beneficiary->getBeneficiaryIdentificationValue(),
            'payment_types' => $beneficiary->getPaymentTypes()
        ];

        if ($convertForValidate) {
            return $common;
        }

        $common += [
            'bank_account_holder_name' => $beneficiary->getBankAccountHolderName(),
            'name' => $beneficiary->getName(),
            'email' => $beneficiary->getEmail(),
            'beneficiary_external_reference' => $beneficiary->getBeneficiaryExternalReference()
        ];

        if ($convertForUpdate) {
            return $common;
        }

        return $common + [
            'creator_contact_id' => $beneficiary->getCreatorContactId()
        ];
    }

    /**
     * @param stdClass $response
     * @param bool $fromValidate
     *
     * @return Beneficiary
     */
    private function createBeneficiaryFromResponse(stdClass $response, $fromValidate = false)
    {
        $beneficiary = new Beneficiary();

        $beneficiary->setBankCountry($response->bank_country)
            ->setCurrency($response->currency)
            ->setBeneficiaryCountry($response->beneficiary_country)
            ->setPaymentTypes($response->payment_types)
            ->setBankName($response->bank_name)
            ->setBankAddress($response->bank_address)
            ->setAccountNumber($response->account_number)
            ->setIban($response->iban)
            ->setBicSwift($response->bic_swift)
            ->setBankAccountType($response->bank_account_type)
            ->setBeneficiaryAddress($response->beneficiary_address)
            ->setBeneficiaryEntityType($response->beneficiary_entity_type)
            ->setBeneficiaryCompanyName($response->beneficiary_company_name)
            ->setBeneficiaryFirstName($response->beneficiary_first_name)
            ->setBeneficiaryLastName($response->beneficiary_last_name)
            ->setBeneficiaryCity($response->beneficiary_city)
            ->setBeneficiaryPostcode($response->beneficiary_postcode)
            ->setBeneficiaryStateOrProvince($response->beneficiary_state_or_province)
            ->setBeneficiaryDateOfBirth(
                (null !== $response->beneficiary_date_of_birth) ? new DateTime($response->beneficiary_date_of_birth) :
                    null
            )
            ->setBeneficiaryIdentificationType($response->beneficiary_identification_type)
            ->setBeneficiaryIdentificationValue($response->beneficiary_identification_value)
            ->setRoutingCodeType1($response->routing_code_type_1)
            ->setRoutingCodeValue1($response->routing_code_value_1)
            ->setRoutingCodeType2($response->routing_code_type_2)
            ->setRoutingCodeValue2($response->routing_code_value_2);

        if (!$fromValidate) {
            $beneficiary->setName($response->name)
                ->setCreatorContactId($response->creator_contact_id)
                ->setEmail($response->email)
                ->setIsDefaultBeneficiary('true' === $response->default_beneficiary)
                ->setBankAccountHolderName($response->bank_account_holder_name)
                ->setCreatedAt(new DateTime($response->created_at))
                ->setUpdatedAt(new DateTime($response->updated_at))
                ->setBeneficiaryExternalReference($response->beneficiary_external_reference);
            $this->setIdProperty($beneficiary, $response->id);
        }

        return $beneficiary;
    }
}


text:
The aim of this file is to provide a first introduction to Spark in
the context of the Cloudera certification. During this guide both Scala
and Python would be used since both programming languages are required
during the certification.

## Table of contents

* Using Hive Context

## Using Hive Context

The first thing to do in order to access Hive tables from
Spark is to make Spark aware of Hive configuration. To do
so we will create a link in the Spark configuration directory
(`/etc/spark/conf/`) to the file `hive-site.xml` located
in the directory `/etc/hive/conf/`. This file contains
Hive configuration an allows spark to create a `sqlContext` based
on Hive.

If we now launch a spark-shell terminal we should see the following:

```
17/08/12 11:26:41 INFO repl.SparkILoop: Created sql context (with Hive support)..
```

We can now make queries on Hive table using spark:

```
sqlContext.sql("SELECT * FROM sqoop_import.departments").collect().foreach(println)

[2,Fitness]
[3,Footwear]
[4,Apparel]
[5,Golf]
[6,Outdoors]
[7,Fan Shop]
[10,New record]
[12,New record]
[8000,TESTING]
```

* We have used `sqlContext` to perform a SQL query on the sqoop_import Hive database.
* We then have collected the results using `collect`.
* Finally we have printed each row collected.

**Python version**:

```
sqlCtx.sql("SELECT * FROM sqoop_import.departments").collect()
```

When launching the pyspark shell it already comes with the
variable `sqlCtx` which is a SQL context for python. Another option
to create a SQL context would be:

```
from pyspark.sql import HiveContext
sqlContext = HiveContext(sc)
```


text:
package jFloatingPointConverter;

public class SinglePrecision {

    private double getDecimalValueOfMantissa(String input) {
        double decimalValueOMantissa = 0.0;
        char[] inputToCharArray = input.toCharArray();
        for (int k = 0; k < inputToCharArray.length-1; k++)
            if (inputToCharArray[k] == '1') decimalValueOMantissa = decimalValueOMantissa + Math.pow(2.0, -1.0*(k+1));
        return decimalValueOMantissa;
    }

    private String getStringBits(float input) {
        String returnString;
        if (Integer.toBinaryString(Float.floatToIntBits(input)).length() != 32) {
            char[] normalisedNumber32length = new char[32];
            int lackOf = 32 - Integer.toBinaryString(Float.floatToIntBits(input)).length();

            for (int k = 0; k < lackOf; k++)
                normalisedNumber32length[k] = '0';

            for (int k = lackOf; k < 32; k++)
                normalisedNumber32length[k] = Integer.toBinaryString(Float.floatToIntBits(input)).toCharArray()[k-lackOf];

            StringBuilder ssBuildString = new StringBuilder();
            for (char elem : normalisedNumber32length) ssBuildString.append(elem);
            returnString = ssBuildString.toString();
        } else returnString = Integer.toBinaryString(Float.floatToIntBits(input));
        return returnString;
    }

    public float getIBM32(float inputIBM32) {
        float returnFloat;
        char signIBM32 = getStringBits(inputIBM32).toCharArray()[0];

        StringBuilder sbExpIBM32 = new StringBuilder();
        for (int k = 1; k < 8; k++)
            sbExpIBM32.append(getStringBits(inputIBM32).toCharArray()[k]);

        String expIBM32 = sbExpIBM32.toString();

        StringBuilder sbMantissaIBM32 = new StringBuilder();
        for (int k = 1; k < 25; k++)
            sbMantissaIBM32.append(getStringBits(inputIBM32).toCharArray()[k+7]);

        String mantissaIBM32 = sbMantissaIBM32.toString();

        returnFloat = (float)(Math.pow(-1.0, (double)signIBM32) * Math.pow(16.0, (Integer.parseInt(expIBM32, 2) - 64)) * getDecimalValueOfMantissa(mantissaIBM32));
        return returnFloat;
    }

    //for checking input(IEEE754) -> output(IEEE754), input == output
    public float getIEEE754(float inputIEEE754) {
        float returnFloat;
        char signIEEE754 = getStringBits(inputIEEE754).toCharArray()[0];

        StringBuilder sbExpIEEE754 = new StringBuilder();
        for (int k = 1; k < 9; k++)
            sbExpIEEE754.append(getStringBits(inputIEEE754).toCharArray()[k]);

        String expIEEE754 = sbExpIEEE754.toString();

        StringBuilder sbMantissaIEEE754 = new StringBuilder();
        for (int k = 1; k < 24; k++)
            sbMantissaIEEE754.append(getStringBits(inputIEEE754).toCharArray()[k+8]);

        String mantissaIEEE754 = sbMantissaIEEE754.toString();

        returnFloat = (float)(Math.pow(-1.0, (double)signIEEE754) * Math.pow(2.0, (Integer.parseInt(expIEEE754, 2) - 127) ) * (1.0 + getDecimalValueOfMantissa(mantissaIEEE754)));
        return returnFloat;
    }
}


text:
package com.headwire.aem.tooling.intellij.action;

import com.headwire.aem.tooling.intellij.communication.ServerConnectionManager;
import com.headwire.aem.tooling.intellij.config.ServerConfiguration;
import com.headwire.aem.tooling.intellij.config.ServerConfigurationManager;
import com.headwire.aem.tooling.intellij.explorer.SlingServerTreeSelectionHandler;
import com.headwire.aem.tooling.intellij.ui.BuildSelectionDialog;
import com.headwire.aem.tooling.intellij.util.ComponentProvider;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;

/**
 * Created by Andreas Schaefer (Headwire.com) on 6/26/15.
 */
public class BuildConfigurationAction
    extends AbstractProjectAction
{
    public BuildConfigurationAction() {
        super("action.build.configuration");
    }

    @Override
    protected boolean isAsynchronous() {
        return false;
    }

    @Override
    protected void execute(@NotNull Project project, @NotNull DataContext dataContext, final ProgressHandler progressHandler) {
        SlingServerTreeSelectionHandler selectionHandler = getSelectionHandler(project);
        ServerConnectionManager serverConnectionManager = ComponentProvider.getComponent(project, ServerConnectionManager.class);
        ServerConfigurationManager configurationManager = ComponentProvider.getComponent(project, ServerConfigurationManager.class);
        if(selectionHandler != null && serverConnectionManager != null && configurationManager != null) {
            ServerConfiguration serverConfiguration = selectionHandler.getCurrentConfiguration();
            BuildSelectionDialog dialog = new BuildSelectionDialog(project, serverConfiguration);
            if(dialog.showAndGet()) {
                // Modules might have changed and so update the tree
                configurationManager.updateServerConfiguration(serverConfiguration);
            }
        }
    }

    @Override
    protected boolean isEnabled(@NotNull Project project, @NotNull DataContext dataContext) {
        ServerConnectionManager serverConnectionManager = ComponentProvider.getComponent(project, ServerConnectionManager.class);
        return serverConnectionManager != null && serverConnectionManager.isConfigurationSelected();
    }
}


text:
package pub;

import java.io.File;
import javax.swing.filechooser.FileFilter;

public class Filter extends FileFilter {

    private String extention;
    private String discription;

    public Filter(String extention, String discription) {
        this.extention = extention;
        this.discription = discription;
    }

    public Filter(String extention) {
        this.extention = extention;
    }

    public boolean accept(File file) {
        return (file.getName().toLowerCase().endsWith("." + extention.toLowerCase()) || file.isDirectory());
    }

    public String getDescription() {
        return discription;
    }

    public String getExtention() {
        return extention;
    }
}


text:
cd ~/GDELT/files
# make sure yesterday's csv's are gone.
rm *.CSV
rm *.csv
cd ~/GDELT
echo Downloading today's file.
python download_daily.py fetch -d ~/GDELT/files -U
cd ~/GDELT/files
echo Cleaning up…
rm *.zip
mv *.CSV today.csv
echo Importing today.csv into SQLite database…
sqlite3 gdelt.db < daily-import.sql
# rm ~/GDELT/files/today.csv

# This does some diagnostics that get mailed to me.
Rscript ~/GDELT/r-test.R

echo Beginning R script…
# "filtered-report.Rnw" is the Sweave document of my report.
R CMD Sweave filtered-report.Rnw
echo First XeLaTeX run…
xelatex filtered-report.tex
echo second XeLaTeX run…
xelatex filtered-report.tex
echo Report complete.

uuencode filtered-report.pdf Daily_Report.pdf | mail -s GDELT_Daily_Report <your.recipient@domain.com> -F"<SenderName>" -f"<sender@domain.com"


text:
package com.alsiry.alquran;
import com.alsiry.alquran.TextActor.TextAlign;
import com.alsiry.alquran.book.Stages;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.utils.ActorGestureListener;

public class GozaTap extends Table {
	public static final float tab_width = Gdx.graphics.getWidth();
	public static final float tab_height = Gdx.graphics.getHeight()/12;
	final float tab_no_width = .13f*tab_width;
	final float joza_page_no_width = .13f*tab_width ;

	final float ayat_widht = .02f*tab_width;
	final float sorah_tanzel_width = .1f*tab_width ;
	final float joza_name_width =.41f* tab_width;
	final float sorah_tab_book_mark_width = .07f*tab_width ;
	final float tab_no_text_scale = tab_height /250 ;
	final float tab_page_text_scale = tab_height /250 ;

	public static final float tab_pading_height = tab_height/100;
	int parts_pages[]={
			1,22,42,
			62,82,102,
			121,142,162,
			182,201,222,
			242,262,282,
			302,322,342,
			362,382,402,
			422,442,462,
			482,502,522,
			542,562,582 ,610//for exeption
		};
	class BookMarks extends Actor{
		TextureRegion bookmark_texture  ;
		Sprite bookmark_sprite ;
		int bookmark_type , no  ;
		boolean bookmark_state = false ;

		float x , y ;
		public BookMarks(int sorah_no , int type_from1_to3) {
			// TODO Auto-generated constructor stub
			bookmark_type = type_from1_to3 ;
			bookmark_texture = book.images_textures_atlas.findRegion("bookmark"+bookmark_type);
			bookmark_sprite = new Sprite(bookmark_texture) ;
			bookmark_sprite.setSize(sorah_tab_book_mark_width, tab_height);
			no = sorah_no ;
		}

		@Override
		public void draw(Batch batch, float parentAlpha) {
			// TODO Auto-generated method stub
			int checker = 0 ;
			int checker_a=0;
			float r,g,b  ;
			r=g=b=0 ;
			super.draw(batch, parentAlpha);
			switch (bookmark_type) {
			case 1:
				checker = book.bookmark_a_page;

				r =1 ;
				g =.105f ;
				b =0.694f;

				break;
			case 2:
				checker = book.bookmark_b_page;
				r =.105f ;
				g =1 ;
				b =0.843f;

				break;
			case 3:
				checker = book.bookmark_c_page;
				r =1 ;
				g =.862f;
				b =.105f ;

				break;
			default:
				break;
			}

				if ((checker >= parts_pages[no - 1] && (checker < parts_pages[no]))) {
					if (checker_a == 0 || checker_a == no) {
						switch (bookmark_type) {
						case 1:
							book.b_a_p_t = no;
							break;
						case 2:
							book.b_b_p_t = no;
							break;
						case 3:
							book.b_c_p_t = no;
							break;
						default:
							break;
						}
						bookmark_state = true;
					} else {
						bookmark_state = false;
					}

				} else
					bookmark_state = false;

			if(bookmark_state){
				x = (joza_page_no_width+sorah_tanzel_width)+(sorah_tab_book_mark_width)*(bookmark_type-1)  ;
				y = book.parts_scroll_pane.getScrollY()+Gdx.graphics.getHeight()-((tab_height*no+tab_pading_height*(no-1)));
				bookmark_sprite.setColor(r, g, b, .8f);
				bookmark_sprite.setPosition(x, y);
				bookmark_sprite.setOriginCenter();
				bookmark_sprite.setScale(.5f, .95f);
				bookmark_sprite.draw(batch);
			}
		}

	}
	class GozaName extends Actor{
		 float width , height , x , y  ;
		 TextureRegion goza_name_texture;
		 Sprite Goza_name_sprite ;
		 int no ;
		 TextActor no_of_surah ;
		float text_y_deferance ;
		public GozaName(int goza_no) {
			// TODO Auto-generated constructor stub
			goza_name_texture = book.get_region("j"+goza_no);
			Goza_name_sprite = new Sprite(goza_name_texture);
			width = joza_name_width ;
			height = tab_height ;
			Goza_name_sprite.setSize(width, height);
			no = goza_no ;
			text_y_deferance=2*tab_height/3;
			x = (joza_page_no_width+sorah_tanzel_width+ayat_widht)+sorah_tab_book_mark_width*3  ;
			y = book.parts_scroll_pane.getScrollY()+Gdx.graphics.getHeight()-((tab_height*no+tab_pading_height*(no-1)));

			no_of_surah = new TextActor(no+"",
					null,
					tab_no_width,
					TextAlign.align_cinter,tab_no_text_scale,x+joza_name_width, text_y_deferance+y);
		}

		@Override
		public void draw(Batch batch, float parentAlpha) {

	// TODO Auto-generated method stub
			x = (joza_page_no_width+sorah_tanzel_width+ayat_widht)+sorah_tab_book_mark_width*3  ;
			y = book.parts_scroll_pane.getScrollY()+Gdx.graphics.getHeight()-((tab_height*no+tab_pading_height*(no-1)));

			Goza_name_sprite.setPosition(x, y);
			Goza_name_sprite.setOriginCenter();
			Goza_name_sprite.setScale(.95f);
			Goza_name_sprite.draw(batch);
			no_of_surah.set_position(x+joza_name_width,text_y_deferance+ y);
			no_of_surah.draw(batch, parentAlpha);
		}
	}
	class Pading extends Actor{
		TextureRegion bar ;
		Sprite pading_sprite;
		float x , y , width ,height ;
		int no ;
		public Pading(int no_of_me) {
			// TODO Auto-generated constructor stub
			bar = book.loading_texture_atlas.findRegion("loadingbar");
		pading_sprite = new Sprite(bar);
		pading_sprite.setColor(0,0,0,1);
		width = tab_width ;
		height = tab_pading_height ;
		pading_sprite.setSize(width, height);
		no = no_of_me ;
		}
		@Override
		public void draw(Batch batch, float parentAlpha) {
			// TODO Auto-generated method stub
			super.draw(batch, parentAlpha);
			x =0  ;
			y = book.parts_scroll_pane.getScrollY()+Gdx.graphics.getHeight()-((tab_height*no+tab_pading_height*(no)));
			pading_sprite.setPosition(x, y);
			pading_sprite.draw(batch);
		}

	}
	class MakeMadany extends Actor{
		 float width , height , x , y  ;
		 int no ;
		 TextActor surah_page_no ;

			float text_y_deferance ;
			public MakeMadany(int sorah_no){
			// TODO Auto-generated constructor stub

			height = tab_height ;
			width = height;

			no = sorah_no ;
			y = book.parts_scroll_pane.getScrollY()+Gdx.graphics.getHeight()-((tab_height*no+tab_pading_height*(no-1)));
			text_y_deferance=2*tab_height/3;
			surah_page_no = new TextActor(""+parts_pages[no-1],
					null,
					joza_page_no_width,
					TextAlign.align_cinter, tab_no_text_scale,0,text_y_deferance+y);

		}
		@Override
		public void draw(Batch batch, float parentAlpha) {

			y = book.parts_scroll_pane.getScrollY()+Gdx.graphics.getHeight()-((tab_height*no+tab_pading_height*(no-1)));

			surah_page_no.set_position(0,text_y_deferance+ y);
			surah_page_no.draw(batch, parentAlpha);
	}

}

	GozaTap(final int goza_no){

	this.add(new GozaName( goza_no)).width(/*gozaname_width+gozatab_book_mark_width*3+tab_no_width*/tab_width).height(tab_height);
	this.add(new MakeMadany( goza_no));
	for (int i=1 ;i<=3 ;i++ )
	{
	this.add(new BookMarks( goza_no , i));
	}
	this.addListener(new ActorGestureListener(){

		@Override
		public void tap(InputEvent event, float x, float y, int count, int button) {
			// TODO Auto-generated method stub
			super.tap(event, x, y, count, button);

			book.stage_detector=Stages.pages ;
			book.config_input_prossesor(Stages.pages);

			book.current_page = parts_pages[goza_no-1] ;
			book.pages_stage.draw();
			book.pages_draw_stage.draw();
			book.pages_stage.act(Gdx.graphics.getDeltaTime());
			book.pages_scroll_pane.setScrollY((book.current_page-1)*book.screen_height );
			book.snab_to =((book.current_page-1)*book.screen_height ) ;
			book.update_saved_page_no(book.current_page) ;

		}
	});
	this.row();
	if ( goza_no!=book.ajzaa_no) {
		this.add(new Pading( goza_no)).width(tab_width).height(tab_pading_height);
	}else{
	this.add(new Table()).width(tab_width).height(tab_pading_height);}
}
}


text:
<?php

namespace app\modules\rooms\controllers;

use Yii;
use app\modules\rooms\models\RoomsAcc;
use app\modules\rooms\models\RoomsAccSearch;
use vova07\admin\components\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * RoomsAccController implements the CRUD actions for RoomsAcc model.
 */
class RoomsaccController extends Controller {

    /**
     * @inheritdoc
     */
    public function behaviors() {
        $behaviors = parent::behaviors();

        $behaviors['access']['rules'] = [
            [
                'allow' => true,
                'actions' => ['index', 'view'],
                'roles' => ['BViewRoomsAccount']
            ]
        ];
        $behaviors['access']['rules'][] = [
            'allow' => true,
            'actions' => ['create'],
            'roles' => ['BCreateRoomsAccount']
        ];
        $behaviors['access']['rules'][] = [
            'allow' => true,
            'actions' => ['update'],
            'roles' => ['BUpdateRoomsAccount']
        ];
        $behaviors['access']['rules'][] = [
            'allow' => true,
            'actions' => ['delete', 'batch-delete'],
            'roles' => ['BDeleteRoomsAccount']
        ];
        $behaviors['verbs'] = [
            'class' => VerbFilter::className(),
            'actions' => [
                'index' => ['get'],
                'create' => ['get', 'post'],
                'update' => ['get', 'put', 'post'],
                'delete' => ['post', 'delete'],
                'batch-delete' => ['post', 'delete']
            ]
        ];

        return $behaviors;
    }

    /**
     * Lists all RoomsAcc models.
     * @return mixed
     */
    public function actionIndex() {
        $searchModel = new RoomsAccSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
                    'searchModel' => $searchModel,
                    'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single RoomsAcc model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id) {
        return $this->render('view', [
                    'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new RoomsAcc model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate() {
        $model = new RoomsAcc(['scenario' => 'admin-create']);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                        'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing RoomsAcc model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id) {
        $model = $this->findModel($id);
        $model->setScenario('admin-update');

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                        'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing RoomsAcc model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id) {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the RoomsAcc model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return RoomsAcc the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id) {
        if (($model = RoomsAcc::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

}


text:
var map, switcherControl, bBoxFrozen = false;
$(function() {

    // Get the page "block" in which an element is contained
    $.fn.getLayer = function() {
        return $(this[0]).closest('.layer-wrap');
    };

    // Try to avoid pink tiles
    OpenLayers.IMAGE_RELOAD_ATTEMPTS = 3;
    OpenLayers.Util.onImageLoadErrorColor = "transparent";
    OpenLayers.ImgPath = "/DAV/web/bundles/berkmanatlasviewer/images/openlayers/";

    // Create our variables
    var options = {
            controls: [],
            projection: new OpenLayers.Projection("EPSG:900913"),
            displayProjection: new OpenLayers.Projection("EPSG:4326"),
            units: "m",
            maxResolution: 156543.0339,
            maxExtent: new OpenLayers.Bounds(-20037508.3427892,-20037508.3427892,20037508.3427892,20037508.3427892),
            numZoomLevels: maxZoom
        },
        gmap = new OpenLayers.Layer.Google("Google Streets", { sphericalMercator: true} ),
        ghyb = new OpenLayers.Layer.Google("Google Hybrid", {type: google.maps.MapTypeId.HYBRID}),
        layers = [gmap, ghyb],
        layer;

    map = new OpenLayers.Map('map', options);

    // Create layers out of the atlas's pages
    for ( i in pages ) {
        pages[i].oBounds = new OpenLayers.Bounds(
            pages[i].bounds.miny,
            pages[i].bounds.minx,
            pages[i].bounds.maxy,
            pages[i].bounds.maxx
        ).transform(map.displayProjection, map.projection);

        layer = new OpenLayers.Layer.TMS(
            pages[i].name,
            "",
            {
                type: 'png',
                alpha: true,
                transitionEffect: 'resize',
                isBaseLayer: false,
                getURL: function(bounds) {
                    var res = this.map.getResolution();
                    var x = Math.round((bounds.left - this.maxExtent.left) / (res * this.tileSize.w));
                    var y = Math.round((bounds.bottom - this.tileOrigin.lat) / (res * this.tileSize.h));
                    var z = this.map.getZoom();

                    for ( i in pages ) {
                        if (this.id == pages[i].layerId) {
                            var mapBounds = pages[i].oBounds,
                                pageId = pages[i].id,
                                minZoom = pages[i].minZoom,
                                maxZoom = pages[i].maxZoom;
                        }
                    }

                    if (mapBounds.intersectsBounds( bounds ) && z >= minZoom && z <= maxZoom ) {
                        return this.url + '../../../tiles/' + atlasId + '/' + pageId + '/' + z + "/" + x + "/" + y + "." + this.type;
                    } else {
                        return "http://www.maptiler.org/img/none.png";
                    }
                }
            }
        );

        pages[i].layerId = layer.id;
        layers.push(layer);
    }
    map.addLayers(layers);

    // Add the feature layer which will serve as the page bounding box on hover
    var style_blue = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
    style_blue.strokeColor = "darkred";
    style_blue.fillColor = "darkred";
    style_blue.fillOpacity = .05;
    style_blue.pointRadius = 10;
    style_blue.strokeWidth = 2;
    style_blue.strokeLinecap = "butt";
    style_blue.zIndex = 999;

    var featureLayer = new OpenLayers.Layer.Vector("layerBBox", { style: style_blue, displayInLayerSwitcher: false });
    map.addLayer(featureLayer);
    map.setLayerIndex(featureLayer, 1000);

    // Add the layer switcher and make it visible by default
    switcherControl = new OpenLayers.Control.CustomLayerSwitcher({ roundedCornerColor: 'black' });
    map.addControl(switcherControl);
    switcherControl.maximizeControl();

    // Hide the page-specific controls by default
    $('#metadata-toggle, .layer-inside-wrap').hide();

    // Add all the other controls
    map.addControl(new OpenLayers.Control.PanZoomBar());
    map.addControl(new OpenLayers.Control.MousePosition());
    map.addControl(new OpenLayers.Control.MouseDefaults());
    map.addControl(new OpenLayers.Control.KeyboardDefaults());

    // Add the custom click handler so we can show which pages have been doubleclicked on
    var clickHandler = new OpenLayers.Control.ClickHandler();
    map.addControl(clickHandler);
    clickHandler.activate();

    // Zoom to the atlas extent by default
    map.zoomToExtent( new OpenLayers.Bounds( atlasBounds.miny, atlasBounds.minx, atlasBounds.maxy, atlasBounds.maxx ).transform(map.displayProjection, map.projection ), true );

    /**
     * Here come the event handlers
     */

    /* ---- Metadata handlers ----*/
    $('#metadata-toggle').click(function() {
        $('#metadata').slideToggle('fast');
        $(this).slideToggle('fast');
    });

    $('#metadata-close').click(function() {
        $('#metadata').slideToggle('fast');
        $('#metadata-toggle').slideToggle('fast');
    });

    $('#page-metadata').dialog({
        autoOpen: false,
        modal: true,
        dialogClass: 'metadata-modal',
        zIndex: 1200
    });

    $('#help').dialog({
        autoOpen: false,
        modal: true,
        title: 'Help',
        width: 'auto',
        maxWidth: '80%',
        zIndex: 1200
    });

    /* ---- Atlas-level handlers ---- */
    $('.olControlLayerSwitcher').mousewheel(function(e) { e.stopPropagation(); });
    $('.atlas-opacity-slider').slider({
        slide: function(e, ui) {
            $('.dataLayersDiv').find('.layer-opacity-slider').each(function() {
                $(this).slider('value', ui.value);
            });
        },
        value: 100,
        step: 10
    });

    $('.atlas-zoom').click(function(e) {
        map.zoomToExtent( new OpenLayers.Bounds( atlasBounds.miny, atlasBounds.minx, atlasBounds.maxy, atlasBounds.maxx ).transform(map.displayProjection, map.projection ), true );
        e.preventDefault();
    });

    $('.multi-layer-zoom').click(function(e) {
        var minx = null, miny = null, maxx = null, maxy = null;
        for( i in pages ) {
            if ( map.getLayer(pages[i].layerId).getVisibility() ) {
                if ( pages[i].bounds.minx < minx || minx === null ) {
                    minx = pages[i].bounds.minx;
                }
                if ( pages[i].bounds.miny < miny || miny === null ) {
                    miny = pages[i].bounds.miny;
                }
                if ( pages[i].bounds.maxx > maxx || maxx === null ) {
                    maxx = pages[i].bounds.maxx;
                }
                if ( pages[i].bounds.maxy < maxy || maxy === null ) {
                    maxy = pages[i].bounds.maxy;
                }
            }
        }
        map.zoomToExtent( new OpenLayers.Bounds( miny, minx, maxy, maxx ).transform(map.displayProjection, map.projection ), true );
        e.preventDefault();
    });

    $('.multi-layer-show').click(function(e) {
        for ( i in map.layers ) {
            if (!map.layers[i].isBaseLayer && map.layers[i].name != 'layerBBox') {
                map.layers[i].setVisibility(true);
                $('.layer-toggle').attr('checked', true);
            }
        }
        e.preventDefault();
    });

    $('.multi-layer-hide').click(function(e) {
        for ( i in map.layers ) {
            if (!map.layers[i].isBaseLayer && map.layers[i].name != 'layerBBox') {
                map.layers[i].setVisibility(false);
                $('.layer-toggle').attr('checked', false);
            }
        }
        e.preventDefault();
    });
    $('.dataLayersDiv').sortable({
        change: function(e, ui) {
            var $layer = $(ui.item).getLayer(),
                startIndex = $layer.data('startIndex'),
                newIndex = $layer.parent().children().not('.ui-sortable-helper').index($layer.parent().find('.ui-sortable-placeholder')),
                diff = startIndex - newIndex;
            //console.log('startIndex: ' + startIndex + ' - newIndex: ' + newIndex + ' - diff: ' + diff);
            $layer.data('startIndex', newIndex);
            map.raiseLayer(map.getLayer($layer.data('layerId')), diff);
        },
        start: function(e, ui) {
            var $layer = $(e.target).getLayer();
            $layer.data('startIndex', $layer.parent().children().index($layer));
            $layer.addClass('not-transparent');
            bBoxFrozen = true;
        },
        stop: function(e) {
            var $layer = $(e.target).getLayer();
            $layer.removeClass('not-transparent');
            bBoxFrozen = false;
        },
        handle: '.layer-handle',
        axis: 'y'
    });

    /* ---- Page-level handlers ---- */
    $('.layer-wrap').hover(
        function(e) {
            showBoundingBox($(e.target).getLayer().data('layerId'));
        },
        function() {
            hideBoundingBox();
        }
    );

    $('.layer-expand-control').click(function() {
        $(this).getLayer().find('.layer-inside-wrap').slideToggle();
        $(this).getLayer().find('.layer-expand-control').toggleClass('expanded-layer');
    });

    $('.layer-handle').dblclick(function() {
        $(this).getLayer().find('.layer-inside-wrap').slideToggle();
        $(this).getLayer().find('.layer-expand-control').toggleClass('expanded-layer');
    });

    $('.layer-opacity-slider').slider({
        slide: function(e, ui) {
            var layerId  = $(ui.handle).getLayer().data('layerId');
            map.getLayer(layerId).setOpacity(ui.value / 100);
        },
        change: function(e, ui) {
            var layerId  = $(ui.handle).getLayer().data('layerId');
            map.getLayer(layerId).setOpacity(ui.value / 100);
        },
        start: function() {
            bBoxFrozen = true;
        },
        stop: function() {
            bBoxFrozen = false;
        },
        value: 100,
        step: 5
    });

    $('.layer-zoom').click(function(e) {
        var i, bounds, layerId = $(this).getLayer().data('layerId');
        for (i in pages) {
            if (pages[i].layerId == layerId) {
                bounds = pages[i].oBounds;
            }
        }
        map.zoomToExtent(bounds, true);
        e.preventDefault();
    });

    $('.layer-raise').click(function(e) {
        var layerId = $(this).getLayer().data('layerId');
        $('.dataLayersDiv').prepend($(e.target).getLayer());
        map.setLayerIndex(map.getLayer(layerId), pages.length + 1);
    });

    $('.layer-metadata').click(function(e) {
        var layerId = $(this).getLayer().data('layerId');
        for (i in pages) {
            if (pages[i].layerId == layerId) {
                $('#page-metadata').html(function() {
                    var html = '
';
                    for (term in pages[i].metadata) {
                        html += '
' + term + '

' + pages[i].metadata[term] + '
';
                    }
                    html += '
';
                    return html;
                }).dialog('option', {title: pages[i].name}).dialog('open');
            }
        }
    });

    $('#help-link').click(function() { $('#help').dialog('open'); });
});

function showBoundingBox(layerId) {
    if (!bBoxFrozen) {
        var bounds, i, featureLayer = map.getLayersByName("layerBBox")[0];
        featureLayer.removeAllFeatures();

        for (i in pages) {
            if (pages[i].layerId == layerId) {
                bounds = pages[i].oBounds;
            }
        }

        var box = new OpenLayers.Feature.Vector(bounds.toGeometry());
        featureLayer.addFeatures([box]);
    }
}

function hideBoundingBox() {
    if (!bBoxFrozen) {
        map.getLayersByName('layerBBox')[0].removeAllFeatures();
    }
}


text:
package sample.chirper.activity.impl;

import akka.NotUsed;
import com.lightbend.lagom.javadsl.api.ServiceCall;
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.CompletionStage;
import javax.inject.Inject;

import org.pcollections.PSequence;
import sample.chirper.activity.api.ActivityStreamService;
import sample.chirper.chirp.api.Chirp;
import sample.chirper.chirp.api.ChirpService;
import sample.chirper.chirp.api.HistoricalChirpsRequest;
import sample.chirper.chirp.api.LiveChirpsRequest;
import sample.chirper.friend.api.FriendService;

import akka.stream.javadsl.Source;

public class ActivityStreamServiceImpl implements ActivityStreamService {

  private final FriendService friendService;
  private final ChirpService chirpService;

  @Inject
  public ActivityStreamServiceImpl(FriendService friendService,
                                   ChirpService chirpService) {
    this.friendService = friendService;
    this.chirpService = chirpService;
  }

  @Override
  public ServiceCall<NotUsed, Source<Chirp, ?>> getLiveActivityStream(String userId) {
    return req -> {
      return friendService.getUser(userId).invoke().thenCompose(user -> {
        PSequence<String> userIds = user.getFriends().plus(userId);
        LiveChirpsRequest chirpsReq =  LiveChirpsRequest.of(userIds);
        // Note that this stream will not include changes to friend associates,
        // e.g. adding a new friend.
        CompletionStage<Source<Chirp, ?>> result = chirpService.getLiveChirps(userId).invoke(chirpsReq);
        return result;
      });
    };
  }

  @Override
  public ServiceCall<NotUsed, Source<Chirp, ?>> getHistoricalActivityStream(String userId) {
    return req ->
      friendService.getUser(userId).invoke().thenCompose(user -> {
        PSequence<String> userIds = user.getFriends().plus(userId);
        // FIXME we should use HistoricalActivityStreamReq request parameter
        Instant fromTime = Instant.now().minus(Duration.ofDays(7));
        HistoricalChirpsRequest chirpsReq = HistoricalChirpsRequest.of(fromTime, userIds);
        CompletionStage<Source<Chirp, ?>> result = chirpService.getHistoricalChirps().invoke(chirpsReq);
        return result;
      });
  }

}


text:
@interface TalkfunCourseModel : NSObject

@property (nonatomic,copy) NSString *course_id;//课程ID
@property (nonatomic,copy) NSString *course_name;//课程名称
//@property (nonatomic,copy) NSString *create_date;//创建日期(格式:2015-09-01)
@property (nonatomic,copy) NSString *start_time;//开始时间(09-09 15:00)
@property (nonatomic,copy) NSString *end_time;//结束时间(09-09 17:00)
@property (nonatomic,copy) NSString *status;//状态:1为未到直播时间,2为在直播时间段内,3为已过直播时间

@end


text:
/**
 * Category.js
 *
 * @description :: Category model is here
 * @docs        :: http://sailsjs.org/#!documentation/models
 */

module.exports = {

  connection: 'restConnection'

};


text:
"""Tests for Heston Model."""

from absl.testing import parameterized

import numpy as np
import tensorflow.compat.v2 as tf

import tf_quant_finance as tff

from tensorflow.python.framework import test_util  # pylint: disable=g-direct-tensorflow-import

HestonModel = tff.models.HestonModel
grids = tff.math.pde.grids

@test_util.run_all_in_graph_and_eager_modes
class HestonModelTest(parameterized.TestCase, tf.test.TestCase):

  def test_volatility(self):
    """Tests volatility stays close to its mean for small vol of vol."""
    theta = 0.05
    process = HestonModel(mean_reversion=1.0, theta=theta, volvol=0.00001,
                          rho=-0.0, dtype=np.float64)
    years = 1.0
    times = np.linspace(0.0, years, int(365 * years))
    num_samples = 2
    paths = process.sample_paths(
        times,
        time_step=0.01,
        num_samples=num_samples,
        initial_state=np.array([np.log(100), 0.045]),
        seed=None)
    # For small values of volvol, volatility should stay close to theta
    volatility_trace = self.evaluate(paths)[..., 1]
    max_deviation = np.max(abs(volatility_trace[:, 50:] - theta))
    self.assertAlmostEqual(max_deviation, 0.0, places=2)

  def test_state(self):
    """Tests state behaves like GBM for small vol of vol."""
    theta = 1.0
    process = HestonModel(mean_reversion=1.0, theta=theta, volvol=0.00001,
                          rho=-0.0, dtype=np.float64)
    times = [0.0, 0.5, 1.0]
    num_samples = 1000
    start_value = 100
    paths = process.sample_paths(
        times,
        time_step=0.001,
        num_samples=num_samples,
        initial_state=np.array([np.log(start_value), 1.0]),
        seed=None)
    # For small values of volvol, state should behave like Geometric
    # Brownian Motion with volatility `theta`.
    state_trace = self.evaluate(paths)[..., 0]
    # Starting point should be the same
    np.testing.assert_allclose(state_trace[:, 0], np.log(100), 1e-8)
    for i in (1, 2):
      # Mean and variance of the approximating Geometric Brownian Motions
      gbm_mean = start_value
      gbm_std = start_value * np.sqrt((np.exp(times[i]) - 1))
      np.testing.assert_allclose(np.mean(np.exp(state_trace[:, i])),
                                 gbm_mean, 1.0)
      np.testing.assert_allclose(np.std(np.exp(state_trace[:, 1])),
                                 gbm_std, 2.0)

  def test_expected_total_variance_scalar(self):
    """Tests the expected total variance calculation."""
    mean_reversion = 1.3
    theta = 0.2
    process = HestonModel(
        mean_reversion=mean_reversion,
        theta=theta,
        volvol=0.01,
        rho=0.1,
        dtype=np.float64)
    future_time = 1.2
    initial_var = 0.3
    expected_var = self.evaluate(
        process.expected_total_variance(future_time, initial_var))
    ground_var = (initial_var - theta) * (1 - np.exp(
        -mean_reversion * future_time)) / mean_reversion + theta * future_time
    np.testing.assert_allclose(expected_var, ground_var)

  def test_expected_var_mc(self):
    """Tests the expected total var calculation matches Monte Carlo results."""

    # Define process
    initial_var = 0.1
    rho = -0.5
    volvol = 1.0
    mean_reversion = 10.0
    theta = 0.04
    dtype = tf.float64
    process = HestonModel(
        mean_reversion=mean_reversion,
        theta=theta,
        volvol=volvol,
        rho=rho,
        dtype=dtype)

    # Draw paths
    num_samples = 10000
    num_times = 252
    initial_state = tf.constant([1.0, initial_var], dtype=dtype)
    future_time = 1.0
    times = tf.constant(np.linspace(0, future_time, num_times), dtype=dtype)
    time_step = 0.1
    paths = process.sample_paths(
        times,
        initial_state,
        time_step=time_step,
        num_samples=num_samples,
        seed=123)

    # Monte carlo estimate of discretized integral.
    mc_estimate_var = self.evaluate(tf.math.reduce_mean(
        tf.math.reduce_sum(tff.math.diff(times) * paths[:, :, 1], axis=1)))

    # Compare to total var from formula implementation.
    expected_var = self.evaluate(
        process.expected_total_variance(future_time, initial_var))
    np.testing.assert_allclose(expected_var, mc_estimate_var, rtol=0.01)

  def test_expected_total_variance_batch(self):
    """Tests the expected total variance calculation."""
    mean_reversion = 1.3
    theta = 0.2
    process = HestonModel(
        mean_reversion=mean_reversion,
        theta=theta,
        volvol=0.01,
        rho=-0.0,
        dtype=np.float64)
    future_time = np.array([0.1, 1.0, 2.0])
    initial_var = np.array([0.1, 0.2, 0.3])
    expected_var = self.evaluate(
        process.expected_total_variance(future_time, initial_var))
    ground_var = (initial_var - theta) * (1 - np.exp(
        -mean_reversion * future_time)) / mean_reversion + theta * future_time
    np.testing.assert_allclose(expected_var, ground_var)

  def test_expected_var_raises_on_piecewise_params(self):
    """Tests the claimed error is raised for piecewise params."""
    dtype = tf.float64
    mean_reversion = tff.math.piecewise.PiecewiseConstantFunc(
        jump_locations=[0.5], values=[1, 1.1], dtype=dtype)
    theta = tff.math.piecewise.PiecewiseConstantFunc(
        jump_locations=[0.5], values=[1, 0.9], dtype=dtype)
    volvol = tff.math.piecewise.PiecewiseConstantFunc(
        jump_locations=[0.3], values=[0.1, 0.2], dtype=dtype)
    rho = tff.math.piecewise.PiecewiseConstantFunc(
        jump_locations=[0.5], values=[0.4, 0.6], dtype=dtype)
    process = HestonModel(
        mean_reversion=mean_reversion,
        theta=theta,
        volvol=volvol,
        rho=rho,
        dtype=dtype)
    with self.assertRaises(ValueError):
      process.expected_total_variance(1.0, 1.0)

  @parameterized.named_parameters(
      ('SinglePrecision', np.float32),
      ('DoublePrecision', np.float64),
      ('AutoDtype', None))
  def test_piecewise_and_dtype(self, dtype):
    """Tests that piecewise constant coefficients can be handled."""
    mean_reversion = tff.math.piecewise.PiecewiseConstantFunc(
        jump_locations=[0.5], values=[1, 1.1], dtype=dtype)
    theta = tff.math.piecewise.PiecewiseConstantFunc(
        jump_locations=[0.5], values=[1, 0.9], dtype=dtype)
    volvol = tff.math.piecewise.PiecewiseConstantFunc(
        jump_locations=[0.3], values=[0.1, 0.2], dtype=dtype)
    rho = tff.math.piecewise.PiecewiseConstantFunc(
        jump_locations=[0.5], values=[0.4, 0.6], dtype=dtype)
    process = HestonModel(
        mean_reversion=mean_reversion, theta=theta, volvol=volvol,
        rho=rho, dtype=dtype)
    times = [0.1, 1.0]
    num_samples = 100
    initial_state = np.array([np.log(100), 0.045], dtype=dtype)
    paths = process.sample_paths(
        times,
        time_step=0.1,
        num_samples=num_samples,
        initial_state=initial_state,
        seed=None)
    paths = self.evaluate(paths)
    state_trace, volatility_trace = paths[..., 0], paths[..., 0]
    if dtype is not None:
      with self.subTest('VolatilityDtype'):
        self.assertEqual(volatility_trace.dtype, dtype)
      with self.subTest('StateDtype'):
        self.assertEqual(state_trace.dtype, dtype)
    # Check drift and volatility calculation
    dtype = paths.dtype
    initial_state = tf.convert_to_tensor(initial_state, dtype=dtype)
    with self.subTest('Drift'):
      self.assertAllClose(
          process.drift_fn()(times[0], initial_state),
          np.array([-0.0225, 0.955]))
    with self.subTest('Volatility'):
      self.assertAllClose(
          process.volatility_fn()(times[0], initial_state),
          np.array([[0.21213203, 0.],
                    [0.00848528, 0.01944222]]))

  def test_compare_monte_carlo_to_backward_pde(self):
    dtype = tf.float64
    mean_reversion = 0.3
    theta = 0.05
    volvol = 0.02
    rho = 0.1
    maturity_time = 1.0
    initial_log_spot = 3.0
    initial_vol = 0.05
    strike = 15
    discounting = 0.5

    heston = HestonModel(
        mean_reversion=mean_reversion, theta=theta, volvol=volvol, rho=rho,
        dtype=dtype)
    initial_state = np.array([initial_log_spot, initial_vol])
    samples = heston.sample_paths(
        times=[maturity_time / 2, maturity_time],
        initial_state=initial_state,
        time_step=0.01,
        num_samples=1000,
        random_type=tff.math.random.RandomType.STATELESS_ANTITHETIC,
        seed=[1, 42])
    self.assertEqual(samples.shape, [1000, 2, 2])
    log_spots = samples[:, -1, 0]
    monte_carlo_price = (
        tf.constant(np.exp(-discounting * maturity_time), dtype=dtype) *
        tf.math.reduce_mean(tf.nn.relu(tf.math.exp(log_spots) - strike)))

    s_min, s_max = 2, 4
    v_min, v_max = 0.03, 0.07
    grid_size_s, grid_size_v = 101, 101
    time_step = 0.01

    grid = grids.uniform_grid(minimums=[s_min, v_min],
                              maximums=[s_max, v_max],
                              sizes=[grid_size_s, grid_size_v],
                              dtype=dtype)

    s_mesh, _ = tf.meshgrid(grid[0], grid[1], indexing='ij')
    final_value_grid = tf.nn.relu(tf.math.exp(s_mesh) - strike)
    value_grid = heston.fd_solver_backward(
        start_time=1.0,
        end_time=0.0,
        coord_grid=grid,
        values_grid=final_value_grid,
        time_step=time_step,
        discounting=lambda *args: discounting)[0]
    pde_price = value_grid[int(grid_size_s / 2), int(grid_size_v / 2)]

    self.assertAllClose(monte_carlo_price, pde_price, atol=0.1, rtol=0.1)

  @parameterized.named_parameters(
      {
          'testcase_name': 'SamplePathsWithNumTimeStep',
          'use_num_time_step': True,
          'use_time_grid': False,
          'supply_normal_draws': False,
      }, {
          'testcase_name': 'SamplePathsWithGrid',
          'use_num_time_step': False,
          'use_time_grid': True,
          'supply_normal_draws': False,
      }, {
          'testcase_name': 'SamplePathsWithGridAndDraws',
          'use_num_time_step': False,
          'use_time_grid': True,
          'supply_normal_draws': True,
      })
  def test_compare_monte_carlo_to_european_option(
      self, use_num_time_step, use_time_grid, supply_normal_draws):
    dtype = tf.float64
    mean_reversion_value = 0.3
    theta = 0.05
    volvol = 0.02
    rho = 0.1
    maturity_time = 1.0
    initial_log_spot = 3.0
    initial_vol = 0.05
    strike = 15
    discounting = 0.5

    mean_reversion = tff.math.piecewise.PiecewiseConstantFunc(
        jump_locations=[0.1, 0.2],
        values=[mean_reversion_value, mean_reversion_value,
                mean_reversion_value], dtype=dtype)

    heston = HestonModel(mean_reversion=mean_reversion, theta=theta,
                         volvol=volvol, rho=rho, dtype=dtype)

    times = [maturity_time / 2, maturity_time]
    num_samples = 10000
    time_step = None
    times_grid = None
    num_time_steps = None
    normal_draws = None
    seed = [1, 42]

    if use_num_time_step:
      num_time_steps = 100
    else:
      time_step = 0.01
    if use_time_grid:
      times_grid = tf.constant(np.linspace(0.0, 1.0, 101), dtype=dtype)
    if supply_normal_draws:
      num_samples = 1
      # Use antithetic sampling
      normal_draws = tf.random.stateless_normal(
          shape=[5000, 100, 2],
          seed=seed,
          dtype=dtype)
      normal_draws = tf.concat([normal_draws, -normal_draws], axis=0)
    random_type = tff.math.random.RandomType.STATELESS_ANTITHETIC

    initial_state = np.array([initial_log_spot, initial_vol])
    samples = heston.sample_paths(
        times=times,
        initial_state=initial_state,
        time_step=time_step,
        num_samples=num_samples,
        random_type=random_type,
        seed=seed,
        num_time_steps=num_time_steps,
        normal_draws=normal_draws,
        times_grid=times_grid)
    self.assertEqual(samples.shape, [10000, 2, 2])
    log_spots = samples[:, -1, 0]
    monte_carlo_price = (
        np.exp(-discounting * maturity_time) *
        tf.math.reduce_mean(
            tf.nn.relu(tf.math.exp(log_spots) * np.exp(
                discounting * maturity_time) - strike)))

    # Calulating European option price using above parameters
    dtype = np.float64
    variances = initial_vol
    discount_rates = discounting
    expiries = maturity_time
    mean_reversion = mean_reversion_value

    spots = np.exp(initial_log_spot)
    forwards = None

    european_option_price = self.evaluate(
        tff.models.heston.approximations.european_option_price(
            mean_reversion=mean_reversion,
            theta=theta,
            volvol=volvol,
            rho=rho,
            variances=variances,
            forwards=forwards,
            spots=spots,
            expiries=expiries,
            strikes=strike,
            discount_rates=discount_rates,
            dtype=dtype))

    # Comparing monte carlo and european option price
    self.assertAllClose(
        monte_carlo_price, european_option_price, atol=0.1, rtol=0.1)

if __name__ == '__main__':
  tf.test.main()


text:
<?php namespace Octommerce\Octommerce\Models;

use Backend\Models\ImportModel;

/**
 * ProductImport Model
 */
class ProductImport extends ImportModel
{
    /**
     * @var array The rules to be applied to the data.
     */
    public $rules = [];

    public function importData($results, $sessionKey = null)
    {
        $extraColumns = [
            'parent_sku',
            'brand_name',
            'category_names',
            'up_sell_skus',
            'cross_sell_skus',
        ];

        foreach ($results as $row => $data) {

            try {

                if (isset($data['id']) && $data['id']) {
                    $product = Product::find($data['id']);

                    if (!$product) {
                        $product = new Product;
                    }

                } elseif (isset($data['sku']) && $data['sku']) {
                    $product = Product::firstOrNew(['sku' => $data['sku']]);
                } else {
                    $product = new Product;
                }

                // If has product id, it's updating
                $isUpdate = $product->id ? true : false;

                // Prepare fillable data
                $fillableData = $data;

                // Filter every columns
                foreach($fillableData as $key => $value) {

                    // If empty, set to null
                    if ($value == '') {
                        $fillableData[$key] = $data[$key] = null;
                    }

                    // If it's extra column, unset it
                    if (in_array($key, $extraColumns)) {
                        unset($fillableData[$key]);
                    }
                }

                // Fill columns
                $product->fill($fillableData);

                // Parent product
                if (isset($data['parent_sku']) && $data['parent_sku']) {
                    $parent = Product::whereSku($data['parent_sku'])->first();

                    if ($parent) {
                        $product->parent_id = $parent->id;
                    }
                }

                // Brand
                if (isset($data['brand_name']) && $data['brand_name']) {
                    $brand = Brand::whereName($data['brand_name'])->first();

                    if ($brand) {
                        $product->brand_id = $brand->id;
                    }
                }

                // Categories
                if (isset($data['category_names']) && $data['category_names']) {

                    $categoryIds = [];
                    foreach (explode(';', $data['category_names']) as $categoryName) {

                        $category = Category::whereName($categoryName)->first();

                        if ($category) {
                            $categoryIds[] = $category->id;
                        }
                    }

                    $product->categories()->sync($categoryIds);
                }

                // Up Sells
                if (isset($data['up_sell_skus']) && $data['up_sell_skus']) {

                    $productIds = [];
                    foreach (explode(';', $data['up_sell_skus']) as $sku) {

                        $upsellProduct = Product::whereSku($sku)->first();

                        if ($upsellProduct) {
                            $productIds[] = $upsellProduct->id;
                        }
                    }

                    $product->up_sells()->sync($productIds);
                }

                // Cross Sells
                if (isset($data['cross_sell_skus']) && $data['cross_sell_skus']) {

                    $productIds = [];
                    foreach (explode(';', $data['cross_sell_skus']) as $sku) {

                        $crossSellProduct = Product::whereSku($sku)->first();

                        if ($crossSellProduct) {
                            $productIds[] = $crossSellProduct->id;
                        }
                    }

                    $product->cross_sells()->sync($productIds);
                }

                $product->save();

                if ($isUpdate) {
                    $this->logUpdated();
                } else {
                    $this->logCreated();
                }
            }
            catch (\Exception $ex) {
                $this->logError($row, $ex->getMessage());
            }

        }
    }
}


text:
package server

import (
	"fmt"
	"net/http"

	"github.com/golang/glog"
	"github.com/gorilla/mux"

	"istio.io/istio/broker/pkg/controller"
	"istio.io/istio/broker/pkg/model/config"
	"istio.io/istio/broker/pkg/platform/kube/crd"
)

// Server data
type Server struct {
	ctr *controller.Controller
}

// CreateServer creates a broker server.
func CreateServer(kubeconfig string) (*Server, error) {
	cc, err := crd.NewClient(kubeconfig, config.BrokerConfigTypes)
	if err != nil {
		return nil, err
	}
	c, err := controller.CreateController(config.MakeBrokerConfigStore(cc))
	if err != nil {
		return nil, err
	}

	return &Server{
		c,
	}, nil
}

// Start runs the server and listen on port.
func (s *Server) Start(port uint16) {
	router := mux.NewRouter()

	router.HandleFunc("/v2/catalog", s.ctr.Catalog).Methods("GET")

	http.Handle("/", router)

	if err := http.ListenAndServe(fmt.Sprintf(":%d", port), nil); err != nil {
		glog.Errorf("Unable to start server: %v", err)
	}
}


text:
from .routers import router
from ..autodiscover import autodiscover

autodiscover()

urlpatterns = router.urls