code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
<?php
use Stecman\Passnote\Object\ReadableEncryptedContent;
use Stecman\Passnote\Object\ReadableEncryptedContentTrait;
class ObjectController extends ControllerBase
{
public static function getObjectUrl(StoredObject $object)
{
return 'object/' . $object->getUuid();
}
public function indexAction($uuid)
{
$object = $this->getObjectById($uuid);
if ($object) {
$content = $this->decryptContent($object);
$this->view->setVar('object', $object);
$this->view->setVar('decrypted_content', $content);
} else {
$this->handleAs404('Object not found');
}
}
public function findAction()
{
$query = $this->request->getPost('query', 'trim');
echo $query;
}
public function versionsAction($uuid)
{
$object = $this->getObjectById($uuid);
if ($object) {
$versions = [];
$differ = new \SebastianBergmann\Diff\Differ('');
$prevContent = '';
foreach ($object->versions as $version) {
$nextContent = $this->decryptContent($version);
$diff = $differ->diff($prevContent, $nextContent);
$prevContent = $nextContent;
$version->_diff = $this->formatDiff($diff);
$versions[] = $version;
}
$object->_diff = $this->formatDiff($differ->diff(
$prevContent,
$this->decryptContent($object)
));
$versions[] = $object;
krsort($versions);
$this->view->setLayout('object');
$this->view->setVar('object', $object);
$this->view->setVar('versions', $versions);
} else {
$this->handleAs404('Object not found');
}
}
public function showVersionAction($objectUuid, $versionUuid)
{
$version = $this->getObjectVersion($objectUuid, $versionUuid);
if ($version) {
$content = $this->decryptContent($version);
$this->view->setVar('object', $version->master);
$this->view->setVar('version', $version);
$this->view->setVar('next_version', $version->getSibling(ObjectVersion::NEWER_VERSION));
$this->view->setVar('prev_version', $version->getSibling(ObjectVersion::OLDER_VERSION));
$this->view->setVar('decrypted_content', $content);
} else {
$this->handleAs404('Object or version not found');
}
}
public function editAction($uuid)
{
$object = $this->getObjectById($uuid);
$form = new ObjectForm(null, Security::getCurrentUser());
if ($object) {
$content = $this->decryptContent($object);
$form->setBody($content);
$form->setEntity($object);
$this->view->setVar('object', $object);
}
$this->view->setVar('form', $form);
if ($this->request->isPost() && $form->isValid($_POST)) {
if (!$this->security->checkToken()) {
$this->flash->error('Invalid security token. Please try submitting the form again.');
return;
}
$savedObject = $form->handleSubmit();
$this->response->redirect( self::getObjectUrl($savedObject) );
}
}
public function deleteAction($objectUuid, $versionUuid = null)
{
if ($versionUuid) {
$object = $this->getObjectVersion($objectUuid, $versionUuid);
} else {
$object = $this->getObjectById($objectUuid);
}
$this->view->setVar('object', $object);
$this->view->setVar('isVersion', $object instanceof ObjectVersion);
if (!$object) {
return $this->handleAs404('Object not found');
}
if ($this->request->isPost()) {
if (!$this->security->checkToken()) {
$this->flash->error('Invalid security token. Please try submitting the form again.');
return;
}
$object->delete();
$this->flashSession->success("Deleted object $objectUuid");
$this->response->redirect('');
}
}
protected function decryptContent(ReadableEncryptedContent $object)
{
$user = Security::getCurrentUser();
if ($object->getKeyId() === $user->accountKey_id) {
$keyService = new \Stecman\Passnote\AccountKeyService();
return $keyService->decryptObject($object);
} else {
// Prompt for decryption passphrase
}
}
/**
* @param string $uuid
* @return \StoredObject
*/
protected function getObjectById($uuid)
{
return StoredObject::findFirst([
'uuid = :uuid: AND user_id = :user_id:',
'bind' => [
'uuid' => $uuid,
'user_id' => Security::getCurrentUserId()
]
]);
}
protected function formatDiff($diff)
{
$diff = preg_replace('/(^-.*$)/m', '<span class="diff-del">$1</span>', $diff);
$diff = preg_replace('/(^\+.*$)/m', '<span class="diff-add">$1</span>', $diff);
return $diff;
}
/**
* Fetch an object version from the database
*
* @param string $objectUuid
* @param string $versionUuid
* @return ObjectVersion|null
*/
protected function getObjectVersion($objectUuid, $versionUuid) {
return $this->modelsManager->executeQuery(
'SELECT ObjectVersion.* FROM ObjectVersion'
.' LEFT JOIN StoredObject Object ON ObjectVersion.object_id = Object.id'
.' WHERE ObjectVersion.uuid = :version_uuid: AND Object.uuid = :object_uuid: AND Object.user_id = :user_id:',
[
'version_uuid' => $versionUuid,
'object_uuid' => $objectUuid,
'user_id' => Security::getCurrentUserId()
]
)->getFirst();
}
}
| stecman/passnote | app/controllers/ObjectController.php | PHP | mit | 6,009 |
import { globalShortcut } from 'electron'
import playbackControls from '../actions/playbackControls'
function initGlobalShortcuts () {
globalShortcut.register('MediaNextTrack', playbackControls.clickNextSong)
globalShortcut.register('MediaPreviousTrack', playbackControls.clickPreviousSong)
globalShortcut.register('MediaStop', playbackControls.clickPlayPause)
globalShortcut.register('MediaPlayPause', playbackControls.clickPlayPause)
}
export default initGlobalShortcuts
| ashokfernandez/kiste | src/shortcuts/initGlobalShortcuts.js | JavaScript | mit | 483 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.automation.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.automation.fluent.models.ConnectionInner;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
/** The response model for the list connection operation. */
@Fluent
public final class ConnectionListResult {
@JsonIgnore private final ClientLogger logger = new ClientLogger(ConnectionListResult.class);
/*
* Gets or sets a list of connection.
*/
@JsonProperty(value = "value")
private List<ConnectionInner> value;
/*
* Gets or sets the next link.
*/
@JsonProperty(value = "nextLink")
private String nextLink;
/**
* Get the value property: Gets or sets a list of connection.
*
* @return the value value.
*/
public List<ConnectionInner> value() {
return this.value;
}
/**
* Set the value property: Gets or sets a list of connection.
*
* @param value the value value to set.
* @return the ConnectionListResult object itself.
*/
public ConnectionListResult withValue(List<ConnectionInner> value) {
this.value = value;
return this;
}
/**
* Get the nextLink property: Gets or sets the next link.
*
* @return the nextLink value.
*/
public String nextLink() {
return this.nextLink;
}
/**
* Set the nextLink property: Gets or sets the next link.
*
* @param nextLink the nextLink value to set.
* @return the ConnectionListResult object itself.
*/
public ConnectionListResult withNextLink(String nextLink) {
this.nextLink = nextLink;
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
if (value() != null) {
value().forEach(e -> e.validate());
}
}
}
| Azure/azure-sdk-for-java | sdk/automation/azure-resourcemanager-automation/src/main/java/com/azure/resourcemanager/automation/models/ConnectionListResult.java | Java | mit | 2,244 |
#
# The MIT License(MIT)
#
# Copyright(c) 2016 Copyleaks LTD (https://copyleaks.com)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# =
module Copyleaks
class AuthExipredException < StandardError
attr_reader :reason
def initialize
@reason = 'Authentication Expired. Need to login again'
end
end
end
| Copyleaks/Ruby-Plagiarism-Checker | lib/copyleaks/models/exceptions/auth_exipred_exception.rb | Ruby | mit | 1,349 |
<?php
/**
* Přidá parametr lang=LANG_CODE za každý odkaz na stránce
*
* @param String $link upravovaný odkaz
* @return String upravený $link
*/
function icom_edit_permalink($link) {
if (icom_is_permalink_struct()) {
return ICOM_ABSPATH . icom_current_lang() . "/" . str_replace(ICOM_ABSPATH, "", $link);
} else {
return ICOM_ABSPATH . str_replace(ICOM_ABSPATH, "", $link) . "&lang=" . icom_current_lang();
}
}
/**
* Zjistí aktuálně nastavený jazyk pro zobrazování stránek
* @return String lang_code
*/
function icom_current_lang() {
global $icom_lang_selected_front, $icom_lang_default_front;
$lang = get_query_var('lang');
if (empty($lang) && !empty($_GET['lang'])) {
$lang = $_GET['lang'];
}
if (empty($lang)) return $icom_lang_default_front;
$lang_exists = preg_grep("/" . $lang . "/i", $icom_lang_selected_front); // musí být regulárem namísto in_array(), kvůli case-insensitive
if (!empty($lang_exists)) {
return $lang;
} else {
return $icom_lang_default_front;
}
}
/**
* Pokud je jazyk ulozen v URL vrati TRUE, jinak FALSE
* #not used
* @return boolean
*/
function icom_lang_in_url() {
$l1 = get_query_var('lang');
$l2 = $_GET['lang'];
if ((isset($l1) && !empty($l1)) || (isset($l2) && !empty($l2))) {
return TRUE;
} else {
return FALSE;
}
}
/**
* Vybere z DB stranky ktere nejsou v aktualne zvolenem jazyce
* nebo maji priznak PREVIEW
*
* @global wpdb $wpdb
* @return int[] ID vyloucenych stranek
*/
function icom_get_exclude_pages() {
global $wpdb;
$current_lang = icom_current_lang();
$pages_for_exclude = $wpdb->get_results(" SELECT id_post FROM " . $wpdb->prefix . "icom_translations WHERE lang != '" . $current_lang . "' OR preview = '1'");
foreach ($pages_for_exclude as $page) {
$exclude_pages[] = $page->id_post;
}
return $exclude_pages;
}
/**
* Vyloučí z výpisu stránky podle aktuálně zvoleného jazyka
*
* Slouzi nejspise k zobrazeni menu na frontendu
*/
function icom_exclude_pages($query) {
$exclude_pages = icom_get_exclude_pages();
$query->set('post__not_in', $exclude_pages);
return $query;
}
/**
* Zjisti jestli jsou nastavene cool URL (mod_rewrite)
*
* @return boolean
*/
function icom_is_permalink_struct() {
$structure = get_option('permalink_structure');
if (empty($structure)) {
return false;
} else {
return true;
}
}
/**
* Vrátí strukturu url dle toho jestli jsou nebo nejsou nastaveny permalinky
* @param $lang
* @param $page
* @return boolean
*/
function icom_get_permalink_struct($lang, $page) {
$permalink = icom_is_permalink_struct();
if ($permalink == false)
return array('permalink' => false, 'value' => '?&' . $page . '&lang=' . $lang);
else
return array('permalink' => true, 'value' => $lang . "/" . $page);
}
/**
* Question: Co dela tahle funkce a k cemu se pouziva??
*
* Zjisti jestli je dana stranka (z tabulky posts) typu 'page'
* @return boolean
*/
/*
function icom_get_type($type) {
switch ($type) {
case "post":
break;
default:
if (get_query_var('page_id') || get_query_var('pagename'))
return true;
else if (!get_query_var('p') && !get_query_var('name'))
return true;
else
return false;
break;
}
}
*/
/**
* Zjisti typ(post, page, ...) stranky [post_type] podle ID
*
* @global wpdb $wpdb
* @param int $id
* @return string
*/
function icom_get_post_type($id) {
global $wpdb;
return $wpdb->get_var("SELECT post_type FROM " . $wpdb->prefix . "posts WHERE ID = " . $id . "");
}
/**
* Zjistí post_status (publish, draft, ...) stránky
*
* @global wpdb $wpdb
* @param int $id
* @return string
*/
function icom_get_post_status($id){
global $wpdb;
return $wpdb->get_var("SELECT post_status FROM " . $wpdb->prefix . "posts WHERE ID = " . $id . "");
}
/**
* Zjisti jazyk stranky podle jejiho ID
*
* @global wpdb $wpdb
* @param int $id
* @return string
*/
function icom_get_post_lang($id) {
global $wpdb;
return $wpdb->get_var("SELECT lang FROM " . $wpdb->prefix . "icom_translations WHERE id_post = " . $id . "");
}
/**
* Sestavi permalink pro stranky typu post. Pokud je zjisteny jiny typ (napr. pages),
* tak fce vrati get_permalink()
*
* @global wpdb $wpdb
* @global string $icom_lang_default_front
* @param int $id
* @return string $permalink
*/
function icom_get_post_permalink($id) {
global $wpdb, $icom_lang_default_front;
$lang = icom_get_post_lang($id);
if (!isset($lang) || empty($lang)) {
$lang = $icom_lang_default_front;
}
/* TO-DO: zde je ješte potřeba dodělat aby to vracelo jazyk v případě, že nejsou povolené COOL URL
*/
if (icom_get_post_type($id) !== "post") {
$permalink = get_permalink($id);
if ((stripos($permalink, $lang)) !== FALSE) {
return $permalink;
} else if ((stripos($permalink, ICOM_HOST)) !== FALSE) {
return substr_replace($permalink, $lang . "/", strlen(ICOM_HOST), 0);
} else {
return NULL;
}
}
$slug = $wpdb->get_var("SELECT post_name FROM " . $wpdb->prefix . "posts WHERE ID = " . $id . "");
$permalink = rtrim(str_replace("/wp-admin/", "", ICOM_ABSPATH), "/");
$permalink = rtrim($permalink, "/") . "/" . $lang . "/" . $slug . "/";
return $permalink;
}
/**
* Ziska ID aktualni stranky stranky
* @return type
*/
function icom_get_post_id() {
global $wpdb, $icom_lang_default;
if (get_query_var('p')) {
return get_query_var('p');
} else if (get_query_var('page_id')) {
return get_query_var('page_id');
} else if (get_query_var('icompage') || get_query_var('pagename') || get_query_var('name')) {
$query_string = get_query_var('icompage');
if (empty($query_string)) $query_string = get_query_var('pagename');
if (empty($query_string)) $query_string = get_query_var('name');
$slug_parts = explode("/", $query_string);
$slug_count = count($slug_parts);
$post_name = $slug_parts[$slug_count - 1]; // ziska ID stranky ze slugu (post_name)
//zkusi ziskat ID stranky z tabulky [icom_transtations]
//podle aktualniho jazyka a podle [post_name] z tabulky [posts]
if (stripos($post_name, "preview-page") !== false)
$where = "t.preview = '1'";
else
$where = "t.lang = %s AND t.preview = '0'";
$qry = "SELECT id_post FROM " . $wpdb->prefix . "icom_translations t, " . $wpdb->prefix . "posts p WHERE p.id = t.id_post AND post_name = '" . $post_name . "' AND (" . $where . ") ORDER BY t.id DESC";
$id = $wpdb->get_var($wpdb->prepare($qry, icom_current_lang()));
//pokud neexistuje stranka v tab. [icom_transtations] tzn. neni dostupna v hledanem jazyce
//zkusi ziskat ID nejake stranky se stejnym slugem z tabulky [posts]
if (is_null($id)) {
$id = $wpdb->get_var($wpdb->prepare($qry, $icom_lang_default));
}
if (is_null($id))
return -1;
else
return $id;
} else {
return null;
}
}
/**
* Pokud ID stranky a jazyk nejsou shodne (podle tabulky icom_translations),
* tak se pokusi ziskat ID stranky v danem jazyce a presmerovat na ni.
* Kdyz neni zadne ID nalezene nepresmeruje.
*
* @global wpdb $wpdb
* @param WP_Query $query
* @return WP_Query
*/
function icom_load_page_by_lang($query) {
global $wpdb, $icom_lang_default;
if (!$query->is_main_query()) {
return $query;
}
$is_permalink = icom_is_permalink_struct(); // TRUE pokud se pouzivaji COOL URL
$current_lang = icom_current_lang(); // Jazyk aktualne uvedeny v URL
$last_lang = get_option("icom_language_last"); // Jazyk, ktery byl v URL naposledy (nevim kvuli cemu jsme ho museli zavest)
$is_homepage = false;
$is_page = false;
$is_preview = false;
$id = icom_get_post_id(); // ID aktualni stranky
$id_homepage = get_option('page_on_front'); // ID homepage
// pokud se jedná o preview stránku (která se používá při PR), jen přesměruje na správný jazyk
$preview = $wpdb->get_var("SELECT lang FROM " . $wpdb->prefix . "icom_translations WHERE id_post = '" . $id . "' AND preview = '1'");
if ($preview && empty(get_query_var('lang'))) {
$query->set('lang', $preview);
wp_redirect(icom_get_post_permalink($id) . "?icom-previewHash=" . $_GET['icom-previewHash'] . "&icom-targetLang" . $_GET['icom-targetLang']);
exit();
}
$link_homepage = get_permalink($id);
// pokud se jedná o úvodní stránku defaultního jazyka a nemá v sobě jazyk
if ($is_permalink == true && $id == $id_homepage && ICOM_ABSPATH != $link_homepage) {
wp_redirect($link_homepage);
exit();
}
// 404ka
if ($id == -1) {
if ($id_homepage > 0) {
$query->is_404 = TRUE;
$query->is_post_page = FALSE;
} else {
$query->is_404 = FALSE;
$query->is_post_page = TRUE;
$id = null;
}
// $id je NULL pokud v URL není ID ani slug
} else if (!isset($id)) {
$is_homepage = true;
//zjistim ID postu na zaklade jazyka a ID homepage stranky
$id = $wpdb->get_var("SELECT id_post FROM " . $wpdb->prefix . "icom_translations WHERE lang = '" . $current_lang . "' AND id_post_orig = '" . $id_homepage . "' AND preview = '0'");
//jelikož homepage je na specifický adrese /[LANG]/,
//tak WP řeknu: to není homepage, ale obyčejná page, tak přestan dělat problémy
if (isset($id)) {
$query->is_home = FALSE;
$query->is_page = TRUE;
$query->set("p", $id);
$query->set("page_id", $id);
//pokud homepage ve zvolenem jazyce neexistuje, je potreba vratit 404 Not Found
} else {
$query->is_home = FALSE;
$query->is_404 = FALSE;
$query->is_post_page = TRUE;
}
} else {
$is_page = (icom_get_post_type($id) == "post" ? false : true);
$query->is_home = FALSE;
$query->is_404 = FALSE;
$query->is_admin = FALSE;
if ($is_page == false) {
$query->is_page = FALSE;
$query->is_single = TRUE;
$query->set("p", $id);
$query->set("page_id", 0);
} else {
$query->is_page = TRUE;
$query->is_single = FALSE;
$query->set("p", 0);
$query->set("page_id", $id);
}
$query->is_archive = FALSE;
$query->is_preview = get_query_var('preview');
$query->is_date = FALSE;
$query->is_year = FALSE;
$query->is_month = FALSE;
$query->is_time = FALSE;
$query->is_author = FALSE;
$query->is_category = FALSE;
$query->is_tag = FALSE;
$query->is_tax = FALSE;
$query->is_search = FALSE;
$query->is_feed = FALSE;
$query->is_comment_feed = FALSE;
$query->is_trackback = FALSE;
$query->is_comments_popup = FALSE;
$query->is_attachment = FALSE;
$query->is_singular = TRUE;
$query->is_robots = FALSE;
$query->is_paged = FALSE;
}
$url_array = explode("?", ICOM_ACTUAL);
$link = icom_get_post_permalink($id);
$post_status = icom_get_post_status($id); // draft, publish, future, ...
// pokud jsou nastaveny permalinky a je v url ?lang=jazyk, přesměrujeme, aby tam nebyl
// anebo pokud tam není a měl by být (může se stát u default_jazyka)
if ($id != null && $link != null && $is_permalink == true && (isset($_GET['p']) || isset($_GET['page_id']) || isset($_GET['lang']) || $url_array[0] != $link) && $post_status != "draft") {
$url = "?" . $url_array[1];
$url = preg_replace("/[?|&]p(=[^&]*)?/", "", $url);
$url = preg_replace("/[?|&]lang(=[^&]*)?/", "", $url);
$url = preg_replace("/[?|&]page_id(=[^&]*)?/", "", $url);
//$url = trim($url, "&");
//$url = preg_replace("/[&]+/", "&", $url);
$url = trim($link . "?" . $url, "?");
wp_redirect($url);
exit();
}
// ziskani zaznamu stranky z ICOM_TRANSLATION
$post = $wpdb->get_row("SELECT * FROM " . $wpdb->prefix . "icom_translations WHERE id_post = '" . icom_save_db($id) . "'");
// Pokud se jazyk stranky, kterou chceme nacist (zobrazit) neshodujes jazykem uvedenym v URL
if ($id != null && $is_permalink == true && strcasecmp($post->lang, $current_lang) != 0) {
// ziskani noveho ID pro presmerovani
if ($post->id_post_parent == 0) {
$new_post_id = $wpdb->get_var("SELECT id_post FROM " . $wpdb->prefix . "icom_translations WHERE (id_post_orig = '" . icom_save_db($id) . "' OR id_post_parent = '" . icom_save_db($id) . "') AND lang = '" . $current_lang . "' AND preview = '0'");
} else {
$new_post_id = $wpdb->get_var("SELECT id_post FROM " . $wpdb->prefix . "icom_translations WHERE (id_post_orig = '" . $post->id_post_parent . "' OR id_post_parent = '" . $post->id_post_parent . "') AND lang = '" . $current_lang . "' AND preview = '0'");
}
// presmerovani na novou stranku, se spravnym jazykem
if (isset($new_post_id)) {
update_last_lang_option($current_lang);
wp_redirect(icom_get_post_permalink($new_post_id));
exit();
}
} else if ($id != null && strcasecmp($last_lang, $current_lang) != 0) {
update_last_lang_option($current_lang);
$is_page == true ? $query->set('page_id', $id) : $query->set('p', $id);
/*
if ($is_page == true) {
$query->set('page_id', $id);
} else if ($query->is_main_query()) {
$query->set('p', $id);
}
*/
} else if ($id != null) {
echo "aaa";
update_last_lang_option($current_lang);
$is_page == true ? $query->set('page_id', $id) : $query->set('p', $id);
}
// pokud jsou vypnuty permalinky
if ($is_permalink == false) {
$id2 = $wpdb->get_var("SELECT id_post FROM " . $wpdb->prefix . "icom_translations WHERE id_post_parent = '" . $id . "' AND lang = '" . $current_lang . "' AND preview = '0'");
if (!isset($id2)) {
$parent = $wpdb->get_var("SELECT id_post_parent FROM " . $wpdb->prefix . "icom_translations WHERE id_post = '" . $id . "' AND lang = '" . $current_lang . "' AND preview = '0'");
if (!isset($parent)) $id = null;
} else {
$id = $id2;
}
if (isset($id)) {
$is_page == true ? $query->set('page_id', $id) : $query->set('p', $id);
} else {
$query->is_404 = TRUE;
}
}
if ($id == null) $query->is_404 = TRUE;
return $query;
}
/**
* Aktualizuje polozku 'icom_last_lang' v databazi
* @param String $lang
*/
function update_last_lang_option($lang) {
update_option("icom_language_last", $lang);
}
// přidání nového tagu %lang%, který se pak používá ve struktuře permalinků v nastavení
function icom_lang_rewrite_tag() {
add_rewrite_tag('%lang%', '^([a-zA-Z]{2,3}(-[a-zA-Z]{2,4})?(-[a-zA-Z]{2})?)');
add_rewrite_tag('%icompage%', '([-a-zA-Z_]+)$');
}
// přidání htaccess pravidla, pro odchycení jazyka (ten musí být ve tvaru (aaz-aazz?-az?)
function icom_lang_rewrite_rule() {
add_rewrite_rule('^([a-zA-Z]{2,3}(-[a-zA-Z]{2,4})?(-[a-zA-Z]{2})?)/(.+)', 'index.php?lang=$matches[1]&icompage=$matches[4]', 'top');
}
| idiomaCoLtd/StreamAPI-wordpress-plugin | stream-api_loading_pages.php | PHP | mit | 15,619 |
/**
* @package EntegreJS
* @subpackage Widgets
* @subpackage fontawesome
* @author James Linden <kodekrash@gmail.com>
* @copyright 2016 James Linden
* @license MIT
*/
E.widget.fontawesome = class extends E.factory.node {
constructor( icon ) {
super( 'i' );
this.attr( 'class', `fa fa-${icon.toString().toLowerCase()}` );
}
static css() {
return 'https:/' + '/maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css';
}
size( size ) {
if( !E.empty( size ) ) {
var sizes = [ 'lg', '2x', '3x', '4x', '5x' ];
size = size.toString().toLowerCase();
if( sizes.includes( size ) ) {
this.attr( 'class', `fa-${size}` );
}
}
return this;
}
fixedwidth() {
this.attr( 'class', 'fa-fw' );
return this;
}
border() {
this.attr( 'class', 'fa-border' );
return this;
}
rotate( angle ) {
angle = parseInt( angle );
if( angle >= 0 && angle <= 360 ) {
this.attr( 'class', `fa-rotate-${angle}` );
}
return this;
}
flip( dir ) {
if( !E.empty( dir ) ) {
switch( dir.toString().toLowerCase() ) {
case 'h':
case 'horz':
dir = 'horizontal';
break;
case 'v':
case 'vert':
dir = 'vertical';
break;
}
if( dir in [ 'horizontal', 'vertical' ] ) {
this.attr( 'class', `fa-flip-${dir}` );
}
}
return this;
}
};
| entegreio/entegre-js | src/widget/fontawesome.js | JavaScript | mit | 1,327 |
import unittest
from app.commands.file_command import FileCommand
class TestFileCommand(unittest.TestCase):
def setUp(self):
self.window = WindowSpy()
self.settings = PluginSettingsStub()
self.sublime = SublimeSpy()
self.os_path = OsPathSpy()
# SUT
self.command = FileCommand(self.settings, self.os_path, self.sublime)
def test_open_source_file(self):
self.settings.tests_folder = 'tests/unit'
self.command.open_source_file('C:/path/to/root/tests/unit/path/to/fileTest.php', self.window)
self.assertEqual('C:/path/to/root/path/to/file.php', self.window.file_to_open)
def test_open_source_file_works_with_backslashes(self):
self.settings.tests_folder = 'tests/unit'
self.command.open_source_file('C:\\path\\to\\root\\tests\\unit\\path\\to\\fileTest.php', self.window)
self.assertEqual('C:/path/to/root/path/to/file.php', self.window.file_to_open)
def test_open_source_file_works_for_network_paths(self):
self.settings.tests_folder = 'tests'
self.command.open_source_file('\\\\server\\dev\\root\\tests\\unit\\Service\\SearchParametersMapperTest.php',
self.window)
self.assertEqual('\\\\server\\dev\\root\\Service\\SearchParametersMapper.php', self.window.file_to_open)
def test_open_source_file_works_for_network_paths_and_complex_tests_folder(self):
self.settings.tests_folder = 'tests/unit'
self.command.open_source_file('\\\\server\\dev\\root\\tests\\unit\\Service\\SearchParametersMapperTest.php',
self.window)
self.assertEqual('\\\\server\\dev\\root\\Service\\SearchParametersMapper.php', self.window.file_to_open)
def test_open_source_file_when_tests_folder_is_not_unit_test_folder(self):
self.settings.root = 'C:/path/to/root'
self.settings.tests_folder = 'tests_folder'
self.command.open_source_file('C:/path/to/root/tests_folder/unit/path/to/fileTest.php', self.window)
self.assertEqual('C:/path/to/root/path/to/file.php', self.window.file_to_open)
def test_open_source_file_remove_only_first_appearance_of_tests_folder_in_path(self):
self.settings.root = 'C:/path/to/root'
self.settings.tests_folder = 'tests'
self.command.open_source_file('C:/path/to/root/tests/unit/path/to/tests/fileTest.php', self.window)
self.assertEqual('C:/path/to/root/path/to/tests/file.php', self.window.file_to_open)
def test_open_source_file_when_tests_folder_is_not_unit_test_folder_remove_only_unit_folder_after_test_path(self):
self.settings.root = 'C:/path/to/root'
self.settings.tests_folder = 'tests_folder'
self.command.open_source_file('C:/path/to/root/tests_folder/unit/path/to/unit/fileTest.php', self.window)
self.assertEqual('C:/path/to/root/path/to/unit/file.php', self.window.file_to_open)
def test_if_source_file_exists_return_true(self):
self.settings.tests_folder = 'tests/unit'
self.os_path.is_file_returns = True
actual = self.command.source_file_exists('C:\\path\\to\\root\\tests\\unit\\path\\to\\fileTest.php')
self.assertTrue(actual)
self.assertEqual('C:/path/to/root/path/to/file.php', self.os_path.isfile_received_filepath)
def test_source_file_does_not_exist_if_file_already_is_a_source_file(self):
self.settings.tests_folder = 'tests/unit'
self.os_path.is_file_returns = True
actual = self.command.source_file_exists('root\path\src\Gallery\ImageType.php')
self.assertFalse(actual)
def test_if_source_file_does_not_exist_return_false(self):
self.settings.tests_folder = 'tests/unit'
self.os_path.is_file_returns = False
self.assertFalse(self.command.source_file_exists('C:/path/to/root/path/to/fileTest.php'))
self.assertEqual('C:/path/to/root/path/to/file.php', self.os_path.isfile_received_filepath)
def test_if_source_file_is_none_return_false(self):
""" This case is possible when currently opened tab in sublime is untitled (i.e. not yet created) file """
self.assertFalse(self.command.source_file_exists(None))
def test_if_test_file_is_none_return_false(self):
""" This case is possible when currently opened tab in sublime is untitled (i.e. not yet created) file """
self.settings.root = 'C:/path/to/root'
self.settings.tests_folder = 'tests/unit'
self.assertFalse(self.command.test_file_exists(None, self.window))
def test_open_file(self):
self.settings.root = 'C:/path/to/root'
self.settings.tests_folder = 'tests/unit'
self.command.open_test_file('C:/path/to/root/path/to/file.php', self.window)
self.assertEqual('C:/path/to/root/tests/unit/path/to/fileTest.php', self.window.file_to_open)
def test_correct_file_name_sent_to_os_is_file_method(self):
self.window.project_root = 'C:/path/to/root'
self.settings.root = ''
self.settings.tests_folder = 'tests/unit'
self.command.test_file_exists('C:/path/to/root/path/to/file.php', self.window)
self.assertEqual('C:/path/to/root/tests/unit/path/to/fileTest.php', self.os_path.isfile_received_filepath)
def test_file_exists_ignores_trailing_slash_in_root_path(self):
self.window.project_root = 'C:/path/to/root/'
self.settings.root = ''
self.settings.tests_folder = 'tests/unit'
self.command.test_file_exists('C:/path/to/root/path/to/file.php', self.window)
self.assertEqual('C:/path/to/root/tests/unit/path/to/fileTest.php', self.os_path.isfile_received_filepath)
def test_if_test_file_exists_return_true(self):
self.settings.root = 'C:/path/to/root/'
self.settings.tests_folder = 'tests/unit'
self.os_path.is_file_returns = True
self.assertTrue(self.command.test_file_exists('C:/path/to/root/path/to/file.php', self.window))
def test_test_file_exists_returns_true_if_test_file_is_input(self):
self.settings.root = 'C:/path/to/root/'
self.settings.tests_folder = 'tests/unit'
self.os_path.is_file_returns = True
self.assertTrue(self.command.test_file_exists('C:/path/to/root/tests/unit/path/to/fileTest.php', self.window))
self.assertEqual('C:/path/to/root/tests/unit/path/to/fileTest.php', self.os_path.isfile_received_filepath,
'Expected test file filepath as parameter to isfile')
def test_if_test_file_does_not_exist_return_false(self):
self.settings.root = 'C:/path/to/root/'
self.settings.tests_folder = 'tests/unit'
self.os_path.is_file_returns = False
self.assertFalse(self.command.test_file_exists('C:/path/to/root/path/to/file.php', self.window))
def test_replace_back_slashes_with_forward_slashes(self):
self.window.project_root = 'C:\\path\\to\\root'
self.settings.root = ''
self.settings.tests_folder = 'tests\\unit'
self.command.test_file_exists('C:\\path\\to\\root\\path\\to\\file.php', self.window)
self.assertEqual('C:/path/to/root/tests/unit/path/to/fileTest.php', self.os_path.isfile_received_filepath)
class PluginSettingsStub:
pass
class WindowSpy:
def __init__(self):
self.file_to_open = None
self.project_root = None
def folders(self):
return [self.project_root]
def open_file(self, file_to_open):
self.file_to_open = file_to_open
class OsPathSpy:
def __init__(self):
self.is_file_returns = None
self.isfile_received_filepath = None
def isfile(self, filepath):
self.isfile_received_filepath = filepath
return self.is_file_returns
class SublimeSpy:
pass
| ldgit/remote-phpunit | tests/app/commands/test_file_command.py | Python | mit | 7,821 |
<?php
/**
* Created by PhpStorm.
* User: Lien
* Date: 27/04/2017
* Time: 16:43
*/
use app\models\ModelEvents;
class ModelEventsTest extends PHPUnit_Framework_TestCase
{
} | Alevyr/WebAdvancedCodeIgniter2017 | application/test/models/ModelEventsTest.php | PHP | mit | 179 |
//https://omegaup.com/arena/problem/El-Arreglo-de-Nieves
#include <cstdio>
#include <iostream>
#include <stack>
using namespace std;
struct inf
{
int p, v;
};
int nums, totes, mint, stval;
int nlist[1000005], tol[1000005], tor[1000005], seen[1000005];
inf lastnp[1000005];
int main()
{
scanf("%d", &nums);
for(int i=1; i<=nums; i++)
scanf("%d", &nlist[i]);
for(int i=1; i<=nums; i++)
{
while(stval && lastnp[stval].v%nlist[i]==0)
stval--;
if(stval)
tol[i]=lastnp[stval].p+1;
else
tol[i]=1;
stval++;
lastnp[stval]={i, nlist[i]};
}
stval=0;
for(int i=nums; i; i--)
{
while(stval && lastnp[stval].v%nlist[i]==0)
stval--;
if(stval)
tor[i]=lastnp[stval].p-1;
else
tor[i]=nums;
stval++;
lastnp[stval]={i, nlist[i]};
}
for(int i=1; i<=nums; i++)
{
if(tor[i]-tol[i]+1>tor[totes]-tol[totes]+1)
totes=i;
}
for(int i=1; i<=nums; i++)
{
if(tor[i]-tol[i]+1==tor[totes]-tol[totes]+1 && !seen[tol[i]])
seen[tol[i]]=1, mint++;
}
printf("%d %d\n", mint, tor[totes]-tol[totes]);
for(int i=1; i<=nums; i++)
{
if(seen[i])
printf("%d ", i);
}
printf("\n");
return 0;
}
| JFAlexanderS/Contest-Archive | OmegaUp/El-Arreglo-de-Nieves.cpp | C++ | mit | 1,363 |
/*
* Class Name: Constantes
* Name: Daniel Arevalo
* Date: 13/03/2016
* Version: 1.0
*/
package co.edu.uniandes.ecos.tarea4.util;
/**
* Clase utilitaria de constantes
* @author Daniel
*/
public class Constantes {
public static final String LOC_METHOD_DATA = "LOC/Method Data";
public static final String PGS_CHAPTER = "Pgs/Chapter";
public static final String CLASS_NAME = "Class Name";
public static final String PAGES = "Pages";
}
| darevalor/Ecos-Tarea4 | src/main/java/co/edu/uniandes/ecos/tarea4/util/Constantes.java | Java | mit | 600 |
<?php
if (!class_exists('Paymentwall_Config'))
include(getcwd() . '/components/gateways/lib/paymentwall-php/lib/paymentwall.php');
/**
* Paymentwall
*
* @copyright Copyright (c) 2015, Paymentwall, Inc.
* @link http://www.paymentwall.com/ Paymentwall
*/
class Brick extends NonmerchantGateway
{
/**
* @var string The version of this Gateway
*/
private static $version = "1.0.0";
/**
* @var string The authors of this Gateway
*/
private static $authors = array(array('name' => "Paymentwall, Inc.", 'url' => "https://www.paymentwall.com"));
/**
* @var array An array of meta data for this Gateway
*/
private $meta;
/**
* Construct a new merchant Gateway
*/
public function __construct()
{
// Load components required by this module
Loader::loadComponents($this, array("Input"));
// Load the language required by this module
Language::loadLang("brick", null, dirname(__FILE__) . DS . "language" . DS);
}
/**
* Initial Paymentwall settings
*/
public function initPaymentwallConfigs()
{
Paymentwall_Config::getInstance()->set(array(
'public_key' => $this->meta['test_mode'] ? $this->meta['public_test_key'] : $this->meta['public_key'],
'private_key' => $this->meta['test_mode'] ? $this->meta['private_test_key'] : $this->meta['private_key']
));
}
/**
* Attempt to install this Gateway
*/
public function install()
{
// Ensure that the system has support for the JSON extension
if (!function_exists("json_decode")) {
$errors = array(
'json' => array(
'required' => Language::_("Brick.!error.json_required", true)
)
);
$this->Input->setErrors($errors);
}
}
/**
* Returns the name of this Gateway
*
* @return string The common name of this Gateway
*/
public function getName()
{
return Language::_("Brick.name", true);
}
/**
* Returns the version of this Gateway
*
* @return string The current version of this Gateway
*/
public function getVersion()
{
return self::$version;
}
/**
* Returns the name and URL for the authors of this Gateway
*
* @return array The name and URL of the authors of this Gateway
*/
public function getAuthors()
{
return self::$authors;
}
/**
* Return all currencies supported by this Gateway
*
* @return array A numerically indexed array containing all currency codes (ISO 4217 format) this Gateway supports
*/
public function getCurrencies()
{
$currencies = array();
$record = new Record();
$result = $record->select("code")->from("currencies")->fetchAll();
foreach ($result as $currency) {
$currencies[] = $currency->code;
}
unset($record);
return $currencies;
}
/**
* Sets the currency code to be used for all subsequent payments
*
* @param string $currency The ISO 4217 currency code to be used for subsequent payments
*/
public function setCurrency($currency)
{
$this->currency = $currency;
}
public function getSignupUrl()
{
return "https://api.paymentwall.com/pwaccount/signup?source=blesta&mode=merchant";
}
/**
* Create and return the view content required to modify the settings of this gateway
*
* @param array $meta An array of meta (settings) data belonging to this gateway
* @return string HTML content containing the fields to update the meta data for this gateway
*/
public function getSettings(array $meta = null)
{
$this->view = $this->makeView("settings", "default", str_replace(ROOTWEBDIR, "", dirname(__FILE__) . DS));
// Load the helpers required for this view
Loader::loadHelpers($this, array("Form", "Html"));
$this->view->set("meta", $meta);
return $this->view->fetch();
}
/**
* Validates the given meta (settings) data to be updated for this Gateway
*
* @param array $meta An array of meta (settings) data to be updated for this Gateway
* @return array The meta data to be updated in the database for this Gateway, or reset into the form on failure
*/
public function editSettings(array $meta)
{
// Verify meta data is valid
$rules = array(
'public_key' => array(
'empty' => array(
'rule' => "isEmpty",
'negate' => true,
'message' => Language::_("Brick.!error.public_key.valid", true),
'post_format' => 'trim'
)
),
'private_key' => array(
'empty' => array(
'rule' => "isEmpty",
'negate' => true,
'message' => Language::_("Brick.!error.private_key.valid", true),
'post_format' => 'trim'
)
),
'test_mode' => array(
'valid' => array(
'if_set' => true,
'rule' => array("in_array", array("true", "false")),
'message' => Language::_("Brick.!error.test_mode.valid", true)
)
)
);
// Set checkbox if not set
if (!isset($meta['test_mode']))
$meta['test_mode'] = "false";
$this->Input->setRules($rules);
// Validate the given meta data to ensure it meets the requirements
$this->Input->validates($meta);
// Return the meta data, no changes required regardless of success or failure for this Gateway
return $meta;
}
/**
* Returns an array of all fields to encrypt when storing in the database
*
* @return array An array of the field names to encrypt when storing in the database
*/
public function encryptableFields()
{
return array(
"public_key",
"private_key",
"public_test_key",
"private_test_key",
);
}
/**
* Sets the meta data for this particular Gateway
*
* @param array $meta An array of meta data to set for this Gateway
*/
public function setMeta(array $meta = null)
{
$this->meta = $meta;
}
/**
* @param $contact
* @return array
*/
private function prepareUserProfileData($contact)
{
return array(
'customer[city]' => $contact->city,
'customer[state]' => $contact->state,
'customer[address]' => $contact->address1,
'customer[country]' => $contact->country,
'customer[zip]' => $contact->zip,
'customer[username]' => $contact->email,
'customer[firstname]' => $contact->first_name,
'customer[lastname]' => $contact->last_name,
);
}
/**
* Validates the incoming POST/GET response from the gateway to ensure it is
* legitimate and can be trusted.
*
* @param array $get The GET data for this request
* @param array $post The POST data for this request
* @return array An array of transaction data, sets any errors using Input if the data fails to validate
* - client_id The ID of the client that attempted the payment
* - amount The amount of the payment
* - currency The currency of the payment
* - invoices An array of invoices and the amount the payment should be applied to (if any) including:
* - id The ID of the invoice to apply to
* - amount The amount to apply to the invoice
* - status The status of the transaction (approved, declined, void, pending, reconciled, refunded, returned)
* - reference_id The reference ID for gateway-only use with this transaction (optional)
* - transaction_id The ID returned by the gateway to identify this transaction
* - parent_transaction_id The ID returned by the gateway to identify this transaction's original transaction (in the case of refunds)
*/
public function validate(array $get, array $post)
{
if(!isset($get['data'])) return false;
$data = $this->decodeData($get['data']);
unset($get['data']);
list($company_id, $payment_method) = $get;
if ($payment_method != 'brick') return false;
$brick = $post['brick'];
$this->initPaymentwallConfigs();
$status = 'error';
$cardInfo = array(
'email' => $data['email'],
'amount' => $data['amount'],
'currency' => $data['currency'],
'description' => $data['description'],
'token' => $brick['token'],
'fingerprint' => $brick['fingerprint'],
);
$charge = new Paymentwall_Charge();
$charge->create($cardInfo);
$response = json_decode($charge->getPublicData(), true);
if ($charge->isSuccessful()) {
if ($charge->isCaptured()) {
// deliver a product
$status = 'approved';
} elseif ($charge->isUnderReview()) {
// decide on risk charge
$status = 'pending';
}
} else {
$_SESSION['brick_errors'] = $response['error']['message'];
}
return array(
'client_id' => $data['client_id'],
'amount' => $data['amount'],
'currency' => $data['currency'],
'status' => $status,
'reference_id' => null,
'transaction_id' => $charge->getId() ? $charge->getId() : false,
'parent_transaction_id' => null,
'invoices' => $data['invoices'] // optional
);
}
/**
* Returns data regarding a success transaction. This method is invoked when
* a client returns from the non-merchant gateway's web site back to Blesta.
*
* @param array $get The GET data for this request
* @param array $post The POST data for this request
* @return array An array of transaction data, may set errors using Input if the data appears invalid
* - client_id The ID of the client that attempted the payment
* - amount The amount of the payment
* - currency The currency of the payment
* - invoices An array of invoices and the amount the payment should be applied to (if any) including:
* - id The ID of the invoice to apply to
* - amount The amount to apply to the invoice
* - status The status of the transaction (approved, declined, void, pending, reconciled, refunded, returned)
* - transaction_id The ID returned by the gateway to identify this transaction
* - parent_transaction_id The ID returned by the gateway to identify this transaction's original transaction
*/
public function success(array $get, array $post)
{
if(isset($_SESSION['brick_errors']) && $_SESSION['brick_errors']){
$this->Input->setErrors(array(
array(
'general' => $_SESSION['brick_errors']
)
));
unset($_SESSION['brick_errors']);
}
return array(
'client_id' => $this->ifSet($post['client_id']),
'amount' => $this->ifSet($post['total']),
'currency' => $this->ifSet($post['currency_code']),
'invoices' => null,
'status' => "approved",
'transaction_id' => $this->ifSet($post['order_number']),
'parent_transaction_id' => null
);
}
/**
* Returns all HTML markup required to render an authorization and capture payment form
*
* @param array $contact_info An array of contact info including:
* - id The contact ID
* - client_id The ID of the client this contact belongs to
* - user_id The user ID this contact belongs to (if any)
* - contact_type The type of contact
* - contact_type_id The ID of the contact type
* - first_name The first name on the contact
* - last_name The last name on the contact
* - title The title of the contact
* - company The company name of the contact
* - address1 The address 1 line of the contact
* - address2 The address 2 line of the contact
* - city The city of the contact
* - state An array of state info including:
* - code The 2 or 3-character state code
* - name The local name of the country
* - country An array of country info including:
* - alpha2 The 2-character country code
* - alpha3 The 3-character country code
* - name The english name of the country
* - alt_name The local name of the country
* - zip The zip/postal code of the contact
* @param float $amount The amount to charge this contact
* @param array $invoice_amounts An array of invoices, each containing:
* - id The ID of the invoice being processed
* - amount The amount being processed for this invoice (which is included in $amount)
* @param array $options An array of options including:
* - description The Description of the charge
* - return_url The URL to redirect users to after a successful payment
* - recur An array of recurring info including:
* - amount The amount to recur
* - term The term to recur
* - period The recurring period (day, week, month, year, onetime) used in conjunction with term in order to determine the next recurring payment
* @return string HTML markup required to render an authorization and capture payment form
*/
public function buildProcess(array $contact_info, $amount, array $invoice_amounts = null, array $options = null)
{
$this->initPaymentwallConfigs();
$post_to = Configure::get("Blesta.gw_callback_url") . Configure::get("Blesta.company_id") . "/brick/";
$fields = array();
$contact = false;
// Set contact email address and phone number
if ($this->ifSet($contact_info['id'], false)) {
Loader::loadModels($this, array("Contacts"));
$contact = $this->Contacts->get($contact_info['id']);
} else {
return "Contact information invalid!";
}
$data = array(
'public_key' => Paymentwall_Config::getInstance()->getPublicKey(),
'amount' => $amount,
'merchant' => $this->ifSet($this->meta['merchant_name'], 'Blesta'),
'product_name' => $options['description'],
'currency' => $this->currency
);
$post_to .= "?data=" . $this->encodeData(array(
'client_id' => $contact->client_id,
'amount' => $amount,
'currency' => $this->currency,
'invoices' => $invoice_amounts,
'email' => $contact->email,
'description' => $options['description'],
));
$this->view = $this->makeView("process", "default", str_replace(ROOTWEBDIR, "", dirname(__FILE__) . DS));
$this->view->set("data", $data);
$this->view->set("post_to", $post_to);
$this->view->set("fields", $fields);
return $this->view->fetch();
}
/**
* @param array $data
* @return string
*/
private function encodeData($data = array())
{
return base64_encode(serialize($data));
}
/**
* @param $strData
* @return mixed
*/
private function decodeData($strData)
{
return unserialize(base64_decode($strData));
}
}
| paymentwall/module-blesta | src/components/gateways/nonmerchant/brick/brick.php | PHP | mit | 16,335 |
package org.butioy.framework.security;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
/**
* Created with IntelliJ IDEA.
* Author butioy
* Date 2015-09-18 22:33
*/
public class XSSHttpServletRequestWrapper extends HttpServletRequestWrapper {
HttpServletRequest orgRequest = null;
public XSSHttpServletRequestWrapper(HttpServletRequest request) {
super(request);
orgRequest = request;
}
/**
* 覆盖getParameter方法,将参数名和参数值都做xss过滤。
* 如果需要获得原始的值,则通过super.getParameterValues(name)来获取
* getParameterNames,getParameterValues和getParameterMap也可能需要覆盖
*/
@Override
public String getParameter(String name) {
String value = super.getParameter(xssEncode(name));
if(StringUtils.isNotBlank(value)) {
value = xssEncode(value);
}
return value;
}
/**
* 覆盖getHeader方法,将参数名和参数值都做xss过滤。
* 如果需要获得原始的值,则通过super.getHeaders(name)来获取
* getHeaderNames 也可能需要覆盖
*/
@Override
public String getHeader(String name) {
String value = super.getHeader(xssEncode(name));
if( StringUtils.isNotBlank(value) ) {
value = xssEncode(value);
}
return value;
}
/**
* 将容易引起xss漏洞的参数全部使用StringEscapeUtils转义
* @param value
* @return
*/
private static String xssEncode(String value) {
if (value == null || value.isEmpty()) {
return value;
}
value = StringEscapeUtils.escapeHtml4(value);
value = StringEscapeUtils.escapeEcmaScript(value);
return value;
}
/**
* 获取最原始的request
* @return
*/
public HttpServletRequest getOrgRequest() {
return orgRequest;
}
/**
* 获取最原始的request的静态方法
* @return
*/
public static HttpServletRequest getOrgRequest(HttpServletRequest request) {
if (request instanceof XSSHttpServletRequestWrapper) {
return ((XSSHttpServletRequestWrapper) request).getOrgRequest();
}
return request;
}
}
| butioy/webIM | butioy-framework-src/org/butioy/framework/security/XSSHttpServletRequestWrapper.java | Java | mit | 2,507 |
#include <Esp.h>
#include "FS.h"
#ifdef ESP32
#include <SPIFFS.h>
#endif
#include "iotsaFilesUpload.h"
#ifdef IOTSA_WITH_WEB
void IotsaFilesUploadMod::setup() {
}
static File _uploadFile;
static bool _uploadOK;
void
IotsaFilesUploadMod::uploadHandler() {
if (needsAuthentication("uploadfiles")) return;
HTTPUpload& upload = server->upload();
_uploadOK = false;
if(upload.status == UPLOAD_FILE_START){
String _uploadfilename = "/data/" + upload.filename;
IFDEBUG IotsaSerial.print("Uploading ");
IFDEBUG IotsaSerial.println(_uploadfilename);
if(SPIFFS.exists(_uploadfilename)) SPIFFS.remove(_uploadfilename);
_uploadFile = SPIFFS.open(_uploadfilename, "w");
//DBG_OUTPUT_PORT.print("Upload: START, filename: "); DBG_OUTPUT_PORT.println(upload.filename);
} else if(upload.status == UPLOAD_FILE_WRITE){
if(_uploadFile) _uploadFile.write(upload.buf, upload.currentSize);
//DBG_OUTPUT_PORT.print("Upload: WRITE, Bytes: "); DBG_OUTPUT_PORT.println(upload.currentSize);
} else if(upload.status == UPLOAD_FILE_END){
if(_uploadFile) {
_uploadFile.close();
_uploadOK = true;
}
//DBG_OUTPUT_PORT.print("Upload: END, Size: "); DBG_OUTPUT_PORT.println(upload.totalSize);
}
}
void
IotsaFilesUploadMod::uploadOkHandler() {
String message;
if (_uploadOK) {
IFDEBUG IotsaSerial.println("upload ok");
server->send(200, "text/plain", "OK");
} else {
IFDEBUG IotsaSerial.println("upload failed");
server->send(403, "text/plain", "FAIL");
}
}
void IotsaFilesUploadMod::uploadFormHandler() {
if (needsAuthentication("uploadfiles")) return;
String message = "<form method='POST' action='/upload' enctype='multipart/form-data'>Select file to upload:<input type='file' name='blob'><br>Filename:<input name='filename'><br><input type='submit' value='Update'></form>";
server->send(200, "text/html", message);
}
void IotsaFilesUploadMod::serverSetup() {
server->on("/upload", HTTP_POST, std::bind(&IotsaFilesUploadMod::uploadOkHandler, this), std::bind(&IotsaFilesUploadMod::uploadHandler, this));
server->on("/upload", HTTP_GET, std::bind(&IotsaFilesUploadMod::uploadFormHandler, this));
}
String IotsaFilesUploadMod::info() {
return "<p>See <a href=\"/upload\">/upload</a> for uploading new files.</p>";
}
void IotsaFilesUploadMod::loop() {
}
#endif // IOTSA_WITH_WEB | cwi-dis/iotsa | src/iotsaFilesUpload.cpp | C++ | mit | 2,362 |
<?php
declare(strict_types=1);
/*
* This file is part of the humbug/php-scoper package.
*
* Copyright (c) 2017 Théo FIDRY <theo.fidry@gmail.com>,
* Pádraic Brady <padraic.brady@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
return [
'meta' => [
'title' => 'Static method call statement of a class imported with a use statement in a namespace',
// Default values. If not specified will be the one used
'prefix' => 'Humbug',
'whitelist' => [],
'exclude-namespaces' => [],
'expose-global-constants' => true,
'expose-global-classes' => false,
'expose-global-functions' => true,
'exclude-constants' => [],
'exclude-classes' => [],
'exclude-functions' => [],
'registered-classes' => [],
'registered-functions' => [],
],
'Static method call statement of a class belonging to the global namespace imported via a use statement' => <<<'PHP'
<?php
namespace {
class Foo {}
}
namespace A {
use Foo;
Foo::main();
}
----
<?php
namespace Humbug;
class Foo
{
}
namespace Humbug\A;
use Humbug\Foo;
Foo::main();
PHP
,
'FQ static method call statement of a class belonging to the global namespace imported via a use statement' => <<<'PHP'
<?php
namespace {
class Foo {}
}
namespace A {
use Foo;
\Foo::main();
}
----
<?php
namespace Humbug;
class Foo
{
}
namespace Humbug\A;
use Humbug\Foo;
\Humbug\Foo::main();
PHP
,
'Static method call statement of a class belonging to the global namespace which has been whitelisted' => <<<'PHP'
<?php
namespace A;
use Closure;
Closure::bind();
----
<?php
namespace Humbug\A;
use Closure;
Closure::bind();
PHP
,
'FQ static method call statement of a class belonging to the global namespace which has been whitelisted' => <<<'PHP'
<?php
namespace A;
use Closure;
\Closure::bind();
----
<?php
namespace Humbug\A;
use Closure;
\Closure::bind();
PHP
,
];
| webmozart/php-scoper | specs/static-method/namespace-two-parts-with-single-level-use.php | PHP | mit | 2,100 |
<?php
class Auth_Model extends CoreApp\DataModel {
public function __construct() {
parent::__construct();
$this->PDO = $this->database->PDOConnection(CoreApp\AppConfig::getData("database=>autchenticationDB"));
$this->database->PDOClose();
}
public function getLocation($la, $lo) {
//Send request and receive json data by latitude and longitude
$url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.trim($la).','.trim($lo).'&sensor=false';
$json = @file_get_contents($url);
$data = json_decode($json);
$status = $data->status;
if($status=="OK"){
//Get address from json data
$location = $data->results[0]->formatted_address;
}
else{
$location = "We're not able to get your position.";
}
//Print address
echo $location;
}
public function newAttemptUser($data) {
//Creating the new Attempt User
$a = new CoreApp\AttemptUser();
//Setting it's properties
$a->aemail = $data["ema"];
$a->apassword = $data["passw"];
$a->devicekey = $data["dk"];
$a->lalo = $data["lalo"];
//XSS, INJECTION ECT...
$a->prepareCredentials();
//return to the attemptuser
return $a;
}
}
| LetsnetHungary/letsnet | App/_models/Auth_Model.php | PHP | mit | 1,452 |
package lua
type lValueArraySorter struct {
L *LState
Fn *LFunction
Values []LValue
}
func (lv lValueArraySorter) Len() int {
return len(lv.Values)
}
func (lv lValueArraySorter) Swap(i, j int) {
lv.Values[i], lv.Values[j] = lv.Values[j], lv.Values[i]
}
func (lv lValueArraySorter) Less(i, j int) bool {
if lv.Fn != nil {
lv.L.Push(lv.Fn)
lv.L.Push(lv.Values[i])
lv.L.Push(lv.Values[j])
lv.L.Call(2, 1)
return LVAsBool(lv.L.reg.Pop())
}
return lessThan(lv.L, lv.Values[i], lv.Values[j])
}
func newLTable(acap int, hcap int) *LTable {
if acap < 0 {
acap = 0
}
if hcap < 0 {
hcap = 0
}
tb := <able{
array: make([]LValue, 0, acap),
dict: make(map[LValue]LValue, hcap),
keys: nil,
k2i: nil,
Metatable: LNil,
}
return tb
}
func (tb *LTable) Len() int {
var prev LValue = LNil
for i := len(tb.array) - 1; i >= 0; i-- {
v := tb.array[i]
if prev == LNil && v != LNil {
return i + 1
}
prev = v
}
return 0
}
func (tb *LTable) Append(value LValue) {
tb.array = append(tb.array, value)
}
func (tb *LTable) Insert(i int, value LValue) {
if i > len(tb.array) {
tb.RawSetInt(i, value)
return
}
if i <= 0 {
tb.RawSet(LNumber(i), value)
return
}
i -= 1
tb.array = append(tb.array, LNil)
copy(tb.array[i+1:], tb.array[i:])
tb.array[i] = value
}
func (tb *LTable) MaxN() int {
for i := len(tb.array) - 1; i >= 0; i-- {
if tb.array[i] != LNil {
return i
}
}
return 0
}
func (tb *LTable) Remove(pos int) {
i := pos - 1
larray := len(tb.array)
switch {
case i >= larray:
return
case i == larray-1 || i < 0:
tb.array = tb.array[:larray-1]
default:
copy(tb.array[i:], tb.array[i+1:])
tb.array[larray-1] = nil
tb.array = tb.array[:larray-1]
}
}
func (tb *LTable) RawSet(key LValue, value LValue) {
switch v := key.(type) {
case LNumber:
if isArrayKey(v) {
index := int(v) - 1
alen := len(tb.array)
switch {
case index == alen:
tb.array = append(tb.array, value)
case index > alen:
for i := 0; i < (index - alen); i++ {
tb.array = append(tb.array, LNil)
}
tb.array = append(tb.array, value)
case index < alen:
tb.array[index] = value
}
return
}
}
tb.dict[key] = value
}
func (tb *LTable) RawSetInt(key int, value LValue) {
if key < 1 || key >= MaxArrayIndex {
tb.dict[LNumber(key)] = value
return
}
index := key - 1
alen := len(tb.array)
switch {
case index == alen:
tb.array = append(tb.array, value)
case index > alen:
for i := 0; i < (index - alen); i++ {
tb.array = append(tb.array, LNil)
}
tb.array = append(tb.array, value)
case index < alen:
tb.array[index] = value
}
}
func (tb *LTable) RawSetH(key LValue, value LValue) {
tb.dict[key] = value
}
func (tb *LTable) RawGet(key LValue) LValue {
switch v := key.(type) {
case LNumber:
if isArrayKey(v) {
index := int(v) - 1
if index >= len(tb.array) {
return LNil
}
return tb.array[index]
}
}
if v, ok := tb.dict[key]; ok {
return v
}
return LNil
}
func (tb *LTable) RawGetInt(key int) LValue {
index := int(key) - 1
if index >= len(tb.array) {
return LNil
}
return tb.array[index]
}
func (tb *LTable) RawGetH(key LValue) LValue {
if v, ok := tb.dict[key]; ok {
return v
}
return LNil
}
func (tb *LTable) ForEach(cb func(LValue, LValue)) {
for i, v := range tb.array {
if v != LNil {
cb(LNumber(i+1), v)
}
}
for k, v := range tb.dict {
if v != LNil {
cb(k, v)
}
}
}
func (tb *LTable) Next(key LValue) (LValue, LValue) {
// TODO: inefficient way
if key == LNil {
tb.keys = nil
tb.k2i = nil
key = LNumber(0)
}
if tb.keys == nil {
tb.keys = make([]LValue, len(tb.dict))
tb.k2i = make(map[LValue]int)
i := 0
for k, _ := range tb.dict {
tb.keys[i] = k
tb.k2i[k] = i
i++
}
}
if kv, ok := key.(LNumber); ok && isInteger(kv) && int(kv) >= 0 {
index := int(kv)
for ; index < len(tb.array); index++ {
if v := tb.array[index]; v != LNil {
return LNumber(index + 1), v
}
}
if index == len(tb.array) {
if len(tb.dict) == 0 {
tb.keys = nil
tb.k2i = nil
return LNil, LNil
}
key = tb.keys[0]
if v := tb.dict[key]; v != LNil {
return key, v
}
}
}
for i := tb.k2i[key] + 1; i < len(tb.dict); i++ {
key = tb.keys[i]
if v := tb.dict[key]; v != LNil {
return key, v
}
}
tb.keys = nil
tb.k2i = nil
return LNil, LNil
}
| evanphx/gopher-lua | table.go | GO | mit | 4,410 |
require("kaoscript/register");
var Type = require("@kaoscript/runtime").Type;
module.exports = function() {
var Shape = require("../export/export.class.default.ks")().Shape;
function foobar() {
if(arguments.length === 1 && Type.isString(arguments[0])) {
let __ks_i = -1;
let x = arguments[++__ks_i];
if(x === void 0 || x === null) {
throw new TypeError("'x' is not nullable");
}
else if(!Type.isString(x)) {
throw new TypeError("'x' is not of type 'String'");
}
return x;
}
else if(arguments.length === 1) {
let __ks_i = -1;
let x = arguments[++__ks_i];
if(x === void 0 || x === null) {
throw new TypeError("'x' is not nullable");
}
else if(!Type.isClassInstance(x, Shape)) {
throw new TypeError("'x' is not of type 'Shape'");
}
return x;
}
else {
throw new SyntaxError("Wrong number of arguments");
}
};
return {
foobar: foobar
};
}; | kaoscript/kaoscript | test/fixtures/compile/export/export.filter.func.import.js | JavaScript | mit | 914 |
/**
* Node class
* @param {object} value
* @constructor
*/
class Node {
constructor(value) {
this._data = value;
}
value() {
return this._data;
}
}
export default Node;
| jvalen/dstruct-algorithms-examples-js | src/Node/Node.js | JavaScript | mit | 190 |
<!DOCTYPE html>
<html lang="en">
<head>
@include('includes.head')
</head>
<body>
<div id="wrapper">
<header>
@include('includes.navbar')
</header>
<div class="container">
<div class="row">
<!-- main content -->
<div id="content" class="col-md-9">
@yield('content')
</div>
<!-- sidebar content -->
<div id="sidebarRight" class="col-md-3 sidebar">
@include('includes/messages')
@yield('sidebarRight')
</div>
</div>
</div>
</div>
<footer id="footer">
@include('includes.footer')
</footer>
</body>
</html>
| GrupaZero/platform_l4 | app/views/layouts/sidebarRight.blade.php | PHP | mit | 671 |
import URL from 'url';
import * as packageCache from '../../util/cache/package';
import { GitlabHttp } from '../../util/http/gitlab';
import type { GetReleasesConfig, ReleaseResult } from '../types';
import type { GitlabTag } from './types';
const gitlabApi = new GitlabHttp();
export const id = 'gitlab-tags';
export const customRegistrySupport = true;
export const defaultRegistryUrls = ['https://gitlab.com'];
export const registryStrategy = 'first';
const cacheNamespace = 'datasource-gitlab';
function getCacheKey(depHost: string, repo: string): string {
const type = 'tags';
return `${depHost}:${repo}:${type}`;
}
export async function getReleases({
registryUrl: depHost,
lookupName: repo,
}: GetReleasesConfig): Promise<ReleaseResult | null> {
const cachedResult = await packageCache.get<ReleaseResult>(
cacheNamespace,
getCacheKey(depHost, repo)
);
// istanbul ignore if
if (cachedResult) {
return cachedResult;
}
const urlEncodedRepo = encodeURIComponent(repo);
// tag
const url = URL.resolve(
depHost,
`/api/v4/projects/${urlEncodedRepo}/repository/tags?per_page=100`
);
const gitlabTags = (
await gitlabApi.getJson<GitlabTag[]>(url, {
paginate: true,
})
).body;
const dependency: ReleaseResult = {
sourceUrl: URL.resolve(depHost, repo),
releases: null,
};
dependency.releases = gitlabTags.map(({ name, commit }) => ({
version: name,
gitRef: name,
releaseTimestamp: commit?.created_at,
}));
const cacheMinutes = 10;
await packageCache.set(
cacheNamespace,
getCacheKey(depHost, repo),
dependency,
cacheMinutes
);
return dependency;
}
| singapore/renovate | lib/datasource/gitlab-tags/index.ts | TypeScript | mit | 1,669 |
var AllDrinks =
[{"drinkName": "Alexander",
"recipe": "Shake all ingredients with ice and strain contents into a cocktail glass. Sprinkle nutmeg on top and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/a/ac/Gin_Alexander_%284371721753%29.jpg/220px-Gin_Alexander_%284371721753%29.jpg",
"alcohol": ["Brandy","Liqueur",],
"ingredients": ["1 oz cognac","1 oz white crème de cacao","1 oz light cream",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 8, "wWarm": 7, "wHot": 5},
"precipValue": {"pNone": 2, "pSome": 6},
"seasonValue":{"sSpr": 7, "sSum": 4, "sFal": 5, "sWin": 3},
"dayValue": {"dMTRS": 2, "dW": 5, "dFS": 7},
"timeValue": {"tMrn": 1, "tAft": 2, "tNt": 5, "wSleep": 5}
}
},
{"drinkName": "Americano",
"recipe": "Pour the Campari and vermouth over ice into glass, add a splash of soda water and garnish with half orange slice.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/2/2b/Americano_cocktail_at_Nightwood_Restaurant.jpg/220px-Americano_cocktail_at_Nightwood_Restaurant.jpg",
"alcohol": ["Vermouth","Liqueur",], "ingredients": ["1 oz Campari","1 oz red vermouth","A splash of soda water",],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 4, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 6, "pSome": 2},
"seasonValue":{"sSpr": 2, "sSum": 7, "sFal": 8, "sWin": 3},
"dayValue": {"dMTRS": 3, "dW": 5, "dFS": 8},
"timeValue": {"tMrn": 1, "tAft": 3, "tNt": 6, "wSleep": 7}
}
},
{"drinkName": "Aperol Spritz",
"recipe": "Add 3 parts prosecco, 2 parts Aperol and top up with soda water, garnish with a slice of orange and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/5/59/Aperol_Spritz_2014a.jpg/220px-Aperol_Spritz_2014a.jpg",
"alcohol": ["Champagne",],
"ingredients": ["3 parts Prosecco","2 parts Aperol","1 part Soda Water",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 5, "wWarm": 5, "wHot": 8},
"precipValue": {"pNone": 7, "pSome": 4},
"seasonValue":{"sSpr": 4, "sSum": 5, "sFal": 6, "sWin": 2},
"dayValue": {"dMTRS": 2, "dW": 5, "dFS": 8},
"timeValue": {"tMrn": 2, "tAft": 5, "tNt": 9, "wSleep": 5}
}
},
{"drinkName": "Appletini",
"recipe": "Mix in a shaker, then pour into a chilled glass. Garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/2/28/Appletini.jpg/220px-Appletini.jpg",
"alcohol": ["Vodka",],
"ingredients": ["1½ oz (3 parts) Vodka","½ oz (1 part) Apple schnapps / Calvados","½ oz (1 part) Cointreau",],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 4, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 6, "pSome": 4},
"seasonValue":{"sSpr": 3, "sSum": 7, "sFal": 6, "sWin": 2},
"dayValue": {"dMTRS": 3, "dW": 5, "dFS": 7},
"timeValue": {"tMrn": 2, "tAft": 6, "tNt": 8, "wSleep": 4}
}
},
{"drinkName": "Aviation",
"recipe": "Add all ingredients into cocktail shaker filled with ice. Shake well and strain into cocktail glass. Garnish with a cherry.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/4/4f/Aviation_Cocktail.jpg/220px-Aviation_Cocktail.jpg",
"alcohol": ["Gin","Liqueur",],
"ingredients": ["1½ oz gin","½ oz lemon juice","½ oz maraschino liqueur",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 5, "wWarm": 7, "wHot": 9},
"precipValue": {"pNone": 6, "pSome": 4},
"seasonValue":{"sSpr": 4, "sSum": 8, "sFal": 7, "sWin": 3},
"dayValue": {"dMTRS": 4, "dW": 6, "dFS": 9},
"timeValue": {"tMrn": 1, "tAft": 4, "tNt": 7, "wSleep": 5}}},
{"drinkName": "B-52",
"recipe": "Layer ingredients into a shot glass. Serve with a stirrer.",
"image": "https://upload.wikimedia.org/wikipedia/commons/3/3a/Cocktail_B52.jpg",
"alcohol": ["Liqueur","Brandy",],
"ingredients": ["¾ oz Kahlúa","¾ oz Baileys Irish Cream","¾ oz Grand Marnier",],
"drinkRating": {
"weatherValue": {"wCold": 4, "wMod": 6, "wWarm": 7, "wHot": 5},
"precipValue": {"pNone": 4, "pSome": 6},
"seasonValue":{"sSpr": 3, "sSum": 6, "sFal": 7, "sWin": 2},
"dayValue": {"dMTRS": 2, "dW": 3, "dFS": 6},
"timeValue": {"tMrn": 2, "tAft": 4, "tNt": 7, "wSleep": 6}
}
},
{"drinkName": "Bellini",
"recipe": "Pour peach purée into chilled flute, add sparkling wine. Stir gently.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d5/Bellini_Cipriani%2C_Macaroni_Grill%2C_Dunwoody_GA.jpg/220px-Bellini_Cipriani%2C_Macaroni_Grill%2C_Dunwoody_GA.jpg",
"alcohol": ["Champagne",],
"ingredients": ["3½ oz (2 parts) Prosecco","2 oz (1 part) fresh peach purée",],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 3, "wWarm": 5, "wHot": 8},
"precipValue": {"pNone": 6, "pSome": 2},
"seasonValue":{"sSpr": 2, "sSum": 5, "sFal": 6, "sWin": 1},
"dayValue": {"dMTRS": 3, "dW": 5, "dFS": 8},
"timeValue": {"tMrn": 2, "tAft": 6, "tNt": 8, "wSleep": 4}
}
},
{"drinkName": "Bijou",
"recipe": "Stir in mixing glass with ice and strain",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Bijou_Cocktail.jpg/220px-Bijou_Cocktail.jpg",
"alcohol": ["Gin","Vermouth",],
"ingredients": ["1 part gin","1 part green Chartreuse","1 part sweet vermouth","Dash orange bitters",],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 2, "wWarm": 4, "wHot": 5},
"precipValue": {"pNone": 3, "pSome": 2},
"seasonValue":{"sSpr": 3, "sSum": 5, "sFal": 2, "sWin": 1},
"dayValue": {"dMTRS": 2, "dW": 4, "dFS": 5},
"timeValue": {"tMrn": 0, "tAft": 3, "tNt": 5, "wSleep": 0}
}
},
{"drinkName": "Black Russian",
"recipe": "Pour the ingredients into an old fashioned glass filled with ice cubes. Stir gently.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c5/Blackrussian.jpg/220px-Blackrussian.jpg",
"alcohol": ["Vodka","Liqueur",],
"ingredients": ["2 oz (5 parts) Vodka","¾ oz (2 parts) Coffee liqueur",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 5, "wWarm": 6, "wHot": 7},
"precipValue": {"pNone": 3, "pSome": 6},
"seasonValue":{"sSpr": 3, "sSum": 6, "sFal": 7, "sWin": 2},
"dayValue": {"dMTRS": 3, "dW": 4, "dFS": 7},
"timeValue": {"tMrn": 2, "tAft": 5, "tNt": 8, "wSleep": 4}
}
},
{"drinkName": "Black Velvet",
"recipe": "fill a tall champagne flute, halfway with chilled sparkling wine and float stout beer on top of the wine",
"image": "https://upload.wikimedia.org/wikipedia/en/thumb/f/f4/Black_Velvet_Cocktail_Layered.jpg/220px-Black_Velvet_Cocktail_Layered.jpg",
"alcohol": ["Champagne","Wine",],
"ingredients": ["Beer","Sparkling wine",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 5, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 4, "pSome": 6},
"seasonValue":{"sSpr": 3, "sSum": 5, "sFal": 6, "sWin": 2},
"dayValue": {"dMTRS": 4, "dW": 6, "dFS": 8},
"timeValue": {"tMrn": 2, "tAft": 6, "tNt": 8, "wSleep": 0}
}
},
{"drinkName": "Bloody Mary",
"recipe": "Add dashes of Worcestershire Sauce, Tabasco, salt and pepper into highball glass, then pour all ingredients into highball with ice cubes. Stir gently.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/1/12/Bloody_Mary.jpg/220px-Bloody_Mary.jpg",
"alcohol": ["Vodka",],
"ingredients": ["1½ oz (3 parts) Vodka","3 oz (6 parts) Tomato juice","½ oz (1 part) Lemon juice","2 to 3 dashes of Worcestershire Sauce","Tabasco","Celery salt","Pepper",],
"drinkRating": {
"weatherValue": {"wCold": 8, "wMod": 7, "wWarm": 7, "wHot": 6},
"precipValue": {"pNone": 4, "pSome": 9},
"seasonValue":{"sSpr": 6, "sSum": 5, "sFal": 8, "sWin": 10},
"dayValue": {"dMTRS": 8, "dW": 8, "dFS": 10},
"timeValue": {"tMrn": 10, "tAft": 8, "tNt": 5, "wSleep": 5}
}
},
{"drinkName": "Blue Hawaii",
"recipe": "Combine all ingredients with ice, stir or shake, then pour into a hurricane glass with the ice. Garnish with pineapple or orange slice.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c7/Bluehawaiian.jpg/220px-Bluehawaiian.jpg",
"alcohol": ["Vodka","Rum","Liqueur",],
"ingredients": ["3/4 oz light rum","3/4 oz vodka","1/2 oz Curaçao","3 oz pineapple juice","1 oz Sweet and Sour",],
"drinkRating": {
"weatherValue": {"wCold": 0, "wMod": 3, "wWarm": 7, "wHot": 9},
"precipValue": {"pNone": 4, "pSome": 6},
"seasonValue":{"sSpr": 2, "sSum": 6, "sFal": 7, "sWin": 1},
"dayValue": {"dMTRS": 4, "dW": 6, "dFS": 8},
"timeValue": {"tMrn": 3, "tAft": 6, "tNt": 8, "wSleep": 1}
}
},
{"drinkName": "Blue Lagoon",
"recipe": "pour vodka and blue curacao in a shaker with ice, shake well & strain into ice filled highball glass, top with lemonade, garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/7/73/Blue_Lagoon_at_the_Mandarin_Oriental%2C_Washington_DC.jpg/220px-Blue_Lagoon_at_the_Mandarin_Oriental%2C_Washington_DC.jpg",
"alcohol": ["Vodka",],
"ingredients": ["1½ oz Vodka","1 oz Blue Curacao","3½ oz Lemonade","1 orange slice.","Ice cubes",],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 4, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 3, "pSome": 2},
"seasonValue":{"sSpr": 5, "sSum": 8, "sFal": 7, "sWin": 3},
"dayValue": {"dMTRS": 5, "dW": 7, "dFS": 9},
"timeValue": {"tMrn": 0, "tAft": 5, "tNt": 7, "wSleep": 3}
}
},
{"drinkName": "Bramble",
"recipe": "Fill glass with crushed ice. Build gin, lemon juice and simple syrup over. Stir, and then pour blackberry liqueur over in a circular fashion to create marbling effect. Garnish with two blackberries and lemon slice.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/2/22/Bramble_Cocktail1.jpg/220px-Bramble_Cocktail1.jpg",
"alcohol": ["Gin","Liqueur",],
"ingredients": ["1½ oz gin","½ oz lemon juice","½ oz simple syrup","½ oz Creme de Mure(blackberry liqueur)",],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 3, "wWarm": 5, "wHot": 8},
"precipValue": {"pNone": 7, "pSome": 2},
"seasonValue":{"sSpr": 4, "sSum": 7, "sFal": 6, "sWin": 2},
"dayValue": {"dMTRS": 3, "dW": 5, "dFS": 8},
"timeValue": {"tMrn": 1, "tAft": 6, "tNt": 8, "wSleep": 3}
}
},
{"drinkName": "Brandy Alexander",
"recipe": "Shake and strain into a chilled cocktail glass. Sprinkle with fresh ground nutmeg.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/c/ca/Brandy_alexander.jpg/220px-Brandy_alexander.jpg",
"alcohol": ["Brandy",],
"ingredients": ["1 oz (1 part) Cognac","1 oz (1 part) Crème de cacao (brown)","1 oz (1 part) Fresh cream",],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 5, "wWarm": 7, "wHot": 9},
"precipValue": {"pNone": 3, "pSome": 2},
"seasonValue":{"sSpr": 5, "sSum": 8, "sFal": 7, "sWin": 2},
"dayValue": {"dMTRS": 3, "dW": 6, "dFS": 9},
"timeValue": {"tMrn": 3, "tAft": 7, "tNt": 8, "wSleep": 4}
}
},
{"drinkName": "Bronx",
"recipe": "Pour into cocktail shaker all ingredients with ice cubes, shake well. Strain in chilled cocktail or martini glass.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/3/3c/Bronx_%28cocktail%29.jpg/220px-Bronx_%28cocktail%29.jpg",
"alcohol": ["Gin","Vermouth",],
"ingredients": ["1 oz (6 parts) Gin","½ oz (3 parts) Sweet Red Vermouth","½ oz (2 parts) Dry Vermouth","½ oz (3 parts) Orange juice",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 5, "wWarm": 7, "wHot": 9},
"precipValue": {"pNone": 6, "pSome": 4},
"seasonValue":{"sSpr": 4, "sSum": 8, "sFal": 7, "sWin": 3},
"dayValue": {"dMTRS": 4, "dW": 6, "dFS": 8},
"timeValue": {"tMrn": 2, "tAft": 6, "tNt": 7, "wSleep": 3}
}
},
{"drinkName": "Bucks Fizz",
"recipe": "* Pour the orange juice into glass and top up Champagne. Stir gently, garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/Buck%27s_Fizz_on_Christmas_Morning_%288491638980%29.jpg/220px-Buck%27s_Fizz_on_Christmas_Morning_%288491638980%29.jpg",
"alcohol": ["Champagne",],
"ingredients": ["2 oz (1 part) orange juice","3½ oz (2 parts) Champagne",],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 5, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 5, "pSome": 2},
"seasonValue":{"sSpr": 5, "sSum": 8, "sFal": 6, "sWin": 3},
"dayValue": {"dMTRS": 5, "dW": 6, "dFS": 8},
"timeValue": {"tMrn": 4, "tAft": 6, "tNt": 7, "wSleep": 5}
}
},
{"drinkName": "Casesar",
"recipe": "Worcestershire Sauce, Sriracha or lime Cholula, lemon juice, olive juice, salt and pepper. Rim with celery salt, fill pint glass with ice - add ingredients - shake passionately & garnish. ",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a7/Caesar_Cocktail.JPG/220px-Caesar_Cocktail.JPG",
"alcohol": ["Vodka",],
"ingredients": ["3 parts Vodka","9 Clamato juice", "Cap of Lemon juice", "2 to 3 dashes of Worcestershire Sauce", "Sriracha", "Celery salt", "Pepper",],
"drinkRating": {
"weatherValue": {"wCold": 8, "wMod": 7, "wWarm": 7, "wHot": 6},
"precipValue": {"pNone": 4, "pSome": 9},
"seasonValue":{"sSpr": 6, "sSum": 5, "sFal": 8, "sWin": 10},
"dayValue": {"dMTRS": 9, "dW": 9, "dFS": 10},
"timeValue": {"tMrn": 10, "tAft": 8, "tNt": 5, "wSleep": 5}
}
},
{"drinkName": "Caipirinha",
"recipe": "Place lime and sugar into old fashioned glass and muddle (mash the two ingredients together using a muddler or a wooden spoon). Fill the glass with crushed ice and add the Cachaça.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/9/99/15-09-26-RalfR-WLC-0048.jpg/220px-15-09-26-RalfR-WLC-0048.jpg",
"alcohol": [],
"ingredients": ["2 oz cachaça","Half a lime cut into 4 wedges","2 teaspoons sugar",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 4, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 8, "pSome": 5},
"seasonValue":{"sSpr": 5, "sSum": 8, "sFal": 6, "sWin": 3},
"dayValue": {"dMTRS": 4, "dW": 6, "dFS": 9},
"timeValue": {"tMrn": 3, "tAft": 7, "tNt": 6, "wSleep": 2}
}
},
{"drinkName": "Cape Codder",
"recipe": "Build all ingredients in a highball glass filled with ice. Garnish with lime wedge.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/3/31/Cape_Codder%2C_Tommy_Doyles_Irish_Pub%2C_Hyannis_MA.jpg/220px-Cape_Codder%2C_Tommy_Doyles_Irish_Pub%2C_Hyannis_MA.jpg",
"alcohol": ["Vodka",],
"ingredients": ["Vodka","Cranberry juice",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 4, "wWarm": 6, "wHot": 9},
"precipValue": {"pNone": 3, "pSome": 5},
"seasonValue":{"sSpr": 4, "sSum": 7, "sFal": 6, "sWin": 2},
"dayValue": {"dMTRS": 5, "dW": 6, "dFS": 7},
"timeValue": {"tMrn": 2, "tAft": 6, "tNt": 7, "wSleep": 4}
}
},
{"drinkName": "Chimayó Cocktail",
"recipe": "Pour the tequila and unfiltered apple cider into glass over ice. Add the lemon juice and creme de cassis and stir. Garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/2/2c/Chimayo_Cocktail_at_Rancho_de_Chimayo%2C_Chimayo_NM.jpg/220px-Chimayo_Cocktail_at_Rancho_de_Chimayo%2C_Chimayo_NM.jpg",
"alcohol": ["Tequila",],
"ingredients": ["1½ oz Tequila","1 oz apple cider","1/4 oz lemon juice","1/4 oz creme de cassis",],
"drinkRating": {
"weatherValue": {"wCold": 4, "wMod": 5, "wWarm": 7, "wHot": 8},
"precipValue": {"pNone": 4, "pSome": 2},
"seasonValue":{"sSpr": 5, "sSum": 8, "sFal": 7, "sWin": 3},
"dayValue": {"dMTRS": 4, "dW": 6, "dFS": 9},
"timeValue": {"tMrn": 4, "tAft": 7, "tNt": 8, "wSleep": 5}
}
},
{"drinkName": "Clover Club Cocktail",
"recipe": "Dry shake ingredients to emulsify, add ice, shake and served straight up.",
"image": "https://upload.wikimedia.org/wikipedia/en/thumb/9/99/Cloverclub.jpg/220px-Cloverclub.jpg",
"alcohol": ["Gin",],
"ingredients": ["1½ oz Gin","½ oz Lemon Juice","½ oz Raspberry Syrup","1 Egg White",],
"drinkRating": {
"weatherValue": {"wCold": 5, "wMod": 6, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 6, "pSome": 4},
"seasonValue":{"sSpr": 5, "sSum": 8, "sFal": 6, "sWin": 4},
"dayValue": {"dMTRS": 5, "dW": 7, "dFS": 10},
"timeValue": {"tMrn": 1, "tAft": 6, "tNt": 8, "wSleep": 5}
}
},
{"drinkName": "Colombia",
"recipe": "Shake the vodka and citrus juices in a mixer, then strain into the glass. Slide the grenadine down one side of the glass, where it will sink to the bottom. Slide the curacao down the other side, to lie between the vodka and grenadine.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/3/35/Columbia-cocktail.jpg/220px-Columbia-cocktail.jpg",
"alcohol": ["Vodka","Liqueur","Brandy",],
"ingredients": ["2 parts vodka or brandy","1 part blue Curaçao","1 part grenadine","1 part lemon juice","6 parts orange juice",],
"drinkRating": {
"weatherValue": {"wCold": 4, "wMod": 5, "wWarm": 7, "wHot": 9},
"precipValue": {"pNone": 8, "pSome": 3},
"seasonValue":{"sSpr": 6, "sSum": 9, "sFal": 7, "sWin": 4},
"dayValue": {"dMTRS": 5, "dW": 6, "dFS": 8},
"timeValue": {"tMrn": 3, "tAft": 7, "tNt": 6, "wSleep": 4}
}
},
{"drinkName": "Cosmopolitan",
"recipe": "Add all ingredients into cocktail shaker filled with ice. Shake well and double strain into large cocktail glass. Garnish with lime wheel.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c0/Cosmopolitan_%285076906532%29.jpg/220px-Cosmopolitan_%285076906532%29.jpg",
"alcohol": ["Vodka",],
"ingredients": ["1½ oz Vodka Citron","½ oz Cointreau","½ oz Fresh lime juice","1 oz Cranberry juice",],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 4, "wWarm": 7, "wHot": 9},
"precipValue": {"pNone": 5, "pSome": 2},
"seasonValue":{"sSpr": 6, "sSum": 9, "sFal": 8, "sWin": 4},
"dayValue": {"dMTRS": 4, "dW": 5, "dFS": 8},
"timeValue": {"tMrn": 2, "tAft": 5, "tNt": 7, "wSleep": 4}
}
},
{"drinkName": "Cuba Libre",
"recipe": "Build all ingredients in a Collins glass filled with ice. Garnish with lime wedge.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/5/5d/15-09-26-RalfR-WLC-0056.jpg/220px-15-09-26-RalfR-WLC-0056.jpg",
"alcohol": ["Rum",],
"ingredients": ["1¾ oz Cola","2 oz Light rum","½ oz Fresh lime juice",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 5, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 7, "pSome": 4},
"seasonValue":{"sSpr": 4, "sSum": 7, "sFal": 6, "sWin": 1},
"dayValue": {"dMTRS": 6, "dW": 7, "dFS": 9},
"timeValue": {"tMrn": 4, "tAft": 7, "tNt": 8, "wSleep": 5}
}
},
{"drinkName": "Dark N Stormy",
"recipe": "In a highball glass filled with ice add 2 oz dark rum and top with ginger beer. Garnish with lime wedge.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/0/00/Dark_n_Stormy.jpg/220px-Dark_n_Stormy.jpg",
"alcohol": ["Rum",],
"ingredients": ["2 oz dark rum","3½ oz Ginger beer",],
"drinkRating": {
"weatherValue": {"wCold": 4, "wMod": 5, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 2, "pSome": 8},
"seasonValue":{"sSpr": 5, "sSum": 7, "sFal": 4, "sWin": 3},
"dayValue": {"dMTRS": 4, "dW": 6, "dFS": 9},
"timeValue": {"tMrn": 1, "tAft": 5, "tNt": 7, "wSleep": 4}
}
},
{"drinkName": "El Presidente",
"recipe": "stir well with ice, then strain into glass. Garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/a/ac/El_Presidente_Cocktail.jpg/220px-El_Presidente_Cocktail.jpg",
"alcohol": ["Rum","Liqueur","Vermouth",],
"ingredients": ["Two parts rum","One part curaçao","One part dry vermouth","Dash grenadine",],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 4, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 7, "pSome": 5},
"seasonValue":{"sSpr": 7, "sSum": 9, "sFal": 6, "sWin": 4},
"dayValue": {"dMTRS": 5, "dW": 6, "dFS": 7},
"timeValue": {"tMrn": 1, "tAft": 5, "tNt": 7, "wSleep": 2}
}
},
{"drinkName": "Espresso Martini",
"recipe": "Pour ingredients into shaker filled with ice, shake vigorously, and strain into chilled martini glass",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/8/8c/Espresso-martini.jpg/220px-Espresso-martini.jpg",
"alcohol": ["Vodka",],
"ingredients": ["2 oz Vodka","½ oz Kahlua","Sugar syrup","1 shot strong Espresso",],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 3, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 4, "pSome": 2},
"seasonValue":{"sSpr": 5, "sSum": 8, "sFal": 6, "sWin": 4},
"dayValue": {"dMTRS": 7, "dW": 6, "dFS": 8},
"timeValue": {"tMrn": 8, "tAft": 7, "tNt": 5, "wSleep": 1}
}
},
{"drinkName": "Fizzy Apple Cocktail",
"recipe": "Combine all three ingredients into a chilled glass and serve with ice and garnish.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d7/Cup02.jpg/220px-Cup02.jpg",
"alcohol": ["Vodka",],
"ingredients": ["1 shot Apple Vodka","1/2 cup Apple Juice","1/2 cup Lemonade",],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 2, "wWarm": 6, "wHot": 7},
"precipValue": {"pNone": 6, "pSome": 4},
"seasonValue":{"sSpr": 5, "sSum": 8, "sFal": 6, "sWin": 1},
"dayValue": {"dMTRS": 5, "dW": 6, "dFS": 9},
"timeValue": {"tMrn": 1, "tAft": 6, "tNt": 7, "wSleep": 2}
}
},
{"drinkName": "Flaming Doctor Pepper",
"recipe": "Layer the two spirits in the shot glass, with the high-proof liquor on top. Light the shot and allow it to burn; then extinguish it by dropping it into the beer glass. Drink immediately.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/5/5b/Flaming_dr_pepper_%28101492893%29.jpg/220px-Flaming_dr_pepper_%28101492893%29.jpg",
"alcohol": ["Liqueur",],
"ingredients": ["1 pint (~13 parts) beer","3 parts Amaretto","1 part high-proof liquor",],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 4, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 4, "pSome": 1},
"seasonValue":{"sSpr": 6, "sSum": 8, "sFal": 7, "sWin": 1},
"dayValue": {"dMTRS": 4, "dW": 3, "dFS": 7},
"timeValue": {"tMrn": 0, "tAft": 5, "tNt": 8, "wSleep": 2}
}
},
{"drinkName": "Flaming Volcano",
"recipe": "Combine all ingredients with 2 scoops of crushed ice in a blender, blend briefly, then pour into the volcano bowl. Pour some rum into the central crater of the volcano bowl and light it.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/3/35/Flaming_Volcano.jpg/220px-Flaming_Volcano.jpg",
"alcohol": ["Rum","Brandy",],
"ingredients": ["1 oz light rum","1 oz brandy","1 oz overproof rum (e.g. Bacardi 151)","4 oz orange juice","2 oz lemon juice","2 oz almond flavored syrup",],
"drinkRating": {
"weatherValue": {"wCold": 5, "wMod": 6, "wWarm": 7, "wHot": 9},
"precipValue": {"pNone": 8, "pSome": 3},
"seasonValue":{"sSpr": 5, "sSum": 8, "sFal": 7, "sWin": 1},
"dayValue": {"dMTRS": 3, "dW": 5, "dFS": 8},
"timeValue": {"tMrn": 0, "tAft": 5, "tNt": 8, "wSleep": 2}
}
},
{"drinkName": "French 75",
"recipe": "Combine gin, syrup, and lemon juice in a cocktail shaker filled with ice. Shake vigorously and strain into an iced champagne glass. Top up with Champagne. Stir gently.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/0/0b/French_75.jpg/220px-French_75.jpg",
"alcohol": ["Champagne","Gin",],
"ingredients": ["1 oz gin","2 dashes simple syrup","½ oz lemon juice","2 oz Champagne",],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 3, "wWarm": 5, "wHot": 6},
"precipValue": {"pNone": 6, "pSome": 2},
"seasonValue":{"sSpr": 5, "sSum": 8, "sFal": 7, "sWin": 3},
"dayValue": {"dMTRS": 4, "dW": 6, "dFS": 8},
"timeValue": {"tMrn": 2, "tAft": 6, "tNt": 8, "wSleep": 1}
}
},
{"drinkName": "Gibson",
"recipe": "*Stir well in a shaker with ice, then strain into a chilled martini glass. Garnish and serve",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/0/08/Gibson_cocktail.jpg/220px-Gibson_cocktail.jpg",
"alcohol": ["Gin","Vermouth",],
"ingredients": ["2 oz gin","½ oz dry vermouth",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 4, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 5, "pSome": 3},
"seasonValue":{"sSpr": 6, "sSum": 8, "sFal": 7, "sWin": 2},
"dayValue": {"dMTRS": 5, "dW": 6, "dFS": 8},
"timeValue": {"tMrn": 2, "tAft": 6, "tNt": 7, "wSleep": 3}
}
},
{"drinkName": "Gimlet",
"recipe": "Mix and serve. Garnish with a slice of lime",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/2/21/Gimlet_cocktail.jpg/220px-Gimlet_cocktail.jpg",
"alcohol": ["Gin","Vodka",],
"ingredients": ["Five parts gin","One part simple syrup","One part sweetened lime juice",],
"drinkRating": {
"weatherValue": {"wCold": 4, "wMod": 5, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 7, "pSome": 2},
"seasonValue":{"sSpr": 6, "sSum": 7, "sFal": 5, "sWin": 3},
"dayValue": {"dMTRS": 4, "dW": 6, "dFS": 9},
"timeValue": {"tMrn": 1, "tAft": 5, "tNt": 8, "wSleep": 2}
}
},
{"drinkName": "Gin & Tonic",
"recipe": "In a glass filled with ice cubes, add gin and tonic.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d4/Gin_and_Tonic_with_ingredients.jpg/220px-Gin_and_Tonic_with_ingredients.jpg",
"alcohol": ["Gin",],
"ingredients": ["Gin", "Tonic"],
"drinkRating": {
"weatherValue": {"wCold": 6, "wMod": 6, "wWarm": 8, "wHot": 9},
"precipValue": {"pNone": 9, "pSome": 5},
"seasonValue":{"sSpr": 8, "sSum": 9, "sFal": 5, "sWin": 2},
"dayValue": {"dMTRS": 8, "dW": 10, "dFS": 9},
"timeValue": {"tMrn": 2, "tAft": 7, "tNt": 8, "wSleep": 0}
}
},
{"drinkName": "Godfather",
"recipe": "Pour all ingredients directly into old fashioned glass filled with ice cubes. Stir gently.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/8/80/Godfather_cocktail.jpg/220px-Godfather_cocktail.jpg",
"alcohol": ["Whiskey","Liqueur",],
"ingredients": ["1 oz scotch whisky","1 oz Disaronno",],
"drinkRating": {
"weatherValue": {"wCold": 9, "wMod": 8, "wWarm": 7, "wHot": 6},
"precipValue": {"pNone": 6, "pSome": 8},
"seasonValue":{"sSpr": 7, "sSum": 8, "sFal": 8, "sWin": 9},
"dayValue": {"dMTRS": 7, "dW": 8, "dFS": 4},
"timeValue": {"tMrn": 8, "tAft": 8, "tNt": 4, "wSleep": 2}
}
},
{"drinkName": "Golden Dream",
"recipe": "Shake with cracked ice. Strain into glass and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/1/15/Godlen-Dream_Mixed_Drink_Cocktail_%282360538105%29.jpg/220px-Godlen-Dream_Mixed_Drink_Cocktail_%282360538105%29.jpg",
"alcohol": ["Liqueur",],
"ingredients": ["¾ oz (2 parts) Galliano","¾ oz (2 parts) Triple Sec","¾ oz (2 parts) Fresh orange juice","½ oz (1 part) Fresh cream",],
"drinkRating": {
"weatherValue": {"wCold": 7, "wMod": 7, "wWarm": 7, "wHot": 7},
"precipValue": {"pNone": 7, "pSome": 5},
"seasonValue":{"sSpr": 8, "sSum": 8, "sFal": 5, "sWin": 5},
"dayValue": {"dMTRS": 5, "dW": 4, "dFS": 7},
"timeValue": {"tMrn": 10, "tAft": 9, "tNt": 5, "wSleep": 0}
}
},
{"drinkName": "Grasshopper",
"recipe": "Pour ingredients into a cocktail shaker with ice. Shake briskly and then strain into a chilled cocktail glass.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/7/7b/Grasshopper_cocktail.jpg/220px-Grasshopper_cocktail.jpg",
"alcohol": ["Liqueur",],
"ingredients": ["1 oz Crème de menthe (green)","1 oz Crème de cacao (white)","1 oz Fresh cream",],
"drinkRating": {
"weatherValue": {"wCold": 5, "wMod": 6, "wWarm": 6, "wHot": 7},
"precipValue": {"pNone": 4, "pSome": 8},
"seasonValue":{"sSpr": 7, "sSum": 8, "sFal": 7, "sWin": 5},
"dayValue": {"dMTRS": 5, "dW": 5, "dFS": 8},
"timeValue": {"tMrn": 2, "tAft": 9, "tNt": 8, "wSleep": 0}
}
},
{"drinkName": "Greyhound",
"recipe": "Mix gin and juice, pour over ice in Old Fashioned glass",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/5/58/Greyhound_Cocktail.jpg/220px-Greyhound_Cocktail.jpg",
"alcohol": ["Gin",],
"ingredients": ["2 oz (1 parts) Gin","7 oz (4 parts) Grapefruit juice",],
"drinkRating": {
"weatherValue": {"wCold": 4, "wMod": 4, "wWarm": 5, "wHot": 7},
"precipValue": {"pNone": 4, "pSome": 2},
"seasonValue":{"sSpr": 8, "sSum": 8, "sFal": 8, "sWin": 6},
"dayValue": {"dMTRS": 8, "dW": 6, "dFS": 6},
"timeValue": {"tMrn": 8, "tAft": 4, "tNt": 8, "wSleep": 4}
}
},
{"drinkName": "Harvey Wallbanger",
"recipe": "Stir the vodka and orange juice with ice in the glass, then float the Galliano on top. Garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/4/44/Harvey_Wallbanger.jpg/220px-Harvey_Wallbanger.jpg",
"alcohol": ["Vodka","Liqueur",],
"ingredients": ["1½ oz (3 parts) Vodka","½ oz (1 part) Galliano","3 oz (6 parts) fresh orange juice",],
"drinkRating": {
"weatherValue": {"wCold": 6, "wMod": 7, "wWarm": 8, "wHot": 9},
"precipValue": {"pNone": 5, "pSome": 5},
"seasonValue":{"sSpr": 8, "sSum": 9, "sFal": 6, "sWin": 4},
"dayValue": {"dMTRS": 8, "dW": 7, "dFS": 7},
"timeValue": {"tMrn": 9, "tAft": 8, "tNt": 6, "wSleep": 0}
}
},
{"drinkName": "Horses Neck",
"recipe": "Pour brandy and ginger ale directly into highball glass with ice cubes. Stir gently. Garnish with lemon zest. If desired, add dashes of Angostura Bitter.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d9/Horse%27s_Neck_cocktail.jpg/220px-Horse%27s_Neck_cocktail.jpg",
"alcohol": ["Brandy",],
"ingredients": ["1½ oz (1 part) Brandy","1¾ oz (3 parts) Ginger ale","Dash of Angostura bitter",],
"drinkRating": {
"weatherValue": {"wCold": 4, "wMod": 5, "wWarm": 6, "wHot": 7},
"precipValue": {"pNone": 4, "pSome": 4},
"seasonValue":{"sSpr": 5, "sSum": 7, "sFal": 9, "sWin": 9},
"dayValue": {"dMTRS": 7, "dW": 6, "dFS": 5},
"timeValue": {"tMrn": 2, "tAft": 8, "tNt": 8, "wSleep": 0}
}
},
{"drinkName": "Huckleberry Hound",
"recipe": "Shake ingredients with ice, then pour into the glass and serve over ice - garnish with Montana Huckleberries",
"image": "http://www.trbimg.com/img-538660e1/turbine/ctn-liquor-cabinet-maggie-mcflys-20140528-001/1050/1050x591",
"alcohol": ["Vodka",],
"ingredients": ["2 oz. 44 North Huckleberry Vodka", "1 oz. Huckleberry syrup", "Lemonade or Limeade"],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 7, "wWarm": 9, "wHot": 10},
"precipValue": {"pNone": 9, "pSome": 4},
"seasonValue":{"sSpr": 7, "sSum": 9, "sFal": 6, "sWin": 4},
"dayValue": {"dMTRS": 8, "dW": 8, "dFS": 9},
"timeValue": {"tMrn": 0, "tAft": 6, "tNt": 9, "wSleep": 0}
}
},
{"drinkName": "Hurricane",
"recipe": "Shake ingredients with ice, then pour into the glass and serve over ice.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e4/Hurricane_cocktail.jpg/220px-Hurricane_cocktail.jpg",
"alcohol": ["Rum",],
"ingredients": ["One part dark rum","One part white rum","Half part over proofed rum","Passion fruit syrup","Lemon juice",],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 3, "wWarm": 8, "wHot": 9},
"precipValue": {"pNone": 8, "pSome": 4},
"seasonValue":{"sSpr": 7, "sSum": 9, "sFal": 6, "sWin": 4},
"dayValue": {"dMTRS": 1, "dW": 5, "dFS": 9},
"timeValue": {"tMrn": 0, "tAft": 5, "tNt": 8, "wSleep": 0}
}
},
{"drinkName": "Irish Car Bomb",
"recipe": "The whiskey is floated on top of the Irish cream in a shot glass, and the shot glass is then dropped into the stout",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/4/4b/Irish_Car_Bomb.jpg/220px-Irish_Car_Bomb.jpg",
"alcohol": ["Whiskey","Liqueur",],
"ingredients": ["1/2 oz whiskey","1/2 oz Irish cream liqueur","1/2 pint stout",],
"drinkRating": {
"weatherValue": {"wCold": 4, "wMod": 4, "wWarm": 5, "wHot": 6},
"precipValue": {"pNone": 7, "pSome": 6},
"seasonValue":{"sSpr": 7, "sSum": 8, "sFal": 6, "sWin": 3},
"dayValue": {"dMTRS": 1, "dW": 5, "dFS": 8},
"timeValue": {"tMrn": 0, "tAft": 4, "tNt": 9, "wSleep": 6}
}
},
{"drinkName": "Irish Coffee",
"recipe": "Heat the coffee, whiskey and sugar; do not boil. Pour into glass and top with cream; serve hot.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/6/61/Irish_coffee_glass.jpg/220px-Irish_coffee_glass.jpg",
"alcohol": ["Whiskey",],
"ingredients": ["1½ oz (2 parts) Irish whiskey","3 oz (4 parts) hot coffee","1 oz (1½ parts) fresh cream","1tsp brown sugar",],
"drinkRating": {
"weatherValue": {"wCold": 10, "wMod": 8, "wWarm": 2, "wHot": 1},
"precipValue": {"pNone": 3, "pSome": 9},
"seasonValue":{"sSpr": 5, "sSum": 5, "sFal": 8, "sWin": 9},
"dayValue": {"dMTRS": 8, "dW": 5, "dFS": 6},
"timeValue": {"tMrn": 10, "tAft": 8, "tNt": 2, "wSleep": 2}
}
},
{"drinkName": "Jack Rose",
"recipe": "Traditionally shaken into a chilled glass, garnished, and served straight up.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/f/fa/15-09-26-RalfR-WLC-0259.jpg/220px-15-09-26-RalfR-WLC-0259.jpg",
"alcohol": ["Brandy",],
"ingredients": ["2 parts applejack","1 part lemon or lime juice","1/2 part grenadine",],
"drinkRating": {
"weatherValue": {"wCold": 6, "wMod": 4, "wWarm": 5, "wHot": 5},
"precipValue": {"pNone": 4, "pSome": 4},
"seasonValue":{"sSpr": 5, "sSum": 4, "sFal": 8, "sWin": 8},
"dayValue": {"dMTRS": 6, "dW": 4, "dFS": 4},
"timeValue": {"tMrn": 1, "tAft": 5, "tNt": 6, "wSleep": 0}
}
},
{"drinkName": "Japanese Slipper",
"recipe": "Shake together in a mixer with ice. Strain into glass, garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c7/Japanese_slipper.jpg/220px-Japanese_slipper.jpg",
"alcohol": ["Liqueur",],
"ingredients": ["1 oz (1 part) Midori","1 oz (1 part) cointreau","1 oz (1 part) lemon juice",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 3, "wWarm": 5, "wHot": 7},
"precipValue": {"pNone": 7, "pSome": 4},
"seasonValue":{"sSpr": 6, "sSum": 8, "sFal": 3, "sWin": 4},
"dayValue": {"dMTRS": 8, "dW": 6, "dFS": 6},
"timeValue": {"tMrn": 1, "tAft": 8, "tNt": 8, "wSleep": 0}
}
},
{"drinkName": "Kalimotxo",
"recipe": "Stir together over plenty of ice.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/7/7c/Porr%C3%B3n_1.jpg/220px-Porr%C3%B3n_1.jpg",
"alcohol": ["Wine",],
"ingredients": ["One part red wine","One part cola",],
"drinkRating": {
"weatherValue": {"wCold": 6, "wMod": 7, "wWarm": 7, "wHot": 7},
"precipValue": {"pNone": 6, "pSome": 9},
"seasonValue":{"sSpr": 7, "sSum": 8, "sFal": 8, "sWin": 7},
"dayValue": {"dMTRS": 9, "dW": 10, "dFS": 4},
"timeValue": {"tMrn": 1, "tAft": 7, "tNt": 8, "wSleep": 0}
}
},
{"drinkName": "Kamikaze",
"recipe": "Shake all ingredients together with ice. Strain into glass, garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/6/61/Kamikaze.jpg/220px-Kamikaze.jpg",
"alcohol": ["Vodka","Liqueur",],
"ingredients": ["1 oz vodka","1 oz triple sec","1 oz lime juice",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 5, "wWarm": 5, "wHot": 5},
"precipValue": {"pNone": 6, "pSome": 6},
"seasonValue":{"sSpr": 4, "sSum": 6, "sFal": 4, "sWin": 6},
"dayValue": {"dMTRS": 0, "dW": 4, "dFS": 9},
"timeValue": {"tMrn": 0, "tAft": 6, "tNt": 7, "wSleep": 0}
}
},
{"drinkName": "Kentucky Corpse Reviver",
"recipe": "Shake ingredients together with ice, and strain into a glass. Garnish with mint sprig.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/8/8f/Glass02.jpg/50px-Glass02.jpg",
"alcohol": ["Whiskey",],
"ingredients": ["1 part Bourbon","1 part Lillet Blanc","1 part Lemon Juice","1 part Cointreau",],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 3, "wWarm": 6, "wHot": 8},
"precipValue": {"pNone": 3, "pSome": 9},
"seasonValue":{"sSpr": 10, "sSum": 8, "sFal": 3, "sWin": 3},
"dayValue": {"dMTRS": 2, "dW": 6, "dFS": 8},
"timeValue": {"tMrn": 2, "tAft": 5, "tNt": 7, "wSleep": 2}
}
},
{"drinkName": "Kir",
"recipe": "Add the crème de cassis to the bottom of the glass, then top up with wine.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c3/Kir_cocktail.jpg/220px-Kir_cocktail.jpg",
"alcohol": ["Wine",],
"ingredients": ["3 oz (9 parts) white wine","½ oz (1 part) crème de cassis",],
"drinkRating": {
"weatherValue": {"wCold": 4, "wMod": 4, "wWarm": 8, "wHot": 8},
"precipValue": {"pNone": 5, "pSome": 8},
"seasonValue":{"sSpr": 8, "sSum": 7, "sFal": 4, "sWin": 4},
"dayValue": {"dMTRS": 8, "dW": 7, "dFS": 7},
"timeValue": {"tMrn": 5, "tAft": 5, "tNt": 4, "wSleep": 2}
}
},
{"drinkName": "Kir Royal",
"recipe": "*Add the crème de cassis to the bottom of the glass, then top up champagne.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e7/Kir_Royal.jpg/220px-Kir_Royal.jpg",
"alcohol": ["Champagne",],
"ingredients": ["3 oz champagne","½ oz crème de cassis",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 6, "wWarm": 6, "wHot": 6},
"precipValue": {"pNone": 5, "pSome": 8},
"seasonValue":{"sSpr": 5, "sSum": 5, "sFal": 7, "sWin": 8},
"dayValue": {"dMTRS": 8, "dW": 7, "dFS": 7},
"timeValue": {"tMrn": 10, "tAft": 7, "tNt": 2, "wSleep": 0}
}
},
{"drinkName": "Long Island Iced Tea",
"recipe": "Add all ingredients into highball glass filled with ice. Stir gently. Garnish with lemon spiral. Serve with straw.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/4/45/Long_Island_Iced_Teas.jpg/220px-Long_Island_Iced_Teas.jpg",
"alcohol": ["Gin","Tequila","Vodka","Rum","Liqueur",],
"ingredients": ["½ oz Tequila","½ oz Vodka","½ oz White rum","½ oz Triple sec","½ oz Gin","¾ oz Lemon juice","1 oz Gomme Syrup","1 dash of Cola",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 4, "wWarm": 8, "wHot": 9},
"precipValue": {"pNone": 8, "pSome": 5},
"seasonValue":{"sSpr": 4, "sSum": 9, "sFal": 8, "sWin": 2},
"dayValue": {"dMTRS": 2, "dW": 6, "dFS": 10},
"timeValue": {"tMrn": 2, "tAft": 5, "tNt": 9, "wSleep": 0}
}
},
{"drinkName": "Lynchburg Lemonade",
"recipe": "Shake first 3 ingredients with ice and strain into ice-filled glass. Top with the lemonade or lemon-lime. Add ice and stir. Garnish with lemon slices and cherries.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/0/0c/Lynchburg_Lemonade%2C_Grindhouse_Killer_Burgers%2C_Atlanta_GA.jpg/220px-Lynchburg_Lemonade%2C_Grindhouse_Killer_Burgers%2C_Atlanta_GA.jpg",
"alcohol": ["Whiskey",],
"ingredients": ["1¼ oz Tennessee whiskey", "¾ oz Triple sec", "2 oz Sour mix", "lemon-lime", "lemon slice", "cherries" ],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 2, "wWarm": 5, "wHot": 10},
"precipValue": {"pNone": 9, "pSome": 7},
"seasonValue":{"sSpr": 7, "sSum": 9, "sFal": 1, "sWin": 1},
"dayValue": {"dMTRS": 3, "dW": 6, "dFS": 9},
"timeValue": {"tMrn": 2, "tAft": 9, "tNt": 8, "wSleep": 0}
}
},
{"drinkName": "Mai Tai",
"recipe": "Shake all ingredients with ice. Strain into glass. Garnish and serve with straw.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/Mai_Tai.jpg/220px-Mai_Tai.jpg",
"alcohol": ["Rum","Liqueur",],
"ingredients": ["1½ oz white rum","¾ oz dark rum","½ oz orange curaçao","½ oz Orgeat syrup","½ oz fresh lime juice",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 5, "wWarm": 8, "wHot": 9},
"precipValue": {"pNone": 3, "pSome": 3},
"seasonValue":{"sSpr": 6, "sSum": 10, "sFal": 4, "sWin": 2},
"dayValue": {"dMTRS": 2, "dW": 7, "dFS": 8},
"timeValue": {"tMrn": 1, "tAft": 6, "tNt": 7, "wSleep": 0}
}
},
{"drinkName": "Manhattan",
"recipe": "Stirred over ice, strained into a chilled glass, garnished, and served up.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/de/Manhattan_Cocktail2.jpg/220px-Manhattan_Cocktail2.jpg",
"alcohol": ["Whiskey","Vermouth",],
"ingredients": ["2 oz rye","¾ oz Sweet red vermouth","Dash Angostura bitters",],
"drinkRating": {
"weatherValue": {"wCold": 7, "wMod": 8, "wWarm": 8, "wHot": 8},
"precipValue": {"pNone": 6, "pSome": 9},
"seasonValue":{"sSpr": 7, "sSum": 4, "sFal": 8, "sWin": 8},
"dayValue": {"dMTRS": 7, "dW": 8, "dFS": 5},
"timeValue": {"tMrn": 2, "tAft": 9, "tNt": 8, "wSleep": 2}
}
},
{"drinkName": "Margarita",
"recipe": "Rub the rim of the glass with the lime slice to make the salt stick. Shake the other ingredients with ice, then carefully pour into the glass.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/3/37/MargaritaReal.jpg/220px-MargaritaReal.jpg",
"alcohol": ["Tequila",],
"ingredients": ["1 oz (7 parts) tequila","¾ oz (4 parts) Cointreau","½ oz (3 parts) lime juice",],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 4, "wWarm": 8, "wHot": 10},
"precipValue": {"pNone": 9, "pSome": 2},
"seasonValue":{"sSpr": 8, "sSum": 10, "sFal": 3, "sWin": 3},
"dayValue": {"dMTRS": 5, "dW": 8, "dFS": 9},
"timeValue": {"tMrn": 1, "tAft": 7, "tNt": 9, "wSleep": 1}
}
},
{"drinkName": "Martini",
"recipe": "Straight: Pour all ingredients into mixing glass with ice cubes. Stir well. Strain in chilled martini cocktail glass. Squeeze oil from lemon peel onto the drink, or garnish with olive.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/8/80/15-09-26-RalfR-WLC-0084.jpg/220px-15-09-26-RalfR-WLC-0084.jpg",
"alcohol": ["Gin","Vermouth",],
"ingredients": ["2 oz (6 parts) gin","½ oz (1 parts) dry vermouth",],
"drinkRating": {
"weatherValue": {"wCold": 7, "wMod": 7, "wWarm": 8, "wHot": 7},
"precipValue": {"pNone": 7, "pSome": 8},
"seasonValue":{"sSpr": 4, "sSum": 6, "sFal": 8, "sWin": 8},
"dayValue": {"dMTRS": 2, "dW": 8, "dFS": 8},
"timeValue": {"tMrn": 1, "tAft": 3, "tNt": 8, "wSleep": 1}
}
},
{"drinkName": "Mimosa",
"recipe": "Ensure both ingredients are well chilled, then mix into the glass. Serve cold.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Pool-side_Mimosas_at_The_Standard_Hotel.jpg/220px-Pool-side_Mimosas_at_The_Standard_Hotel.jpg",
"alcohol": ["Champagne",],
"ingredients": ["7 oz champagne","2 oz orange juice",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 6, "wWarm": 8, "wHot": 8},
"precipValue": {"pNone": 8, "pSome": 4},
"seasonValue":{"sSpr": 9, "sSum": 8, "sFal": 5, "sWin": 4},
"dayValue": {"dMTRS": 6, "dW": 7, "dFS": 9},
"timeValue": {"tMrn": 9, "tAft": 4, "tNt": 3, "wSleep": 0}
}
},
{"drinkName": "Mint Julep",
"recipe": "In a highball glass gently muddle the mint, sugar and water. Fill the glass with cracked ice, add Bourbon and stir well until the glass is well frosted. Garnish with a mint sprig.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/5/55/Mint_Julep_im_Silberbecher.jpg/220px-Mint_Julep_im_Silberbecher.jpg",
"alcohol": ["Whiskey",],
"ingredients": ["2 oz Bourbon whiskey","4 mint leaves","1 teaspoon powdered sugar","2 teaspoons water", "mint sprig"],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 3, "wWarm": 6, "wHot": 9},
"precipValue": {"pNone": 10, "pSome": 2},
"seasonValue":{"sSpr": 9, "sSum": 8, "sFal": 3, "sWin": 1},
"dayValue": {"dMTRS": 3, "dW": 7, "dFS": 8},
"timeValue": {"tMrn": 10, "tAft": 8, "tNt": 3, "wSleep": 1}
}
},
{"drinkName": "Monkey Gland",
"recipe": "Shake well over ice cubes in a shaker, strain into a chilled cocktail glass.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/5/58/Monkey_Gland_%2811677703163%29.jpg/220px-Monkey_Gland_%2811677703163%29.jpg",
"alcohol": ["Gin",],
"ingredients": ["2 oz gin","1 oz orange juice","2 drops absinthe","2 drops grenadine",],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 3, "wWarm": 9, "wHot": 7},
"precipValue": {"pNone": 6, "pSome": 3},
"seasonValue":{"sSpr": 8, "sSum": 6, "sFal": 7, "sWin": 1},
"dayValue": {"dMTRS": 3, "dW": 8, "dFS": 7},
"timeValue": {"tMrn": 4, "tAft": 6, "tNt": 5, "wSleep": 3}
}
},
{"drinkName": "Moscow Mule",
"recipe": "Combine vodka and ginger beer in a highball glass filled with ice. Add lime juice. Stir gently. Garnish with a lime slice and sprig of mint on the brim of the copper mug.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a7/Moscow_Mule.jpg/220px-Moscow_Mule.jpg",
"alcohol": ["Vodka",],
"ingredients": ["1½ oz (9 parts) vodka","¼ oz (1 part) lime juice","1¾ oz (24 parts) ginger beer","lime slice", "sprig of mint"],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 5, "wWarm": 8, "wHot": 9},
"precipValue": {"pNone": 6, "pSome": 4},
"seasonValue":{"sSpr": 9, "sSum": 8, "sFal": 4, "sWin": 2},
"dayValue": {"dMTRS": 6, "dW": 7, "dFS": 8},
"timeValue": {"tMrn": 2, "tAft": 8, "tNt": 9, "wSleep": 4}
}
},
{"drinkName": "Negroni",
"recipe": "Stir into glass over ice, garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c6/Negroni_served_in_Vancouver_BC.jpg/220px-Negroni_served_in_Vancouver_BC.jpg",
"alcohol": ["Gin","Vermouth","Liqueur",],
"ingredients": ["1 oz gin","1 oz sweet red vermouth","1 oz campari",],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 4, "wWarm": 6, "wHot": 7},
"precipValue": {"pNone": 7, "pSome": 2},
"seasonValue":{"sSpr": 6, "sSum": 8, "sFal": 5, "sWin": 3},
"dayValue": {"dMTRS": 3, "dW": 5, "dFS": 7},
"timeValue": {"tMrn": 2, "tAft": 8, "tNt": 6, "wSleep": 3}
}
},
{"drinkName": "Nikolaschka",
"recipe": "Pour cognac into brandy snifter, place lemon disk across the top of the glass and top with sugar and coffee.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e7/Cocktail_-_Nikolaschka.jpg/220px-Cocktail_-_Nikolaschka.jpg",
"alcohol": ["Brandy",],
"ingredients": ["Cognac","Coffee powder","Powdered sugar","Lemon disk, peeled",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 9, "wWarm": 7, "wHot": 6},
"precipValue": {"pNone": 8, "pSome": 5},
"seasonValue": {"sSpr": 7, "sSum": 4, "sFal": 8, "sWin": 3},
"dayValue": {"dMTRS": 5, "dW": 4, "dFS": 7},
"timeValue": {"tMrn": 9, "tAft": 6, "tNt": 5, "wSleep": 1}
}
},
{"drinkName": "Old Fashioned",
"recipe": "Place sugar cube in old fashioned glass and saturate with bitters, add a dash of plain water. Muddle until dissolved. Fill the glass with ice cubes and add whiskey. Garnish with orange twist, and a cocktail cherry.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/6/6f/Whiskey_Old_Fashioned1.jpg/220px-Whiskey_Old_Fashioned1.jpg",
"alcohol": ["Whiskey",],
"ingredients": ["1½ oz Bourbon or Rye whiskey","2 dashes Angostura bitters","1 sugar cube","Few dashes plain water","orange twist", "cocktail cherry"],
"drinkRating": {
"weatherValue": {"wCold": 7, "wMod": 9, "wWarm": 5, "wHot": 4},
"precipValue": {"pNone": 4, "pSome": 7},
"seasonValue": {"sSpr": 4, "sSum": 5, "sFal": 8, "sWin": 7},
"dayValue": {"dMTRS": 9, "dW": 7, "dFS": 5},
"timeValue": {"tMrn": 2, "tAft": 6, "tNt": 9, "wSleep": 8}
}
},
{"drinkName": "Orgasm",
"recipe": "Build all ingredients over ice in an old fashioned glass or shot glass.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/4/4f/Orgasm_%28cocktail%29.jpg/220px-Orgasm_%28cocktail%29.jpg",
"alcohol": ["Liqueur",],
"ingredients": ["3/4 oz. Amaretto","3/4 oz. Kahlúa","3/4 oz. Baileys Irish Cream",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 4, "wWarm": 6, "wHot": 7},
"precipValue": {"pNone": 8, "pSome": 2},
"seasonValue": {"sSpr": 8, "sSum": 9, "sFal": 4, "sWin": 3},
"dayValue": {"dMTRS": 3, "dW": 6, "dFS": 8},
"timeValue": {"tMrn": 4, "tAft": 7, "tNt": 6, "wSleep": 3}
}
},
{"drinkName": "Paradise",
"recipe": "Shake together over ice. Strain into cocktail glass and serve chilled.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b3/Paradise_cocktail.jpg/220px-Paradise_cocktail.jpg",
"alcohol": ["Gin","Brandy",],
"ingredients": ["1 oz (7 parts) gin","¾ oz (4 parts) apricot brandy","½ oz (3 parts) orange juice",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 5, "wWarm": 7, "wHot": 8},
"precipValue": {"pNone": 6, "pSome": 4},
"seasonValue": {"sSpr": 7, "sSum": 8, "sFal": 5, "sWin": 2},
"dayValue": {"dMTRS": 4, "dW": 5, "dFS": 9},
"timeValue": {"tMrn": 6, "tAft": 7, "tNt": 4, "wSleep": 3}
}
},
{"drinkName": "Piña Colada",
"recipe": "Mix with crushed ice in blender until smooth. Pour into chilled glass, garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b2/Pi%C3%B1a_Colada.jpg/220px-Pi%C3%B1a_Colada.jpg",
"alcohol": ["Rum",],
"ingredients": ["1 oz (one part) white rum","1 oz (one part) coconut milk","3 oz (3 parts) pineapple juice",],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 4, "wWarm": 8, "wHot": 10},
"precipValue": {"pNone": 9, "pSome": 1},
"seasonValue": {"sSpr": 8, "sSum": 10, "sFal": 4, "sWin": 1},
"dayValue": {"dMTRS": 2, "dW": 5, "dFS": 9},
"timeValue": {"tMrn": 8, "tAft": 9, "tNt": 4, "wSleep": 1}
}
},
{"drinkName": "Pink Lady",
"recipe": "Shake ingredients very well with ice and strain into cocktail glass. Garnish with a cherry.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a2/Pink_Lady_with_a_twist_of_lime%2C_in_a_cocktail_glass.jpg/220px-Pink_Lady_with_a_twist_of_lime%2C_in_a_cocktail_glass.jpg",
"alcohol": ["Gin",],
"ingredients": ["1.5 oz. gin","4 dashes grenadine","1 egg white","cherry"],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 7, "wWarm": 8, "wHot": 5},
"precipValue": {"pNone": 3, "pSome": 5},
"seasonValue": {"sSpr": 8, "sSum": 7, "sFal": 6, "sWin": 4},
"dayValue": {"dMTRS": 3, "dW": 7, "dFS": 8},
"timeValue": {"tMrn": 6, "tAft": 8, "tNt": 4, "wSleep": 2}
}
},
{"drinkName": "Planters Punch",
"recipe": "Pour all ingredients, except the bitters, into shaker filled with ice. Shake well. Pour into large glass, filled with ice. Add Angostura bitters, on top. Garnish with cocktail cherry and pineapple.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/1/10/Planters_Punch_2.jpg/220px-Planters_Punch_2.jpg",
"alcohol": ["Rum",],
"ingredients": ["1½ oz Dark rum","1 oz Fresh orange juice","1 oz Fresh pineapple juice","¾ oz Fresh lemon juice","½ oz Grenadine syrup","½ oz Sugar syrup","3 or 4 dashes Angostura bitters",],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 2, "wWarm": 5, "wHot": 9},
"precipValue": {"pNone": 9, "pSome": 1},
"seasonValue": {"sSpr": 9, "sSum": 8, "sFal": 3, "sWin": 1},
"dayValue": {"dMTRS": 4, "dW": 6, "dFS": 8},
"timeValue": {"tMrn": 6, "tAft": 9, "tNt": 5, "wSleep": 3}
}
},
{"drinkName": "Porto Flip",
"recipe": "Shake ingredients together in a mixer with ice. Strain into glass, garnish and serve",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d2/Porto_Flip.jpg/220px-Porto_Flip.jpg",
"alcohol": ["Wine","Brandy",],
"ingredients": ["½ oz (3 parts) brandy","1½ oz (8 parts) port","½ oz (2 parts) egg yolk",],
"drinkRating": {
"weatherValue": {"wCold": 7, "wMod": 9, "wWarm": 5, "wHot": 3},
"precipValue": {"pNone": 3, "pSome": 7},
"seasonValue": {"sSpr": 5, "sSum": 4, "sFal": 9, "sWin": 8},
"dayValue": {"dMTRS": 3, "dW": 9, "dFS": 7},
"timeValue": {"tMrn": 2, "tAft": 7, "tNt": 9, "wSleep": 6}
}
},
{"drinkName": "Rickey",
"recipe": "Combine spirit, lime and shell in a highball or wine glass. Add ice, stir and then add sparkling mineral water.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/8/8d/Gin_Rickey.jpg/220px-Gin_Rickey.jpg",
"alcohol": ["Gin","Whiskey",],
"ingredients": ["2oz bourbon, rye whiskey, or gin","Half of a lime","Sparkling mineral water",],
"drinkRating": {
"weatherValue": {"wCold": 5, "wMod": 7, "wWarm": 6, "wHot": 3},
"precipValue": {"pNone": 2, "pSome": 6},
"seasonValue": {"sSpr": 9, "sSum": 7, "sFal": 7, "sWin": 3},
"dayValue": {"dMTRS": 4, "dW": 6, "dFS": 7},
"timeValue": {"tMrn": 2, "tAft": 4, "tNt": 8, "wSleep": 7}
}
},
{"drinkName": "Rob Roy",
"recipe": "Stirred over ice, strained into a chilled glass, garnished, and served straight up, or mixed in rocks glass, filled with ice.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e8/15-09-26-RalfR-WLC-0266.jpg/220px-15-09-26-RalfR-WLC-0266.jpg",
"alcohol": ["Whiskey","Vermouth",],
"ingredients": ["1½ oz Scotch whisky","¾ oz Sweet vermouth","Dash Angostura bitters",],
"drinkRating": {
"weatherValue": {"wCold": 8, "wMod": 9, "wWarm": 5, "wHot": 2},
"precipValue": {"pNone": 2, "pSome": 6},
"seasonValue": {"sSpr": 5, "sSum": 3, "sFal": 9, "sWin": 8},
"dayValue": {"dMTRS": 5, "dW": 8, "dFS": 7},
"timeValue": {"tMrn": 1, "tAft": 3, "tNt": 7, "wSleep": 8}
}
},
{"drinkName": "Rose",
"recipe": "Shake together in a cocktail shaker, then strain into chilled glass. Garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b8/Rose_%28cocktail%29.jpg/220px-Rose_%28cocktail%29.jpg",
"alcohol": ["Vermouth","Brandy"],
"ingredients": ["1½ oz (2 parts) dry vermouth","¾ oz (1 parts) Kirsch","3 Dashes Strawberry syrup",],
"drinkRating": {
"weatherValue": {"wCold": 8, "wMod": 9, "wWarm": 5, "wHot": 2},
"precipValue": {"pNone": 1, "pSome": 7},
"seasonValue": {"sSpr": 5, "sSum": 3, "sFal": 7, "sWin": 8},
"dayValue": {"dMTRS": 5, "dW": 6, "dFS": 8},
"timeValue": {"tMrn": 2, "tAft": 4, "tNt": 8, "wSleep": 7}
}
},
{"drinkName": "Rusty Nail",
"recipe": "Pour all ingredients directly into old-fashioned glass filled with ice. Stir gently. Garnish with a lemon twist. Serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/9/9a/Rusty_Nail_at_Sparta_Restaurant%2C_Bedford_MA.jpg/220px-Rusty_Nail_at_Sparta_Restaurant%2C_Bedford_MA.jpg",
"alcohol": ["Whiskey",],
"ingredients": ["7.2 oz Scotch Whisky","¾ oz Drambuie",],
"drinkRating": {
"weatherValue": {"wCold": 9, "wMod": 6, "wWarm": 3, "wHot": 1},
"precipValue": {"pNone": 2, "pSome": 7},
"seasonValue": {"sSpr": 2, "sSum": 1, "sFal": 6, "sWin": 8},
"dayValue": {"dMTRS": 4, "dW": 7, "dFS": 6},
"timeValue": {"tMrn": 1, "tAft": 3, "tNt": 6, "wSleep": 8}
}
},
{"drinkName": "Sake Bomb",
"recipe": "The shot of sake is dropped into the beer, causing it to fizz violently. The drink should then be consumed immediately.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/7/71/Sake_bomb_-_man_pounds_table_with_fist.jpg/220px-Sake_bomb_-_man_pounds_table_with_fist.jpg",
"alcohol": ["Wine",],
"ingredients": ["1 pint (~16 parts) beer","1 shot (1.5 parts) sake",],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 7, "wWarm": 5, "wHot": 3},
"precipValue": {"pNone": 6, "pSome": 3},
"seasonValue": {"sSpr": 6, "sSum": 7, "sFal": 8, "sWin": 2},
"dayValue": {"dMTRS": 2, "dW": 6, "dFS": 9},
"timeValue": {"tMrn": 2, "tAft": 5, "tNt": 9, "wSleep": 1}
}
},
{"drinkName": "Salty Dog",
"recipe": "Shake gin and grapefruit juice in cocktail shaker. Strain into a salt-rimmed highball glass.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c2/Salty_Dog.jpg/220px-Salty_Dog.jpg",
"alcohol": ["Gin","Vodka",],
"ingredients": ["1½ oz gin or vodka","3½ oz grapefruit juice",],
"drinkRating": {
"weatherValue": {"wCold": 4, "wMod": 8, "wWarm": 7, "wHot": 6},
"precipValue": {"pNone": 2, "pSome": 8},
"seasonValue": {"sSpr": 5, "sSum": 5, "sFal": 7, "sWin": 6},
"dayValue": {"dMTRS": 8, "dW": 7, "dFS": 4},
"timeValue": {"tMrn": 7, "tAft": 8, "tNt": 5, "wSleep": 6}
}
},
{"drinkName": "Screwdriver",
"recipe": "Mix in a highball glass with ice. Garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/4/45/Screwdriver%2C_Birmingham-Shuttlesworth_International_Airport%2C_Birmingham_AL.jpg/220px-Screwdriver%2C_Birmingham-Shuttlesworth_International_Airport%2C_Birmingham_AL.jpg",
"alcohol": ["Vodka",],
"ingredients": ["2 oz (1 part) vodka","3½ oz (2 parts) orange juice",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 9, "wWarm": 6, "wHot": 7},
"precipValue": {"pNone": 5, "pSome": 4},
"seasonValue": {"sSpr": 8, "sSum": 9, "sFal": 6, "sWin": 5},
"dayValue": {"dMTRS": 9, "dW": 5, "dFS": 3},
"timeValue": {"tMrn": 10, "tAft": 8, "tNt": 3, "wSleep": 5}
}
},
{"drinkName": "Sea Breeze",
"recipe": "Build all ingredients in a highball glass filled with ice. Garnish with lime wedge.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b1/Cocktail_with_vodka.jpg/220px-Cocktail_with_vodka.jpg",
"alcohol": ["Vodka",],
"ingredients": ["1½ oz Vodka","1¾ oz Cranberry juice","1 oz Grapefruit juice","lime wedge"],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 4, "wWarm": 6, "wHot": 7},
"precipValue": {"pNone": 9, "pSome": 3},
"seasonValue": {"sSpr": 8, "sSum": 9, "sFal": 7, "sWin": 3},
"dayValue": {"dMTRS": 4, "dW": 5, "dFS": 7},
"timeValue": {"tMrn": 7, "tAft": 8, "tNt": 4, "wSleep": 3}
}
},
{"drinkName": "Sex on the Beach",
"recipe": "Build all ingredients in a highball glass filled with ice. Garnish with orange slice.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a2/Sex_On_The_Beach.jpg/220px-Sex_On_The_Beach.jpg",
"alcohol": ["Vodka", "Liqueur",],
"ingredients": ["1½ oz Vodka","¾ oz Peach schnapps","1½ oz Orange juice","1½ oz Cranberry juice",],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 4, "wWarm": 5, "wHot": 10},
"precipValue": {"pNone": 9, "pSome": 2},
"seasonValue": {"sSpr": 6, "sSum": 10, "sFal": 2, "sWin": 1},
"dayValue": {"dMTRS": 2, "dW": 6, "dFS": 10},
"timeValue": {"tMrn": 7, "tAft": 8, "tNt": 3, "wSleep": 2}
}
},
{"drinkName": "Sidecar",
"recipe": "Pour all ingredients into cocktail shaker filled with ice. Shake well and strain into cocktail glass.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/9/94/Sidecar-cocktail.jpg/220px-Sidecar-cocktail.jpg",
"alcohol": ["Brandy",],
"ingredients": ["2 oz cognac","¾ oz triple sec","¾ oz lemon juice",],
"drinkRating": {
"weatherValue": {"wCold": 5, "wMod": 9, "wWarm": 7, "wHot": 6},
"precipValue": {"pNone": 3, "pSome": 8},
"seasonValue": {"sSpr": 9, "sSum": 6, "sFal": 5, "sWin": 7},
"dayValue": {"dMTRS": 3, "dW": 4, "dFS": 5},
"timeValue": {"tMrn": 2, "tAft": 5, "tNt": 9, "wSleep": 8}
}
},
{"drinkName": "Singapore Sling",
"recipe": "Pour all ingredients into cocktail shaker filled with ice cubes. Shake well. Strain into highball glass. Garnish with pineapple and cocktail cherry.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/4/44/Singapore_Sling.jpg/220px-Singapore_Sling.jpg",
"alcohol": ["Gin","Liqueur",],
"ingredients": ["1 oz Gin","½ oz Cherry Liqueur","¼ oz Cointreau","¼ oz DOM Bénédictine","½ oz Grenadine","1¾ oz Pineapple juice","½ oz Fresh lime juice","1 dash Angostura bitters",],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 3, "wWarm": 6, "wHot": 9},
"precipValue": {"pNone": 8, "pSome": 2},
"seasonValue": {"sSpr": 8, "sSum": 9, "sFal": 4, "sWin": 2},
"dayValue": {"dMTRS": 3, "dW": 6, "dFS": 7},
"timeValue": {"tMrn": 6, "tAft": 8, "tNt": 2, "wSleep": 1}
}
},
{"drinkName": "Slippery Nipple",
"recipe": "Pour the Baileys into a shot glass, then pour the Sambuca on top so that the two liquids do not mix.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/3/32/Slippery_Nipple.jpg/220px-Slippery_Nipple.jpg",
"alcohol": ["Liqueur",],
"ingredients": ["(1 part) Sambuca","(1 part) Baileys Irish Cream",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 9, "wWarm": 8, "wHot": 4},
"precipValue": {"pNone": 5, "pSome": 5},
"seasonValue": {"sSpr": 6, "sSum": 7, "sFal": 2, "sWin": 2},
"dayValue": {"dMTRS": 2, "dW": 5, "dFS": 8},
"timeValue": {"tMrn": 3, "tAft": 4, "tNt": 8, "wSleep": 4}
}
},
{"drinkName": "Springbokkie",
"recipe": "The Crème de menthe is poured into the shot glass and the Amarula is carefully layered on top.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/7/74/Amarula_Springbokkie_shooter.jpg/220px-Amarula_Springbokkie_shooter.jpg",
"alcohol": ["Liqueur",],
"ingredients": ["½ oz (1 part) Amarula","1 oz (3 parts) Crème de menthe",],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 5, "wWarm": 9, "wHot": 7},
"precipValue": {"pNone": 8, "pSome": 5},
"seasonValue": {"sSpr": 9, "sSum": 7, "sFal": 4, "sWin": 3},
"dayValue": {"dMTRS": 3, "dW": 5, "dFS": 6},
"timeValue": {"tMrn": 7, "tAft": 9, "tNt": 4, "wSleep": 2}
}
},
{"drinkName": "Tequila & Tonic",
"recipe": "In a glass filled with ice cubes, add tequila and tonic.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/f/f3/Tequila_%26_Tonic.jpg/220px-Tequila_%26_Tonic.jpg",
"alcohol": ["Tequila",],
"ingredients": ["Tequila","Tonic"],
"drinkRating": {
"weatherValue": {"wCold": 3, "wMod": 6, "wWarm": 7, "wHot": 6},
"precipValue": {"pNone": 8, "pSome": 4},
"seasonValue": {"sSpr": 6, "sSum": 8, "sFal": 5, "sWin": 2},
"dayValue": {"dMTRS": 5, "dW": 6, "dFS": 8},
"timeValue": {"tMrn": 2, "tAft": 6, "tNt": 5, "wSleep": 8}
}
},
{"drinkName": "Tequila Sunrise",
"recipe": "Pour the tequila and orange juice into glass over ice. Add the grenadine, which will sink to the bottom. Do not stir. Garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/7/79/Tequila_Sunrise_garnished_with_orange_and_cherry_-_Evan_Swigart.jpg/220px-Tequila_Sunrise_garnished_with_orange_and_cherry_-_Evan_Swigart.jpg",
"alcohol": ["Tequila",],
"ingredients": ["1½ oz (3 parts) Tequila","3 oz (6 parts) Orange juice","½ oz (1 part) Grenadine syrup",],
"drinkRating": {
"weatherValue": {"wCold": 4, "wMod": 5, "wWarm": 6, "wHot": 7},
"precipValue": {"pNone": 9, "pSome": 4},
"seasonValue": {"sSpr": 6, "sSum": 9, "sFal": 4, "sWin": 1},
"dayValue": {"dMTRS": 2, "dW": 3, "dFS": 6},
"timeValue": {"tMrn": 10, "tAft": 3, "tNt": 2, "wSleep": 1}
}
},
{"drinkName": "The Last Word",
"recipe": "Shake with ice and strain into a cocktail glass.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/4/43/The_Last_Word_cocktail_raised.jpg/220px-The_Last_Word_cocktail_raised.jpg",
"alcohol": ["Liqueur","Gin",],
"ingredients": ["One part gin","One part lime juice","One part green Chartreuse","One part maraschino liqueur",],
"drinkRating": {
"weatherValue": {"wCold": 7, "wMod": 6, "wWarm": 5, "wHot": 3},
"precipValue": {"pNone": 3, "pSome": 7},
"seasonValue": {"sSpr": 4, "sSum": 3, "sFal": 7, "sWin": 6},
"dayValue": {"dMTRS": 7, "dW": 4, "dFS": 3},
"timeValue": {"tMrn": 3, "tAft": 7, "tNt": 5, "wSleep": 6}
}
},
{"drinkName": "Tinto de Verano",
"recipe": "Mix and serve well chilled.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/f/f9/Tinto_de_verano.jpg/220px-Tinto_de_verano.jpg",
"alcohol": ["Wine",],
"ingredients": ["One part red wine","One part Sprite and water(or Gaseosa)",],
"drinkRating": {
"weatherValue": {"wCold": 4, "wMod": 5, "wWarm": 8, "wHot": 6},
"precipValue": {"pNone": 9, "pSome": 2},
"seasonValue": {"sSpr": 7, "sSum": 8, "sFal": 4, "sWin": 1},
"dayValue": {"dMTRS": 6, "dW": 7, "dFS": 8},
"timeValue": {"tMrn": 1, "tAft": 9, "tNt": 6, "wSleep": 1}
}
},
{"drinkName": "Tom Collins",
"recipe": "Mix the gin, lemon juice and sugar syrup in a tall glass with ice, top up with soda water, garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/0/0b/Tom_Collins_in_Copenhagen.jpg/220px-Tom_Collins_in_Copenhagen.jpg",
"alcohol": ["Gin",],
"ingredients": ["1½ oz (3 parts) Old Tom Gin","1 oz (2 parts) lemon juice","½ oz (1 part) sugar syrup","2 oz (4 parts) carbonated water",],
"drinkRating": {
"weatherValue": {"wCold": 5, "wMod": 5, "wWarm": 8, "wHot": 6},
"precipValue": {"pNone": 7, "pSome": 3},
"seasonValue": {"sSpr": 9, "sSum": 7, "sFal": 6, "sWin": 3},
"dayValue": {"dMTRS": 5, "dW": 8, "dFS": 7},
"timeValue": {"tMrn": 5, "tAft": 9, "tNt": 6, "wSleep": 2}
}
},
{"drinkName": "Vesper",
"recipe": "Shake over ice until well chilled, then strain into a deep goblet and garnish with a thin slice of lemon peel.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/0/01/Vesper_Martini_%28corrected%29.jpg/220px-Vesper_Martini_%28corrected%29.jpg",
"alcohol": ["Gin","Vodka", "Wine"],
"ingredients": ["2 oz gin","½ oz vodka","¼ oz Lillet Blonde(wine)",],
"drinkRating": {
"weatherValue": {"wCold": 7, "wMod": 8, "wWarm": 4, "wHot": 2},
"precipValue": {"pNone": 2, "pSome": 9},
"seasonValue": {"sSpr": 3, "sSum": 6, "sFal": 7, "sWin": 9},
"dayValue": {"dMTRS": 6, "dW": 7, "dFS": 5},
"timeValue": {"tMrn": 2, "tAft": 9, "tNt": 8, "wSleep": 7}
}
},
{"drinkName": "Vodka Martini",
"recipe": "Straight: Pour all ingredients into mixing glass with ice cubes. Shake well. Strain in chilled martini cocktail glass. Squeeze oil from lemon peel onto the drink, or garnish with olive.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/9/92/Vodka_Martini%2C_Macaroni_Grill%2C_Dunwoody_GA.jpg/220px-Vodka_Martini%2C_Macaroni_Grill%2C_Dunwoody_GA.jpg",
"alcohol": ["Vermouth","Vodka",],
"ingredients": ["2 oz (6 parts) vodka","½ oz (1 parts) dry vermouth",],
"drinkRating": {
"weatherValue": {"wCold": 5, "wMod": 10, "wWarm": 4, "wHot": 3},
"precipValue": {"pNone": 4, "pSome": 8},
"seasonValue": {"sSpr": 3, "sSum": 5, "sFal": 7, "sWin": 6},
"dayValue": {"dMTRS": 8, "dW": 4, "dFS": 7},
"timeValue": {"tMrn": 1, "tAft": 4, "tNt": 10, "wSleep": 9}
}
},
{"drinkName": "Whiskey Sour",
"recipe": "Shake with ice. Strain into chilled glass, garnish and serve.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/5/59/Whiskey_Sour.jpg/220px-Whiskey_Sour.jpg",
"alcohol": ["Whiskey",],
"ingredients": ["1½ oz (3 parts) Bourbon whiskey","1 oz (2 parts) fresh lemon juice","½ oz (1 part) Gomme syrup","dash egg white (optional)",],
"drinkRating": {
"weatherValue": {"wCold": 2, "wMod": 6, "wWarm": 6, "wHot": 5},
"precipValue": {"pNone": 6, "pSome": 4},
"seasonValue": {"sSpr": 6, "sSum": 9, "sFal": 5, "sWin": 3},
"dayValue": {"dMTRS": 2, "dW": 4, "dFS": 6},
"timeValue": {"tMrn": 1, "tAft": 6, "tNt": 7, "wSleep": 2}
}
},
{"drinkName": "White Russian",
"recipe": "Pour coffee liqueur and vodka into an Old Fashioned glass filled with ice. Float fresh cream on top and stir slowly.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/4/48/White-Russian.jpg/220px-White-Russian.jpg",
"alcohol": ["Vodka","Liqueur",],
"ingredients": ["2 oz (5 parts) Vodka","¾ oz (2 parts) Coffee liqueur","1 oz (3 parts) fresh cream",],
"drinkRating": {
"weatherValue": {"wCold": 5, "wMod": 8, "wWarm": 7, "wHot": 6},
"precipValue": {"pNone": 7, "pSome": 3},
"seasonValue": {"sSpr": 7, "sSum": 7, "sFal": 9, "sWin": 3},
"dayValue": {"dMTRS": 7, "dW": 10, "dFS": 4},
"timeValue": {"tMrn": 6, "tAft": 8, "tNt": 4, "wSleep": 2}
}
},
{"drinkName": "Zombie",
"recipe": "Mix ingredients other than the 151 in a shaker with ice. Pour into glass and top with the high-proof rum.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e7/Zombiecocktail.jpg/220px-Zombiecocktail.jpg",
"alcohol": ["Brandy","Rum",],
"ingredients": ["1 part white rum","1 part golden rum","1 part dark rum","1 part apricot brandy","1 part pineapple juice","½ part 151-proof rum","1 part lime juice",],
"drinkRating": {
"weatherValue": {"wCold": 1, "wMod": 2, "wWarm": 7, "wHot": 10},
"precipValue": {"pNone": 8, "pSome": 1},
"seasonValue": {"sSpr": 6, "sSum": 9, "sFal": 2, "sWin": 1},
"dayValue": {"dMTRS": 1, "dW": 4, "dFS": 9},
"timeValue": {"tMrn": 3, "tAft": 10, "tNt": 6, "wSleep": 1}
}
}]
module.exports = AllDrinks; | srs1212/drinkSync | AllDrinks.js | JavaScript | mit | 69,466 |
//
// Copyright (c) 2009-2021 Krueger Systems, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#if WINDOWS_PHONE && !USE_WP8_NATIVE_SQLITE
#define USE_CSHARP_SQLITE
#endif
using System;
using System.Collections;
using System.Diagnostics;
#if !USE_SQLITEPCL_RAW
using System.Runtime.InteropServices;
#endif
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading;
#if USE_CSHARP_SQLITE
using Sqlite3 = Community.CsharpSqlite.Sqlite3;
using Sqlite3DatabaseHandle = Community.CsharpSqlite.Sqlite3.sqlite3;
using Sqlite3Statement = Community.CsharpSqlite.Sqlite3.Vdbe;
#elif USE_WP8_NATIVE_SQLITE
using Sqlite3 = Sqlite.Sqlite3;
using Sqlite3DatabaseHandle = Sqlite.Database;
using Sqlite3Statement = Sqlite.Statement;
#elif USE_SQLITEPCL_RAW
using Sqlite3DatabaseHandle = SQLitePCL.sqlite3;
using Sqlite3BackupHandle = SQLitePCL.sqlite3_backup;
using Sqlite3Statement = SQLitePCL.sqlite3_stmt;
using Sqlite3 = SQLitePCL.raw;
#else
using Sqlite3DatabaseHandle = System.IntPtr;
using Sqlite3BackupHandle = System.IntPtr;
using Sqlite3Statement = System.IntPtr;
#endif
#pragma warning disable 1591 // XML Doc Comments
namespace SQLite
{
public class SQLiteException : Exception
{
public SQLite3.Result Result { get; private set; }
protected SQLiteException (SQLite3.Result r, string message) : base (message)
{
Result = r;
}
public static SQLiteException New (SQLite3.Result r, string message)
{
return new SQLiteException (r, message);
}
}
public class NotNullConstraintViolationException : SQLiteException
{
public IEnumerable<TableMapping.Column> Columns { get; protected set; }
protected NotNullConstraintViolationException (SQLite3.Result r, string message)
: this (r, message, null, null)
{
}
protected NotNullConstraintViolationException (SQLite3.Result r, string message, TableMapping mapping, object obj)
: base (r, message)
{
if (mapping != null && obj != null) {
this.Columns = from c in mapping.Columns
where c.IsNullable == false && c.GetValue (obj) == null
select c;
}
}
public static new NotNullConstraintViolationException New (SQLite3.Result r, string message)
{
return new NotNullConstraintViolationException (r, message);
}
public static NotNullConstraintViolationException New (SQLite3.Result r, string message, TableMapping mapping, object obj)
{
return new NotNullConstraintViolationException (r, message, mapping, obj);
}
public static NotNullConstraintViolationException New (SQLiteException exception, TableMapping mapping, object obj)
{
return new NotNullConstraintViolationException (exception.Result, exception.Message, mapping, obj);
}
}
[Flags]
public enum SQLiteOpenFlags
{
ReadOnly = 1, ReadWrite = 2, Create = 4,
NoMutex = 0x8000, FullMutex = 0x10000,
SharedCache = 0x20000, PrivateCache = 0x40000,
ProtectionComplete = 0x00100000,
ProtectionCompleteUnlessOpen = 0x00200000,
ProtectionCompleteUntilFirstUserAuthentication = 0x00300000,
ProtectionNone = 0x00400000
}
[Flags]
public enum CreateFlags
{
/// <summary>
/// Use the default creation options
/// </summary>
None = 0x000,
/// <summary>
/// Create a primary key index for a property called 'Id' (case-insensitive).
/// This avoids the need for the [PrimaryKey] attribute.
/// </summary>
ImplicitPK = 0x001,
/// <summary>
/// Create indices for properties ending in 'Id' (case-insensitive).
/// </summary>
ImplicitIndex = 0x002,
/// <summary>
/// Create a primary key for a property called 'Id' and
/// create an indices for properties ending in 'Id' (case-insensitive).
/// </summary>
AllImplicit = 0x003,
/// <summary>
/// Force the primary key property to be auto incrementing.
/// This avoids the need for the [AutoIncrement] attribute.
/// The primary key property on the class should have type int or long.
/// </summary>
AutoIncPK = 0x004,
/// <summary>
/// Create virtual table using FTS3
/// </summary>
FullTextSearch3 = 0x100,
/// <summary>
/// Create virtual table using FTS4
/// </summary>
FullTextSearch4 = 0x200
}
/// <summary>
/// An open connection to a SQLite database.
/// </summary>
[Preserve (AllMembers = true)]
public partial class SQLiteConnection : IDisposable
{
private bool _open;
private TimeSpan _busyTimeout;
readonly static Dictionary<string, TableMapping> _mappings = new Dictionary<string, TableMapping> ();
private System.Diagnostics.Stopwatch _sw;
private long _elapsedMilliseconds = 0;
private int _transactionDepth = 0;
private Random _rand = new Random ();
public Sqlite3DatabaseHandle Handle { get; private set; }
static readonly Sqlite3DatabaseHandle NullHandle = default (Sqlite3DatabaseHandle);
static readonly Sqlite3BackupHandle NullBackupHandle = default (Sqlite3BackupHandle);
/// <summary>
/// Gets the database path used by this connection.
/// </summary>
public string DatabasePath { get; private set; }
/// <summary>
/// Gets the SQLite library version number. 3007014 would be v3.7.14
/// </summary>
public int LibVersionNumber { get; private set; }
/// <summary>
/// Whether Trace lines should be written that show the execution time of queries.
/// </summary>
public bool TimeExecution { get; set; }
/// <summary>
/// Whether to write queries to <see cref="Tracer"/> during execution.
/// </summary>
public bool Trace { get; set; }
/// <summary>
/// The delegate responsible for writing trace lines.
/// </summary>
/// <value>The tracer.</value>
public Action<string> Tracer { get; set; }
/// <summary>
/// Whether to store DateTime properties as ticks (true) or strings (false).
/// </summary>
public bool StoreDateTimeAsTicks { get; private set; }
/// <summary>
/// Whether to store TimeSpan properties as ticks (true) or strings (false).
/// </summary>
public bool StoreTimeSpanAsTicks { get; private set; }
/// <summary>
/// The format to use when storing DateTime properties as strings. Ignored if StoreDateTimeAsTicks is true.
/// </summary>
/// <value>The date time string format.</value>
public string DateTimeStringFormat { get; private set; }
/// <summary>
/// The DateTimeStyles value to use when parsing a DateTime property string.
/// </summary>
/// <value>The date time style.</value>
internal System.Globalization.DateTimeStyles DateTimeStyle { get; private set; }
#if USE_SQLITEPCL_RAW && !NO_SQLITEPCL_RAW_BATTERIES
static SQLiteConnection ()
{
SQLitePCL.Batteries_V2.Init ();
}
#endif
/// <summary>
/// Constructs a new SQLiteConnection and opens a SQLite database specified by databasePath.
/// </summary>
/// <param name="databasePath">
/// Specifies the path to the database file.
/// </param>
/// <param name="storeDateTimeAsTicks">
/// Specifies whether to store DateTime properties as ticks (true) or strings (false). You
/// absolutely do want to store them as Ticks in all new projects. The value of false is
/// only here for backwards compatibility. There is a *significant* speed advantage, with no
/// down sides, when setting storeDateTimeAsTicks = true.
/// If you use DateTimeOffset properties, it will be always stored as ticks regardingless
/// the storeDateTimeAsTicks parameter.
/// </param>
public SQLiteConnection (string databasePath, bool storeDateTimeAsTicks = true)
: this (new SQLiteConnectionString (databasePath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create, storeDateTimeAsTicks))
{
}
/// <summary>
/// Constructs a new SQLiteConnection and opens a SQLite database specified by databasePath.
/// </summary>
/// <param name="databasePath">
/// Specifies the path to the database file.
/// </param>
/// <param name="openFlags">
/// Flags controlling how the connection should be opened.
/// </param>
/// <param name="storeDateTimeAsTicks">
/// Specifies whether to store DateTime properties as ticks (true) or strings (false). You
/// absolutely do want to store them as Ticks in all new projects. The value of false is
/// only here for backwards compatibility. There is a *significant* speed advantage, with no
/// down sides, when setting storeDateTimeAsTicks = true.
/// If you use DateTimeOffset properties, it will be always stored as ticks regardingless
/// the storeDateTimeAsTicks parameter.
/// </param>
public SQLiteConnection (string databasePath, SQLiteOpenFlags openFlags, bool storeDateTimeAsTicks = true)
: this (new SQLiteConnectionString (databasePath, openFlags, storeDateTimeAsTicks))
{
}
/// <summary>
/// Constructs a new SQLiteConnection and opens a SQLite database specified by databasePath.
/// </summary>
/// <param name="connectionString">
/// Details on how to find and open the database.
/// </param>
public SQLiteConnection (SQLiteConnectionString connectionString)
{
if (connectionString == null)
throw new ArgumentNullException (nameof (connectionString));
if (connectionString.DatabasePath == null)
throw new InvalidOperationException ("DatabasePath must be specified");
DatabasePath = connectionString.DatabasePath;
LibVersionNumber = SQLite3.LibVersionNumber ();
#if NETFX_CORE
SQLite3.SetDirectory(/*temp directory type*/2, Windows.Storage.ApplicationData.Current.TemporaryFolder.Path);
#endif
Sqlite3DatabaseHandle handle;
#if SILVERLIGHT || USE_CSHARP_SQLITE || USE_SQLITEPCL_RAW
var r = SQLite3.Open (connectionString.DatabasePath, out handle, (int)connectionString.OpenFlags, connectionString.VfsName);
#else
// open using the byte[]
// in the case where the path may include Unicode
// force open to using UTF-8 using sqlite3_open_v2
var databasePathAsBytes = GetNullTerminatedUtf8 (connectionString.DatabasePath);
var r = SQLite3.Open (databasePathAsBytes, out handle, (int)connectionString.OpenFlags, connectionString.VfsName);
#endif
Handle = handle;
if (r != SQLite3.Result.OK) {
throw SQLiteException.New (r, String.Format ("Could not open database file: {0} ({1})", DatabasePath, r));
}
_open = true;
StoreDateTimeAsTicks = connectionString.StoreDateTimeAsTicks;
StoreTimeSpanAsTicks = connectionString.StoreTimeSpanAsTicks;
DateTimeStringFormat = connectionString.DateTimeStringFormat;
DateTimeStyle = connectionString.DateTimeStyle;
BusyTimeout = TimeSpan.FromSeconds (1.0);
Tracer = line => Debug.WriteLine (line);
connectionString.PreKeyAction?.Invoke (this);
if (connectionString.Key is string stringKey) {
SetKey (stringKey);
}
else if (connectionString.Key is byte[] bytesKey) {
SetKey (bytesKey);
}
else if (connectionString.Key != null) {
throw new InvalidOperationException ("Encryption keys must be strings or byte arrays");
}
connectionString.PostKeyAction?.Invoke (this);
}
/// <summary>
/// Enables the write ahead logging. WAL is significantly faster in most scenarios
/// by providing better concurrency and better disk IO performance than the normal
/// journal mode. You only need to call this function once in the lifetime of the database.
/// </summary>
public void EnableWriteAheadLogging ()
{
ExecuteScalar<string> ("PRAGMA journal_mode=WAL");
}
/// <summary>
/// Convert an input string to a quoted SQL string that can be safely used in queries.
/// </summary>
/// <returns>The quoted string.</returns>
/// <param name="unsafeString">The unsafe string to quote.</param>
static string Quote (string unsafeString)
{
// TODO: Doesn't call sqlite3_mprintf("%Q", u) because we're waiting on https://github.com/ericsink/SQLitePCL.raw/issues/153
if (unsafeString == null)
return "NULL";
var safe = unsafeString.Replace ("'", "''");
return "'" + safe + "'";
}
/// <summary>
/// Sets the key used to encrypt/decrypt the database with "pragma key = ...".
/// This must be the first thing you call before doing anything else with this connection
/// if your database is encrypted.
/// This only has an effect if you are using the SQLCipher nuget package.
/// </summary>
/// <param name="key">Ecryption key plain text that is converted to the real encryption key using PBKDF2 key derivation</param>
void SetKey (string key)
{
if (key == null)
throw new ArgumentNullException (nameof (key));
var q = Quote (key);
ExecuteScalar<string> ("pragma key = " + q);
}
/// <summary>
/// Sets the key used to encrypt/decrypt the database.
/// This must be the first thing you call before doing anything else with this connection
/// if your database is encrypted.
/// This only has an effect if you are using the SQLCipher nuget package.
/// </summary>
/// <param name="key">256-bit (32 byte) ecryption key data</param>
void SetKey (byte[] key)
{
if (key == null)
throw new ArgumentNullException (nameof (key));
if (key.Length != 32 && key.Length != 48)
throw new ArgumentException ("Key must be 32 bytes (256-bit) or 48 bytes (384-bit)", nameof (key));
var s = String.Join ("", key.Select (x => x.ToString ("X2")));
ExecuteScalar<string> ("pragma key = \"x'" + s + "'\"");
}
/// <summary>
/// Enable or disable extension loading.
/// </summary>
public void EnableLoadExtension (bool enabled)
{
SQLite3.Result r = SQLite3.EnableLoadExtension (Handle, enabled ? 1 : 0);
if (r != SQLite3.Result.OK) {
string msg = SQLite3.GetErrmsg (Handle);
throw SQLiteException.New (r, msg);
}
}
#if !USE_SQLITEPCL_RAW
static byte[] GetNullTerminatedUtf8 (string s)
{
var utf8Length = System.Text.Encoding.UTF8.GetByteCount (s);
var bytes = new byte [utf8Length + 1];
utf8Length = System.Text.Encoding.UTF8.GetBytes(s, 0, s.Length, bytes, 0);
return bytes;
}
#endif
/// <summary>
/// Sets a busy handler to sleep the specified amount of time when a table is locked.
/// The handler will sleep multiple times until a total time of <see cref="BusyTimeout"/> has accumulated.
/// </summary>
public TimeSpan BusyTimeout {
get { return _busyTimeout; }
set {
_busyTimeout = value;
if (Handle != NullHandle) {
SQLite3.BusyTimeout (Handle, (int)_busyTimeout.TotalMilliseconds);
}
}
}
/// <summary>
/// Returns the mappings from types to tables that the connection
/// currently understands.
/// </summary>
public IEnumerable<TableMapping> TableMappings {
get {
lock (_mappings) {
return new List<TableMapping> (_mappings.Values);
}
}
}
/// <summary>
/// Retrieves the mapping that is automatically generated for the given type.
/// </summary>
/// <param name="type">
/// The type whose mapping to the database is returned.
/// </param>
/// <param name="createFlags">
/// Optional flags allowing implicit PK and indexes based on naming conventions
/// </param>
/// <returns>
/// The mapping represents the schema of the columns of the database and contains
/// methods to set and get properties of objects.
/// </returns>
public TableMapping GetMapping (Type type, CreateFlags createFlags = CreateFlags.None)
{
TableMapping map;
var key = type.FullName;
lock (_mappings) {
if (_mappings.TryGetValue (key, out map)) {
if (createFlags != CreateFlags.None && createFlags != map.CreateFlags) {
map = new TableMapping (type, createFlags);
_mappings[key] = map;
}
}
else {
map = new TableMapping (type, createFlags);
_mappings.Add (key, map);
}
}
return map;
}
/// <summary>
/// Retrieves the mapping that is automatically generated for the given type.
/// </summary>
/// <param name="createFlags">
/// Optional flags allowing implicit PK and indexes based on naming conventions
/// </param>
/// <returns>
/// The mapping represents the schema of the columns of the database and contains
/// methods to set and get properties of objects.
/// </returns>
public TableMapping GetMapping<T> (CreateFlags createFlags = CreateFlags.None)
{
return GetMapping (typeof (T), createFlags);
}
private struct IndexedColumn
{
public int Order;
public string ColumnName;
}
private struct IndexInfo
{
public string IndexName;
public string TableName;
public bool Unique;
public List<IndexedColumn> Columns;
}
/// <summary>
/// Executes a "drop table" on the database. This is non-recoverable.
/// </summary>
public int DropTable<T> ()
{
return DropTable (GetMapping (typeof (T)));
}
/// <summary>
/// Executes a "drop table" on the database. This is non-recoverable.
/// </summary>
/// <param name="map">
/// The TableMapping used to identify the table.
/// </param>
public int DropTable (TableMapping map)
{
var query = string.Format ("drop table if exists \"{0}\"", map.TableName);
return Execute (query);
}
/// <summary>
/// Executes a "create table if not exists" on the database. It also
/// creates any specified indexes on the columns of the table. It uses
/// a schema automatically generated from the specified type. You can
/// later access this schema by calling GetMapping.
/// </summary>
/// <returns>
/// Whether the table was created or migrated.
/// </returns>
public CreateTableResult CreateTable<T> (CreateFlags createFlags = CreateFlags.None)
{
return CreateTable (typeof (T), createFlags);
}
/// <summary>
/// Executes a "create table if not exists" on the database. It also
/// creates any specified indexes on the columns of the table. It uses
/// a schema automatically generated from the specified type. You can
/// later access this schema by calling GetMapping.
/// </summary>
/// <param name="ty">Type to reflect to a database table.</param>
/// <param name="createFlags">Optional flags allowing implicit PK and indexes based on naming conventions.</param>
/// <returns>
/// Whether the table was created or migrated.
/// </returns>
public CreateTableResult CreateTable (Type ty, CreateFlags createFlags = CreateFlags.None)
{
var map = GetMapping (ty, createFlags);
// Present a nice error if no columns specified
if (map.Columns.Length == 0) {
throw new Exception (string.Format ("Cannot create a table without columns (does '{0}' have public properties?)", ty.FullName));
}
// Check if the table exists
var result = CreateTableResult.Created;
var existingCols = GetTableInfo (map.TableName);
// Create or migrate it
if (existingCols.Count == 0) {
// Facilitate virtual tables a.k.a. full-text search.
bool fts3 = (createFlags & CreateFlags.FullTextSearch3) != 0;
bool fts4 = (createFlags & CreateFlags.FullTextSearch4) != 0;
bool fts = fts3 || fts4;
var @virtual = fts ? "virtual " : string.Empty;
var @using = fts3 ? "using fts3 " : fts4 ? "using fts4 " : string.Empty;
// Build query.
var query = "create " + @virtual + "table if not exists \"" + map.TableName + "\" " + @using + "(\n";
var decls = map.Columns.Select (p => Orm.SqlDecl (p, StoreDateTimeAsTicks, StoreTimeSpanAsTicks));
var decl = string.Join (",\n", decls.ToArray ());
query += decl;
query += ")";
if (map.WithoutRowId) {
query += " without rowid";
}
Execute (query);
}
else {
result = CreateTableResult.Migrated;
MigrateTable (map, existingCols);
}
var indexes = new Dictionary<string, IndexInfo> ();
foreach (var c in map.Columns) {
foreach (var i in c.Indices) {
var iname = i.Name ?? map.TableName + "_" + c.Name;
IndexInfo iinfo;
if (!indexes.TryGetValue (iname, out iinfo)) {
iinfo = new IndexInfo {
IndexName = iname,
TableName = map.TableName,
Unique = i.Unique,
Columns = new List<IndexedColumn> ()
};
indexes.Add (iname, iinfo);
}
if (i.Unique != iinfo.Unique)
throw new Exception ("All the columns in an index must have the same value for their Unique property");
iinfo.Columns.Add (new IndexedColumn {
Order = i.Order,
ColumnName = c.Name
});
}
}
foreach (var indexName in indexes.Keys) {
var index = indexes[indexName];
var columns = index.Columns.OrderBy (i => i.Order).Select (i => i.ColumnName).ToArray ();
CreateIndex (indexName, index.TableName, columns, index.Unique);
}
return result;
}
/// <summary>
/// Executes a "create table if not exists" on the database for each type. It also
/// creates any specified indexes on the columns of the table. It uses
/// a schema automatically generated from the specified type. You can
/// later access this schema by calling GetMapping.
/// </summary>
/// <returns>
/// Whether the table was created or migrated for each type.
/// </returns>
public CreateTablesResult CreateTables<T, T2> (CreateFlags createFlags = CreateFlags.None)
where T : new()
where T2 : new()
{
return CreateTables (createFlags, typeof (T), typeof (T2));
}
/// <summary>
/// Executes a "create table if not exists" on the database for each type. It also
/// creates any specified indexes on the columns of the table. It uses
/// a schema automatically generated from the specified type. You can
/// later access this schema by calling GetMapping.
/// </summary>
/// <returns>
/// Whether the table was created or migrated for each type.
/// </returns>
public CreateTablesResult CreateTables<T, T2, T3> (CreateFlags createFlags = CreateFlags.None)
where T : new()
where T2 : new()
where T3 : new()
{
return CreateTables (createFlags, typeof (T), typeof (T2), typeof (T3));
}
/// <summary>
/// Executes a "create table if not exists" on the database for each type. It also
/// creates any specified indexes on the columns of the table. It uses
/// a schema automatically generated from the specified type. You can
/// later access this schema by calling GetMapping.
/// </summary>
/// <returns>
/// Whether the table was created or migrated for each type.
/// </returns>
public CreateTablesResult CreateTables<T, T2, T3, T4> (CreateFlags createFlags = CreateFlags.None)
where T : new()
where T2 : new()
where T3 : new()
where T4 : new()
{
return CreateTables (createFlags, typeof (T), typeof (T2), typeof (T3), typeof (T4));
}
/// <summary>
/// Executes a "create table if not exists" on the database for each type. It also
/// creates any specified indexes on the columns of the table. It uses
/// a schema automatically generated from the specified type. You can
/// later access this schema by calling GetMapping.
/// </summary>
/// <returns>
/// Whether the table was created or migrated for each type.
/// </returns>
public CreateTablesResult CreateTables<T, T2, T3, T4, T5> (CreateFlags createFlags = CreateFlags.None)
where T : new()
where T2 : new()
where T3 : new()
where T4 : new()
where T5 : new()
{
return CreateTables (createFlags, typeof (T), typeof (T2), typeof (T3), typeof (T4), typeof (T5));
}
/// <summary>
/// Executes a "create table if not exists" on the database for each type. It also
/// creates any specified indexes on the columns of the table. It uses
/// a schema automatically generated from the specified type. You can
/// later access this schema by calling GetMapping.
/// </summary>
/// <returns>
/// Whether the table was created or migrated for each type.
/// </returns>
public CreateTablesResult CreateTables (CreateFlags createFlags = CreateFlags.None, params Type[] types)
{
var result = new CreateTablesResult ();
foreach (Type type in types) {
var aResult = CreateTable (type, createFlags);
result.Results[type] = aResult;
}
return result;
}
/// <summary>
/// Creates an index for the specified table and columns.
/// </summary>
/// <param name="indexName">Name of the index to create</param>
/// <param name="tableName">Name of the database table</param>
/// <param name="columnNames">An array of column names to index</param>
/// <param name="unique">Whether the index should be unique</param>
/// <returns>Zero on success.</returns>
public int CreateIndex (string indexName, string tableName, string[] columnNames, bool unique = false)
{
const string sqlFormat = "create {2} index if not exists \"{3}\" on \"{0}\"(\"{1}\")";
var sql = String.Format (sqlFormat, tableName, string.Join ("\", \"", columnNames), unique ? "unique" : "", indexName);
return Execute (sql);
}
/// <summary>
/// Creates an index for the specified table and column.
/// </summary>
/// <param name="indexName">Name of the index to create</param>
/// <param name="tableName">Name of the database table</param>
/// <param name="columnName">Name of the column to index</param>
/// <param name="unique">Whether the index should be unique</param>
/// <returns>Zero on success.</returns>
public int CreateIndex (string indexName, string tableName, string columnName, bool unique = false)
{
return CreateIndex (indexName, tableName, new string[] { columnName }, unique);
}
/// <summary>
/// Creates an index for the specified table and column.
/// </summary>
/// <param name="tableName">Name of the database table</param>
/// <param name="columnName">Name of the column to index</param>
/// <param name="unique">Whether the index should be unique</param>
/// <returns>Zero on success.</returns>
public int CreateIndex (string tableName, string columnName, bool unique = false)
{
return CreateIndex (tableName + "_" + columnName, tableName, columnName, unique);
}
/// <summary>
/// Creates an index for the specified table and columns.
/// </summary>
/// <param name="tableName">Name of the database table</param>
/// <param name="columnNames">An array of column names to index</param>
/// <param name="unique">Whether the index should be unique</param>
/// <returns>Zero on success.</returns>
public int CreateIndex (string tableName, string[] columnNames, bool unique = false)
{
return CreateIndex (tableName + "_" + string.Join ("_", columnNames), tableName, columnNames, unique);
}
/// <summary>
/// Creates an index for the specified object property.
/// e.g. CreateIndex<Client>(c => c.Name);
/// </summary>
/// <typeparam name="T">Type to reflect to a database table.</typeparam>
/// <param name="property">Property to index</param>
/// <param name="unique">Whether the index should be unique</param>
/// <returns>Zero on success.</returns>
public int CreateIndex<T> (Expression<Func<T, object>> property, bool unique = false)
{
MemberExpression mx;
if (property.Body.NodeType == ExpressionType.Convert) {
mx = ((UnaryExpression)property.Body).Operand as MemberExpression;
}
else {
mx = (property.Body as MemberExpression);
}
var propertyInfo = mx.Member as PropertyInfo;
if (propertyInfo == null) {
throw new ArgumentException ("The lambda expression 'property' should point to a valid Property");
}
var propName = propertyInfo.Name;
var map = GetMapping<T> ();
var colName = map.FindColumnWithPropertyName (propName).Name;
return CreateIndex (map.TableName, colName, unique);
}
[Preserve (AllMembers = true)]
public class ColumnInfo
{
// public int cid { get; set; }
[Column ("name")]
public string Name { get; set; }
// [Column ("type")]
// public string ColumnType { get; set; }
public int notnull { get; set; }
// public string dflt_value { get; set; }
// public int pk { get; set; }
public override string ToString ()
{
return Name;
}
}
/// <summary>
/// Query the built-in sqlite table_info table for a specific tables columns.
/// </summary>
/// <returns>The columns contains in the table.</returns>
/// <param name="tableName">Table name.</param>
public List<ColumnInfo> GetTableInfo (string tableName)
{
var query = "pragma table_info(\"" + tableName + "\")";
return Query<ColumnInfo> (query);
}
void MigrateTable (TableMapping map, List<ColumnInfo> existingCols)
{
var toBeAdded = new List<TableMapping.Column> ();
foreach (var p in map.Columns) {
var found = false;
foreach (var c in existingCols) {
found = (string.Compare (p.Name, c.Name, StringComparison.OrdinalIgnoreCase) == 0);
if (found)
break;
}
if (!found) {
toBeAdded.Add (p);
}
}
foreach (var p in toBeAdded) {
var addCol = "alter table \"" + map.TableName + "\" add column " + Orm.SqlDecl (p, StoreDateTimeAsTicks, StoreTimeSpanAsTicks);
Execute (addCol);
}
}
/// <summary>
/// Creates a new SQLiteCommand. Can be overridden to provide a sub-class.
/// </summary>
/// <seealso cref="SQLiteCommand.OnInstanceCreated"/>
protected virtual SQLiteCommand NewCommand ()
{
return new SQLiteCommand (this);
}
/// <summary>
/// Creates a new SQLiteCommand given the command text with arguments. Place a '?'
/// in the command text for each of the arguments.
/// </summary>
/// <param name="cmdText">
/// The fully escaped SQL.
/// </param>
/// <param name="ps">
/// Arguments to substitute for the occurences of '?' in the command text.
/// </param>
/// <returns>
/// A <see cref="SQLiteCommand"/>
/// </returns>
public SQLiteCommand CreateCommand (string cmdText, params object[] ps)
{
if (!_open)
throw SQLiteException.New (SQLite3.Result.Error, "Cannot create commands from unopened database");
var cmd = NewCommand ();
cmd.CommandText = cmdText;
foreach (var o in ps) {
cmd.Bind (o);
}
return cmd;
}
/// <summary>
/// Creates a new SQLiteCommand given the command text with named arguments. Place a "[@:$]VVV"
/// in the command text for each of the arguments. VVV represents an alphanumeric identifier.
/// For example, @name :name and $name can all be used in the query.
/// </summary>
/// <param name="cmdText">
/// The fully escaped SQL.
/// </param>
/// <param name="args">
/// Arguments to substitute for the occurences of "[@:$]VVV" in the command text.
/// </param>
/// <returns>
/// A <see cref="SQLiteCommand" />
/// </returns>
public SQLiteCommand CreateCommand (string cmdText, Dictionary<string, object> args)
{
if (!_open)
throw SQLiteException.New (SQLite3.Result.Error, "Cannot create commands from unopened database");
SQLiteCommand cmd = NewCommand ();
cmd.CommandText = cmdText;
foreach (var kv in args) {
cmd.Bind (kv.Key, kv.Value);
}
return cmd;
}
/// <summary>
/// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?'
/// in the command text for each of the arguments and then executes that command.
/// Use this method instead of Query when you don't expect rows back. Such cases include
/// INSERTs, UPDATEs, and DELETEs.
/// You can set the Trace or TimeExecution properties of the connection
/// to profile execution.
/// </summary>
/// <param name="query">
/// The fully escaped SQL.
/// </param>
/// <param name="args">
/// Arguments to substitute for the occurences of '?' in the query.
/// </param>
/// <returns>
/// The number of rows modified in the database as a result of this execution.
/// </returns>
public int Execute (string query, params object[] args)
{
var cmd = CreateCommand (query, args);
if (TimeExecution) {
if (_sw == null) {
_sw = new Stopwatch ();
}
_sw.Reset ();
_sw.Start ();
}
var r = cmd.ExecuteNonQuery ();
if (TimeExecution) {
_sw.Stop ();
_elapsedMilliseconds += _sw.ElapsedMilliseconds;
Tracer?.Invoke (string.Format ("Finished in {0} ms ({1:0.0} s total)", _sw.ElapsedMilliseconds, _elapsedMilliseconds / 1000.0));
}
return r;
}
/// <summary>
/// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?'
/// in the command text for each of the arguments and then executes that command.
/// Use this method when return primitive values.
/// You can set the Trace or TimeExecution properties of the connection
/// to profile execution.
/// </summary>
/// <param name="query">
/// The fully escaped SQL.
/// </param>
/// <param name="args">
/// Arguments to substitute for the occurences of '?' in the query.
/// </param>
/// <returns>
/// The number of rows modified in the database as a result of this execution.
/// </returns>
public T ExecuteScalar<T> (string query, params object[] args)
{
var cmd = CreateCommand (query, args);
if (TimeExecution) {
if (_sw == null) {
_sw = new Stopwatch ();
}
_sw.Reset ();
_sw.Start ();
}
var r = cmd.ExecuteScalar<T> ();
if (TimeExecution) {
_sw.Stop ();
_elapsedMilliseconds += _sw.ElapsedMilliseconds;
Tracer?.Invoke (string.Format ("Finished in {0} ms ({1:0.0} s total)", _sw.ElapsedMilliseconds, _elapsedMilliseconds / 1000.0));
}
return r;
}
/// <summary>
/// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?'
/// in the command text for each of the arguments and then executes that command.
/// It returns each row of the result using the mapping automatically generated for
/// the given type.
/// </summary>
/// <param name="query">
/// The fully escaped SQL.
/// </param>
/// <param name="args">
/// Arguments to substitute for the occurences of '?' in the query.
/// </param>
/// <returns>
/// An enumerable with one result for each row returned by the query.
/// </returns>
public List<T> Query<T> (string query, params object[] args) where T : new()
{
var cmd = CreateCommand (query, args);
return cmd.ExecuteQuery<T> ();
}
/// <summary>
/// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?'
/// in the command text for each of the arguments and then executes that command.
/// It returns the first column of each row of the result.
/// </summary>
/// <param name="query">
/// The fully escaped SQL.
/// </param>
/// <param name="args">
/// Arguments to substitute for the occurences of '?' in the query.
/// </param>
/// <returns>
/// An enumerable with one result for the first column of each row returned by the query.
/// </returns>
public List<T> QueryScalars<T> (string query, params object[] args)
{
var cmd = CreateCommand (query, args);
return cmd.ExecuteQueryScalars<T> ().ToList ();
}
/// <summary>
/// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?'
/// in the command text for each of the arguments and then executes that command.
/// It returns each row of the result using the mapping automatically generated for
/// the given type.
/// </summary>
/// <param name="query">
/// The fully escaped SQL.
/// </param>
/// <param name="args">
/// Arguments to substitute for the occurences of '?' in the query.
/// </param>
/// <returns>
/// An enumerable with one result for each row returned by the query.
/// The enumerator (retrieved by calling GetEnumerator() on the result of this method)
/// will call sqlite3_step on each call to MoveNext, so the database
/// connection must remain open for the lifetime of the enumerator.
/// </returns>
public IEnumerable<T> DeferredQuery<T> (string query, params object[] args) where T : new()
{
var cmd = CreateCommand (query, args);
return cmd.ExecuteDeferredQuery<T> ();
}
/// <summary>
/// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?'
/// in the command text for each of the arguments and then executes that command.
/// It returns each row of the result using the specified mapping. This function is
/// only used by libraries in order to query the database via introspection. It is
/// normally not used.
/// </summary>
/// <param name="map">
/// A <see cref="TableMapping"/> to use to convert the resulting rows
/// into objects.
/// </param>
/// <param name="query">
/// The fully escaped SQL.
/// </param>
/// <param name="args">
/// Arguments to substitute for the occurences of '?' in the query.
/// </param>
/// <returns>
/// An enumerable with one result for each row returned by the query.
/// </returns>
public List<object> Query (TableMapping map, string query, params object[] args)
{
var cmd = CreateCommand (query, args);
return cmd.ExecuteQuery<object> (map);
}
/// <summary>
/// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?'
/// in the command text for each of the arguments and then executes that command.
/// It returns each row of the result using the specified mapping. This function is
/// only used by libraries in order to query the database via introspection. It is
/// normally not used.
/// </summary>
/// <param name="map">
/// A <see cref="TableMapping"/> to use to convert the resulting rows
/// into objects.
/// </param>
/// <param name="query">
/// The fully escaped SQL.
/// </param>
/// <param name="args">
/// Arguments to substitute for the occurences of '?' in the query.
/// </param>
/// <returns>
/// An enumerable with one result for each row returned by the query.
/// The enumerator (retrieved by calling GetEnumerator() on the result of this method)
/// will call sqlite3_step on each call to MoveNext, so the database
/// connection must remain open for the lifetime of the enumerator.
/// </returns>
public IEnumerable<object> DeferredQuery (TableMapping map, string query, params object[] args)
{
var cmd = CreateCommand (query, args);
return cmd.ExecuteDeferredQuery<object> (map);
}
/// <summary>
/// Returns a queryable interface to the table represented by the given type.
/// </summary>
/// <returns>
/// A queryable object that is able to translate Where, OrderBy, and Take
/// queries into native SQL.
/// </returns>
public TableQuery<T> Table<T> () where T : new()
{
return new TableQuery<T> (this);
}
/// <summary>
/// Attempts to retrieve an object with the given primary key from the table
/// associated with the specified type. Use of this method requires that
/// the given type have a designated PrimaryKey (using the PrimaryKeyAttribute).
/// </summary>
/// <param name="pk">
/// The primary key.
/// </param>
/// <returns>
/// The object with the given primary key. Throws a not found exception
/// if the object is not found.
/// </returns>
public T Get<T> (object pk) where T : new()
{
var map = GetMapping (typeof (T));
return Query<T> (map.GetByPrimaryKeySql, pk).First ();
}
/// <summary>
/// Attempts to retrieve an object with the given primary key from the table
/// associated with the specified type. Use of this method requires that
/// the given type have a designated PrimaryKey (using the PrimaryKeyAttribute).
/// </summary>
/// <param name="pk">
/// The primary key.
/// </param>
/// <param name="map">
/// The TableMapping used to identify the table.
/// </param>
/// <returns>
/// The object with the given primary key. Throws a not found exception
/// if the object is not found.
/// </returns>
public object Get (object pk, TableMapping map)
{
return Query (map, map.GetByPrimaryKeySql, pk).First ();
}
/// <summary>
/// Attempts to retrieve the first object that matches the predicate from the table
/// associated with the specified type.
/// </summary>
/// <param name="predicate">
/// A predicate for which object to find.
/// </param>
/// <returns>
/// The object that matches the given predicate. Throws a not found exception
/// if the object is not found.
/// </returns>
public T Get<T> (Expression<Func<T, bool>> predicate) where T : new()
{
return Table<T> ().Where (predicate).First ();
}
/// <summary>
/// Attempts to retrieve an object with the given primary key from the table
/// associated with the specified type. Use of this method requires that
/// the given type have a designated PrimaryKey (using the PrimaryKeyAttribute).
/// </summary>
/// <param name="pk">
/// The primary key.
/// </param>
/// <returns>
/// The object with the given primary key or null
/// if the object is not found.
/// </returns>
public T Find<T> (object pk) where T : new()
{
var map = GetMapping (typeof (T));
return Query<T> (map.GetByPrimaryKeySql, pk).FirstOrDefault ();
}
/// <summary>
/// Attempts to retrieve an object with the given primary key from the table
/// associated with the specified type. Use of this method requires that
/// the given type have a designated PrimaryKey (using the PrimaryKeyAttribute).
/// </summary>
/// <param name="pk">
/// The primary key.
/// </param>
/// <param name="map">
/// The TableMapping used to identify the table.
/// </param>
/// <returns>
/// The object with the given primary key or null
/// if the object is not found.
/// </returns>
public object Find (object pk, TableMapping map)
{
return Query (map, map.GetByPrimaryKeySql, pk).FirstOrDefault ();
}
/// <summary>
/// Attempts to retrieve the first object that matches the predicate from the table
/// associated with the specified type.
/// </summary>
/// <param name="predicate">
/// A predicate for which object to find.
/// </param>
/// <returns>
/// The object that matches the given predicate or null
/// if the object is not found.
/// </returns>
public T Find<T> (Expression<Func<T, bool>> predicate) where T : new()
{
return Table<T> ().Where (predicate).FirstOrDefault ();
}
/// <summary>
/// Attempts to retrieve the first object that matches the query from the table
/// associated with the specified type.
/// </summary>
/// <param name="query">
/// The fully escaped SQL.
/// </param>
/// <param name="args">
/// Arguments to substitute for the occurences of '?' in the query.
/// </param>
/// <returns>
/// The object that matches the given predicate or null
/// if the object is not found.
/// </returns>
public T FindWithQuery<T> (string query, params object[] args) where T : new()
{
return Query<T> (query, args).FirstOrDefault ();
}
/// <summary>
/// Attempts to retrieve the first object that matches the query from the table
/// associated with the specified type.
/// </summary>
/// <param name="map">
/// The TableMapping used to identify the table.
/// </param>
/// <param name="query">
/// The fully escaped SQL.
/// </param>
/// <param name="args">
/// Arguments to substitute for the occurences of '?' in the query.
/// </param>
/// <returns>
/// The object that matches the given predicate or null
/// if the object is not found.
/// </returns>
public object FindWithQuery (TableMapping map, string query, params object[] args)
{
return Query (map, query, args).FirstOrDefault ();
}
/// <summary>
/// Whether <see cref="BeginTransaction"/> has been called and the database is waiting for a <see cref="Commit"/>.
/// </summary>
public bool IsInTransaction {
get { return _transactionDepth > 0; }
}
/// <summary>
/// Begins a new transaction. Call <see cref="Commit"/> to end the transaction.
/// </summary>
/// <example cref="System.InvalidOperationException">Throws if a transaction has already begun.</example>
public void BeginTransaction ()
{
// The BEGIN command only works if the transaction stack is empty,
// or in other words if there are no pending transactions.
// If the transaction stack is not empty when the BEGIN command is invoked,
// then the command fails with an error.
// Rather than crash with an error, we will just ignore calls to BeginTransaction
// that would result in an error.
if (Interlocked.CompareExchange (ref _transactionDepth, 1, 0) == 0) {
try {
Execute ("begin transaction");
}
catch (Exception ex) {
var sqlExp = ex as SQLiteException;
if (sqlExp != null) {
// It is recommended that applications respond to the errors listed below
// by explicitly issuing a ROLLBACK command.
// TODO: This rollback failsafe should be localized to all throw sites.
switch (sqlExp.Result) {
case SQLite3.Result.IOError:
case SQLite3.Result.Full:
case SQLite3.Result.Busy:
case SQLite3.Result.NoMem:
case SQLite3.Result.Interrupt:
RollbackTo (null, true);
break;
}
}
else {
// Call decrement and not VolatileWrite in case we've already
// created a transaction point in SaveTransactionPoint since the catch.
Interlocked.Decrement (ref _transactionDepth);
}
throw;
}
}
else {
// Calling BeginTransaction on an already open transaction is invalid
throw new InvalidOperationException ("Cannot begin a transaction while already in a transaction.");
}
}
/// <summary>
/// Creates a savepoint in the database at the current point in the transaction timeline.
/// Begins a new transaction if one is not in progress.
///
/// Call <see cref="RollbackTo(string)"/> to undo transactions since the returned savepoint.
/// Call <see cref="Release"/> to commit transactions after the savepoint returned here.
/// Call <see cref="Commit"/> to end the transaction, committing all changes.
/// </summary>
/// <returns>A string naming the savepoint.</returns>
public string SaveTransactionPoint ()
{
int depth = Interlocked.Increment (ref _transactionDepth) - 1;
string retVal = "S" + _rand.Next (short.MaxValue) + "D" + depth;
try {
Execute ("savepoint " + retVal);
}
catch (Exception ex) {
var sqlExp = ex as SQLiteException;
if (sqlExp != null) {
// It is recommended that applications respond to the errors listed below
// by explicitly issuing a ROLLBACK command.
// TODO: This rollback failsafe should be localized to all throw sites.
switch (sqlExp.Result) {
case SQLite3.Result.IOError:
case SQLite3.Result.Full:
case SQLite3.Result.Busy:
case SQLite3.Result.NoMem:
case SQLite3.Result.Interrupt:
RollbackTo (null, true);
break;
}
}
else {
Interlocked.Decrement (ref _transactionDepth);
}
throw;
}
return retVal;
}
/// <summary>
/// Rolls back the transaction that was begun by <see cref="BeginTransaction"/> or <see cref="SaveTransactionPoint"/>.
/// </summary>
public void Rollback ()
{
RollbackTo (null, false);
}
/// <summary>
/// Rolls back the savepoint created by <see cref="BeginTransaction"/> or SaveTransactionPoint.
/// </summary>
/// <param name="savepoint">The name of the savepoint to roll back to, as returned by <see cref="SaveTransactionPoint"/>. If savepoint is null or empty, this method is equivalent to a call to <see cref="Rollback"/></param>
public void RollbackTo (string savepoint)
{
RollbackTo (savepoint, false);
}
/// <summary>
/// Rolls back the transaction that was begun by <see cref="BeginTransaction"/>.
/// </summary>
/// <param name="savepoint">The name of the savepoint to roll back to, as returned by <see cref="SaveTransactionPoint"/>. If savepoint is null or empty, this method is equivalent to a call to <see cref="Rollback"/></param>
/// <param name="noThrow">true to avoid throwing exceptions, false otherwise</param>
void RollbackTo (string savepoint, bool noThrow)
{
// Rolling back without a TO clause rolls backs all transactions
// and leaves the transaction stack empty.
try {
if (String.IsNullOrEmpty (savepoint)) {
if (Interlocked.Exchange (ref _transactionDepth, 0) > 0) {
Execute ("rollback");
}
}
else {
DoSavePointExecute (savepoint, "rollback to ");
}
}
catch (SQLiteException) {
if (!noThrow)
throw;
}
// No need to rollback if there are no transactions open.
}
/// <summary>
/// Releases a savepoint returned from <see cref="SaveTransactionPoint"/>. Releasing a savepoint
/// makes changes since that savepoint permanent if the savepoint began the transaction,
/// or otherwise the changes are permanent pending a call to <see cref="Commit"/>.
///
/// The RELEASE command is like a COMMIT for a SAVEPOINT.
/// </summary>
/// <param name="savepoint">The name of the savepoint to release. The string should be the result of a call to <see cref="SaveTransactionPoint"/></param>
public void Release (string savepoint)
{
try {
DoSavePointExecute (savepoint, "release ");
}
catch (SQLiteException ex) {
if (ex.Result == SQLite3.Result.Busy) {
// Force a rollback since most people don't know this function can fail
// Don't call Rollback() since the _transactionDepth is 0 and it won't try
// Calling rollback makes our _transactionDepth variable correct.
// Writes to the database only happen at depth=0, so this failure will only happen then.
try {
Execute ("rollback");
}
catch {
// rollback can fail in all sorts of wonderful version-dependent ways. Let's just hope for the best
}
}
throw;
}
}
void DoSavePointExecute (string savepoint, string cmd)
{
// Validate the savepoint
int firstLen = savepoint.IndexOf ('D');
if (firstLen >= 2 && savepoint.Length > firstLen + 1) {
int depth;
if (Int32.TryParse (savepoint.Substring (firstLen + 1), out depth)) {
// TODO: Mild race here, but inescapable without locking almost everywhere.
if (0 <= depth && depth < _transactionDepth) {
#if NETFX_CORE || USE_SQLITEPCL_RAW || NETCORE
Volatile.Write (ref _transactionDepth, depth);
#elif SILVERLIGHT
_transactionDepth = depth;
#else
Thread.VolatileWrite (ref _transactionDepth, depth);
#endif
Execute (cmd + savepoint);
return;
}
}
}
throw new ArgumentException ("savePoint is not valid, and should be the result of a call to SaveTransactionPoint.", "savePoint");
}
/// <summary>
/// Commits the transaction that was begun by <see cref="BeginTransaction"/>.
/// </summary>
public void Commit ()
{
if (Interlocked.Exchange (ref _transactionDepth, 0) != 0) {
try {
Execute ("commit");
}
catch {
// Force a rollback since most people don't know this function can fail
// Don't call Rollback() since the _transactionDepth is 0 and it won't try
// Calling rollback makes our _transactionDepth variable correct.
try {
Execute ("rollback");
}
catch {
// rollback can fail in all sorts of wonderful version-dependent ways. Let's just hope for the best
}
throw;
}
}
// Do nothing on a commit with no open transaction
}
/// <summary>
/// Executes <paramref name="action"/> within a (possibly nested) transaction by wrapping it in a SAVEPOINT. If an
/// exception occurs the whole transaction is rolled back, not just the current savepoint. The exception
/// is rethrown.
/// </summary>
/// <param name="action">
/// The <see cref="Action"/> to perform within a transaction. <paramref name="action"/> can contain any number
/// of operations on the connection but should never call <see cref="BeginTransaction"/> or
/// <see cref="Commit"/>.
/// </param>
public void RunInTransaction (Action action)
{
try {
var savePoint = SaveTransactionPoint ();
action ();
Release (savePoint);
}
catch (Exception) {
Rollback ();
throw;
}
}
/// <summary>
/// Inserts all specified objects.
/// </summary>
/// <param name="objects">
/// An <see cref="IEnumerable"/> of the objects to insert.
/// <param name="runInTransaction"/>
/// A boolean indicating if the inserts should be wrapped in a transaction.
/// </param>
/// <returns>
/// The number of rows added to the table.
/// </returns>
public int InsertAll (System.Collections.IEnumerable objects, bool runInTransaction = true)
{
var c = 0;
if (runInTransaction) {
RunInTransaction (() => {
foreach (var r in objects) {
c += Insert (r);
}
});
}
else {
foreach (var r in objects) {
c += Insert (r);
}
}
return c;
}
/// <summary>
/// Inserts all specified objects.
/// </summary>
/// <param name="objects">
/// An <see cref="IEnumerable"/> of the objects to insert.
/// </param>
/// <param name="extra">
/// Literal SQL code that gets placed into the command. INSERT {extra} INTO ...
/// </param>
/// <param name="runInTransaction">
/// A boolean indicating if the inserts should be wrapped in a transaction.
/// </param>
/// <returns>
/// The number of rows added to the table.
/// </returns>
public int InsertAll (System.Collections.IEnumerable objects, string extra, bool runInTransaction = true)
{
var c = 0;
if (runInTransaction) {
RunInTransaction (() => {
foreach (var r in objects) {
c += Insert (r, extra);
}
});
}
else {
foreach (var r in objects) {
c += Insert (r, extra);
}
}
return c;
}
/// <summary>
/// Inserts all specified objects.
/// </summary>
/// <param name="objects">
/// An <see cref="IEnumerable"/> of the objects to insert.
/// </param>
/// <param name="objType">
/// The type of object to insert.
/// </param>
/// <param name="runInTransaction">
/// A boolean indicating if the inserts should be wrapped in a transaction.
/// </param>
/// <returns>
/// The number of rows added to the table.
/// </returns>
public int InsertAll (System.Collections.IEnumerable objects, Type objType, bool runInTransaction = true)
{
var c = 0;
if (runInTransaction) {
RunInTransaction (() => {
foreach (var r in objects) {
c += Insert (r, objType);
}
});
}
else {
foreach (var r in objects) {
c += Insert (r, objType);
}
}
return c;
}
/// <summary>
/// Inserts the given object (and updates its
/// auto incremented primary key if it has one).
/// The return value is the number of rows added to the table.
/// </summary>
/// <param name="obj">
/// The object to insert.
/// </param>
/// <returns>
/// The number of rows added to the table.
/// </returns>
public int Insert (object obj)
{
if (obj == null) {
return 0;
}
return Insert (obj, "", Orm.GetType (obj));
}
/// <summary>
/// Inserts the given object (and updates its
/// auto incremented primary key if it has one).
/// The return value is the number of rows added to the table.
/// If a UNIQUE constraint violation occurs with
/// some pre-existing object, this function deletes
/// the old object.
/// </summary>
/// <param name="obj">
/// The object to insert.
/// </param>
/// <returns>
/// The number of rows modified.
/// </returns>
public int InsertOrReplace (object obj)
{
if (obj == null) {
return 0;
}
return Insert (obj, "OR REPLACE", Orm.GetType (obj));
}
/// <summary>
/// Inserts the given object (and updates its
/// auto incremented primary key if it has one).
/// The return value is the number of rows added to the table.
/// </summary>
/// <param name="obj">
/// The object to insert.
/// </param>
/// <param name="objType">
/// The type of object to insert.
/// </param>
/// <returns>
/// The number of rows added to the table.
/// </returns>
public int Insert (object obj, Type objType)
{
return Insert (obj, "", objType);
}
/// <summary>
/// Inserts the given object (and updates its
/// auto incremented primary key if it has one).
/// The return value is the number of rows added to the table.
/// If a UNIQUE constraint violation occurs with
/// some pre-existing object, this function deletes
/// the old object.
/// </summary>
/// <param name="obj">
/// The object to insert.
/// </param>
/// <param name="objType">
/// The type of object to insert.
/// </param>
/// <returns>
/// The number of rows modified.
/// </returns>
public int InsertOrReplace (object obj, Type objType)
{
return Insert (obj, "OR REPLACE", objType);
}
/// <summary>
/// Inserts the given object (and updates its
/// auto incremented primary key if it has one).
/// The return value is the number of rows added to the table.
/// </summary>
/// <param name="obj">
/// The object to insert.
/// </param>
/// <param name="extra">
/// Literal SQL code that gets placed into the command. INSERT {extra} INTO ...
/// </param>
/// <returns>
/// The number of rows added to the table.
/// </returns>
public int Insert (object obj, string extra)
{
if (obj == null) {
return 0;
}
return Insert (obj, extra, Orm.GetType (obj));
}
/// <summary>
/// Inserts the given object (and updates its
/// auto incremented primary key if it has one).
/// The return value is the number of rows added to the table.
/// </summary>
/// <param name="obj">
/// The object to insert.
/// </param>
/// <param name="extra">
/// Literal SQL code that gets placed into the command. INSERT {extra} INTO ...
/// </param>
/// <param name="objType">
/// The type of object to insert.
/// </param>
/// <returns>
/// The number of rows added to the table.
/// </returns>
public int Insert (object obj, string extra, Type objType)
{
if (obj == null || objType == null) {
return 0;
}
var map = GetMapping (objType);
if (map.PK != null && map.PK.IsAutoGuid) {
if (map.PK.GetValue (obj).Equals (Guid.Empty)) {
map.PK.SetValue (obj, Guid.NewGuid ());
}
}
var replacing = string.Compare (extra, "OR REPLACE", StringComparison.OrdinalIgnoreCase) == 0;
var cols = replacing ? map.InsertOrReplaceColumns : map.InsertColumns;
var vals = new object[cols.Length];
for (var i = 0; i < vals.Length; i++) {
vals[i] = cols[i].GetValue (obj);
}
var insertCmd = GetInsertCommand (map, extra);
int count;
lock (insertCmd) {
// We lock here to protect the prepared statement returned via GetInsertCommand.
// A SQLite prepared statement can be bound for only one operation at a time.
try {
count = insertCmd.ExecuteNonQuery (vals);
}
catch (SQLiteException ex) {
if (SQLite3.ExtendedErrCode (this.Handle) == SQLite3.ExtendedResult.ConstraintNotNull) {
throw NotNullConstraintViolationException.New (ex.Result, ex.Message, map, obj);
}
throw;
}
if (map.HasAutoIncPK) {
var id = SQLite3.LastInsertRowid (Handle);
map.SetAutoIncPK (obj, id);
}
}
if (count > 0)
OnTableChanged (map, NotifyTableChangedAction.Insert);
return count;
}
readonly Dictionary<Tuple<string, string>, PreparedSqlLiteInsertCommand> _insertCommandMap = new Dictionary<Tuple<string, string>, PreparedSqlLiteInsertCommand> ();
PreparedSqlLiteInsertCommand GetInsertCommand (TableMapping map, string extra)
{
PreparedSqlLiteInsertCommand prepCmd;
var key = Tuple.Create (map.MappedType.FullName, extra);
lock (_insertCommandMap) {
if (_insertCommandMap.TryGetValue (key, out prepCmd)) {
return prepCmd;
}
}
prepCmd = CreateInsertCommand (map, extra);
lock (_insertCommandMap) {
if (_insertCommandMap.TryGetValue (key, out var existing)) {
prepCmd.Dispose ();
return existing;
}
_insertCommandMap.Add (key, prepCmd);
}
return prepCmd;
}
PreparedSqlLiteInsertCommand CreateInsertCommand (TableMapping map, string extra)
{
var cols = map.InsertColumns;
string insertSql;
if (cols.Length == 0 && map.Columns.Length == 1 && map.Columns[0].IsAutoInc) {
insertSql = string.Format ("insert {1} into \"{0}\" default values", map.TableName, extra);
}
else {
var replacing = string.Compare (extra, "OR REPLACE", StringComparison.OrdinalIgnoreCase) == 0;
if (replacing) {
cols = map.InsertOrReplaceColumns;
}
insertSql = string.Format ("insert {3} into \"{0}\"({1}) values ({2})", map.TableName,
string.Join (",", (from c in cols
select "\"" + c.Name + "\"").ToArray ()),
string.Join (",", (from c in cols
select "?").ToArray ()), extra);
}
var insertCommand = new PreparedSqlLiteInsertCommand (this, insertSql);
return insertCommand;
}
/// <summary>
/// Updates all of the columns of a table using the specified object
/// except for its primary key.
/// The object is required to have a primary key.
/// </summary>
/// <param name="obj">
/// The object to update. It must have a primary key designated using the PrimaryKeyAttribute.
/// </param>
/// <returns>
/// The number of rows updated.
/// </returns>
public int Update (object obj)
{
if (obj == null) {
return 0;
}
return Update (obj, Orm.GetType (obj));
}
/// <summary>
/// Updates all of the columns of a table using the specified object
/// except for its primary key.
/// The object is required to have a primary key.
/// </summary>
/// <param name="obj">
/// The object to update. It must have a primary key designated using the PrimaryKeyAttribute.
/// </param>
/// <param name="objType">
/// The type of object to insert.
/// </param>
/// <returns>
/// The number of rows updated.
/// </returns>
public int Update (object obj, Type objType)
{
int rowsAffected = 0;
if (obj == null || objType == null) {
return 0;
}
var map = GetMapping (objType);
var pk = map.PK;
if (pk == null) {
throw new NotSupportedException ("Cannot update " + map.TableName + ": it has no PK");
}
var cols = from p in map.Columns
where p != pk
select p;
var vals = from c in cols
select c.GetValue (obj);
var ps = new List<object> (vals);
if (ps.Count == 0) {
// There is a PK but no accompanying data,
// so reset the PK to make the UPDATE work.
cols = map.Columns;
vals = from c in cols
select c.GetValue (obj);
ps = new List<object> (vals);
}
ps.Add (pk.GetValue (obj));
var q = string.Format ("update \"{0}\" set {1} where \"{2}\" = ? ", map.TableName, string.Join (",", (from c in cols
select "\"" + c.Name + "\" = ? ").ToArray ()), pk.Name);
try {
rowsAffected = Execute (q, ps.ToArray ());
}
catch (SQLiteException ex) {
if (ex.Result == SQLite3.Result.Constraint && SQLite3.ExtendedErrCode (this.Handle) == SQLite3.ExtendedResult.ConstraintNotNull) {
throw NotNullConstraintViolationException.New (ex, map, obj);
}
throw ex;
}
if (rowsAffected > 0)
OnTableChanged (map, NotifyTableChangedAction.Update);
return rowsAffected;
}
/// <summary>
/// Updates all specified objects.
/// </summary>
/// <param name="objects">
/// An <see cref="IEnumerable"/> of the objects to insert.
/// </param>
/// <param name="runInTransaction">
/// A boolean indicating if the inserts should be wrapped in a transaction
/// </param>
/// <returns>
/// The number of rows modified.
/// </returns>
public int UpdateAll (System.Collections.IEnumerable objects, bool runInTransaction = true)
{
var c = 0;
if (runInTransaction) {
RunInTransaction (() => {
foreach (var r in objects) {
c += Update (r);
}
});
}
else {
foreach (var r in objects) {
c += Update (r);
}
}
return c;
}
/// <summary>
/// Deletes the given object from the database using its primary key.
/// </summary>
/// <param name="objectToDelete">
/// The object to delete. It must have a primary key designated using the PrimaryKeyAttribute.
/// </param>
/// <returns>
/// The number of rows deleted.
/// </returns>
public int Delete (object objectToDelete)
{
var map = GetMapping (Orm.GetType (objectToDelete));
var pk = map.PK;
if (pk == null) {
throw new NotSupportedException ("Cannot delete " + map.TableName + ": it has no PK");
}
var q = string.Format ("delete from \"{0}\" where \"{1}\" = ?", map.TableName, pk.Name);
var count = Execute (q, pk.GetValue (objectToDelete));
if (count > 0)
OnTableChanged (map, NotifyTableChangedAction.Delete);
return count;
}
/// <summary>
/// Deletes the object with the specified primary key.
/// </summary>
/// <param name="primaryKey">
/// The primary key of the object to delete.
/// </param>
/// <returns>
/// The number of objects deleted.
/// </returns>
/// <typeparam name='T'>
/// The type of object.
/// </typeparam>
public int Delete<T> (object primaryKey)
{
return Delete (primaryKey, GetMapping (typeof (T)));
}
/// <summary>
/// Deletes the object with the specified primary key.
/// </summary>
/// <param name="primaryKey">
/// The primary key of the object to delete.
/// </param>
/// <param name="map">
/// The TableMapping used to identify the table.
/// </param>
/// <returns>
/// The number of objects deleted.
/// </returns>
public int Delete (object primaryKey, TableMapping map)
{
var pk = map.PK;
if (pk == null) {
throw new NotSupportedException ("Cannot delete " + map.TableName + ": it has no PK");
}
var q = string.Format ("delete from \"{0}\" where \"{1}\" = ?", map.TableName, pk.Name);
var count = Execute (q, primaryKey);
if (count > 0)
OnTableChanged (map, NotifyTableChangedAction.Delete);
return count;
}
/// <summary>
/// Deletes all the objects from the specified table.
/// WARNING WARNING: Let me repeat. It deletes ALL the objects from the
/// specified table. Do you really want to do that?
/// </summary>
/// <returns>
/// The number of objects deleted.
/// </returns>
/// <typeparam name='T'>
/// The type of objects to delete.
/// </typeparam>
public int DeleteAll<T> ()
{
var map = GetMapping (typeof (T));
return DeleteAll (map);
}
/// <summary>
/// Deletes all the objects from the specified table.
/// WARNING WARNING: Let me repeat. It deletes ALL the objects from the
/// specified table. Do you really want to do that?
/// </summary>
/// <param name="map">
/// The TableMapping used to identify the table.
/// </param>
/// <returns>
/// The number of objects deleted.
/// </returns>
public int DeleteAll (TableMapping map)
{
var query = string.Format ("delete from \"{0}\"", map.TableName);
var count = Execute (query);
if (count > 0)
OnTableChanged (map, NotifyTableChangedAction.Delete);
return count;
}
/// <summary>
/// Backup the entire database to the specified path.
/// </summary>
/// <param name="destinationDatabasePath">Path to backup file.</param>
/// <param name="databaseName">The name of the database to backup (usually "main").</param>
public void Backup (string destinationDatabasePath, string databaseName = "main")
{
// Open the destination
var r = SQLite3.Open (destinationDatabasePath, out var destHandle);
if (r != SQLite3.Result.OK) {
throw SQLiteException.New (r, "Failed to open destination database");
}
// Init the backup
var backup = SQLite3.BackupInit (destHandle, databaseName, Handle, databaseName);
if (backup == NullBackupHandle) {
SQLite3.Close (destHandle);
throw new Exception ("Failed to create backup");
}
// Perform it
SQLite3.BackupStep (backup, -1);
SQLite3.BackupFinish (backup);
// Check for errors
r = SQLite3.GetResult (destHandle);
string msg = "";
if (r != SQLite3.Result.OK) {
msg = SQLite3.GetErrmsg (destHandle);
}
// Close everything and report errors
SQLite3.Close (destHandle);
if (r != SQLite3.Result.OK) {
throw SQLiteException.New (r, msg);
}
}
~SQLiteConnection ()
{
Dispose (false);
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
public void Close ()
{
Dispose (true);
}
protected virtual void Dispose (bool disposing)
{
var useClose2 = LibVersionNumber >= 3007014;
if (_open && Handle != NullHandle) {
try {
if (disposing) {
lock (_insertCommandMap) {
foreach (var sqlInsertCommand in _insertCommandMap.Values) {
sqlInsertCommand.Dispose ();
}
_insertCommandMap.Clear ();
}
var r = useClose2 ? SQLite3.Close2 (Handle) : SQLite3.Close (Handle);
if (r != SQLite3.Result.OK) {
string msg = SQLite3.GetErrmsg (Handle);
throw SQLiteException.New (r, msg);
}
}
else {
var r = useClose2 ? SQLite3.Close2 (Handle) : SQLite3.Close (Handle);
}
}
finally {
Handle = NullHandle;
_open = false;
}
}
}
void OnTableChanged (TableMapping table, NotifyTableChangedAction action)
{
var ev = TableChanged;
if (ev != null)
ev (this, new NotifyTableChangedEventArgs (table, action));
}
public event EventHandler<NotifyTableChangedEventArgs> TableChanged;
}
public class NotifyTableChangedEventArgs : EventArgs
{
public TableMapping Table { get; private set; }
public NotifyTableChangedAction Action { get; private set; }
public NotifyTableChangedEventArgs (TableMapping table, NotifyTableChangedAction action)
{
Table = table;
Action = action;
}
}
public enum NotifyTableChangedAction
{
Insert,
Update,
Delete,
}
/// <summary>
/// Represents a parsed connection string.
/// </summary>
public class SQLiteConnectionString
{
const string DateTimeSqliteDefaultFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff";
public string UniqueKey { get; }
public string DatabasePath { get; }
public bool StoreDateTimeAsTicks { get; }
public bool StoreTimeSpanAsTicks { get; }
public string DateTimeStringFormat { get; }
public System.Globalization.DateTimeStyles DateTimeStyle { get; }
public object Key { get; }
public SQLiteOpenFlags OpenFlags { get; }
public Action<SQLiteConnection> PreKeyAction { get; }
public Action<SQLiteConnection> PostKeyAction { get; }
public string VfsName { get; }
#if NETFX_CORE
static readonly string MetroStyleDataPath = Windows.Storage.ApplicationData.Current.LocalFolder.Path;
public static readonly string[] InMemoryDbPaths = new[]
{
":memory:",
"file::memory:"
};
public static bool IsInMemoryPath(string databasePath)
{
return InMemoryDbPaths.Any(i => i.Equals(databasePath, StringComparison.OrdinalIgnoreCase));
}
#endif
/// <summary>
/// Constructs a new SQLiteConnectionString with all the data needed to open an SQLiteConnection.
/// </summary>
/// <param name="databasePath">
/// Specifies the path to the database file.
/// </param>
/// <param name="storeDateTimeAsTicks">
/// Specifies whether to store DateTime properties as ticks (true) or strings (false). You
/// absolutely do want to store them as Ticks in all new projects. The value of false is
/// only here for backwards compatibility. There is a *significant* speed advantage, with no
/// down sides, when setting storeDateTimeAsTicks = true.
/// If you use DateTimeOffset properties, it will be always stored as ticks regardingless
/// the storeDateTimeAsTicks parameter.
/// </param>
public SQLiteConnectionString (string databasePath, bool storeDateTimeAsTicks = true)
: this (databasePath, SQLiteOpenFlags.Create | SQLiteOpenFlags.ReadWrite, storeDateTimeAsTicks)
{
}
/// <summary>
/// Constructs a new SQLiteConnectionString with all the data needed to open an SQLiteConnection.
/// </summary>
/// <param name="databasePath">
/// Specifies the path to the database file.
/// </param>
/// <param name="storeDateTimeAsTicks">
/// Specifies whether to store DateTime properties as ticks (true) or strings (false). You
/// absolutely do want to store them as Ticks in all new projects. The value of false is
/// only here for backwards compatibility. There is a *significant* speed advantage, with no
/// down sides, when setting storeDateTimeAsTicks = true.
/// If you use DateTimeOffset properties, it will be always stored as ticks regardingless
/// the storeDateTimeAsTicks parameter.
/// </param>
/// <param name="key">
/// Specifies the encryption key to use on the database. Should be a string or a byte[].
/// </param>
/// <param name="preKeyAction">
/// Executes prior to setting key for SQLCipher databases
/// </param>
/// <param name="postKeyAction">
/// Executes after setting key for SQLCipher databases
/// </param>
/// <param name="vfsName">
/// Specifies the Virtual File System to use on the database.
/// </param>
public SQLiteConnectionString (string databasePath, bool storeDateTimeAsTicks, object key = null, Action<SQLiteConnection> preKeyAction = null, Action<SQLiteConnection> postKeyAction = null, string vfsName = null)
: this (databasePath, SQLiteOpenFlags.Create | SQLiteOpenFlags.ReadWrite, storeDateTimeAsTicks, key, preKeyAction, postKeyAction, vfsName)
{
}
/// <summary>
/// Constructs a new SQLiteConnectionString with all the data needed to open an SQLiteConnection.
/// </summary>
/// <param name="databasePath">
/// Specifies the path to the database file.
/// </param>
/// <param name="openFlags">
/// Flags controlling how the connection should be opened.
/// </param>
/// <param name="storeDateTimeAsTicks">
/// Specifies whether to store DateTime properties as ticks (true) or strings (false). You
/// absolutely do want to store them as Ticks in all new projects. The value of false is
/// only here for backwards compatibility. There is a *significant* speed advantage, with no
/// down sides, when setting storeDateTimeAsTicks = true.
/// If you use DateTimeOffset properties, it will be always stored as ticks regardingless
/// the storeDateTimeAsTicks parameter.
/// </param>
/// <param name="key">
/// Specifies the encryption key to use on the database. Should be a string or a byte[].
/// </param>
/// <param name="preKeyAction">
/// Executes prior to setting key for SQLCipher databases
/// </param>
/// <param name="postKeyAction">
/// Executes after setting key for SQLCipher databases
/// </param>
/// <param name="vfsName">
/// Specifies the Virtual File System to use on the database.
/// </param>
/// <param name="dateTimeStringFormat">
/// Specifies the format to use when storing DateTime properties as strings.
/// </param>
/// <param name="storeTimeSpanAsTicks">
/// Specifies whether to store TimeSpan properties as ticks (true) or strings (false). You
/// absolutely do want to store them as Ticks in all new projects. The value of false is
/// only here for backwards compatibility. There is a *significant* speed advantage, with no
/// down sides, when setting storeTimeSpanAsTicks = true.
/// </param>
public SQLiteConnectionString (string databasePath, SQLiteOpenFlags openFlags, bool storeDateTimeAsTicks, object key = null, Action<SQLiteConnection> preKeyAction = null, Action<SQLiteConnection> postKeyAction = null, string vfsName = null, string dateTimeStringFormat = DateTimeSqliteDefaultFormat, bool storeTimeSpanAsTicks = true)
{
if (key != null && !((key is byte[]) || (key is string)))
throw new ArgumentException ("Encryption keys must be strings or byte arrays", nameof (key));
UniqueKey = string.Format ("{0}_{1:X8}", databasePath, (uint)openFlags);
StoreDateTimeAsTicks = storeDateTimeAsTicks;
StoreTimeSpanAsTicks = storeTimeSpanAsTicks;
DateTimeStringFormat = dateTimeStringFormat;
DateTimeStyle = "o".Equals (DateTimeStringFormat, StringComparison.OrdinalIgnoreCase) || "r".Equals (DateTimeStringFormat, StringComparison.OrdinalIgnoreCase) ? System.Globalization.DateTimeStyles.RoundtripKind : System.Globalization.DateTimeStyles.None;
Key = key;
PreKeyAction = preKeyAction;
PostKeyAction = postKeyAction;
OpenFlags = openFlags;
VfsName = vfsName;
#if NETFX_CORE
DatabasePath = IsInMemoryPath(databasePath)
? databasePath
: System.IO.Path.Combine(MetroStyleDataPath, databasePath);
#else
DatabasePath = databasePath;
#endif
}
}
[AttributeUsage (AttributeTargets.Class)]
public class TableAttribute : Attribute
{
public string Name { get; set; }
/// <summary>
/// Flag whether to create the table without rowid (see https://sqlite.org/withoutrowid.html)
///
/// The default is <c>false</c> so that sqlite adds an implicit <c>rowid</c> to every table created.
/// </summary>
public bool WithoutRowId { get; set; }
public TableAttribute (string name)
{
Name = name;
}
}
[AttributeUsage (AttributeTargets.Property)]
public class ColumnAttribute : Attribute
{
public string Name { get; set; }
public ColumnAttribute (string name)
{
Name = name;
}
}
[AttributeUsage (AttributeTargets.Property)]
public class PrimaryKeyAttribute : Attribute
{
}
[AttributeUsage (AttributeTargets.Property)]
public class AutoIncrementAttribute : Attribute
{
}
[AttributeUsage (AttributeTargets.Property)]
public class IndexedAttribute : Attribute
{
public string Name { get; set; }
public int Order { get; set; }
public virtual bool Unique { get; set; }
public IndexedAttribute ()
{
}
public IndexedAttribute (string name, int order)
{
Name = name;
Order = order;
}
}
[AttributeUsage (AttributeTargets.Property)]
public class IgnoreAttribute : Attribute
{
}
[AttributeUsage (AttributeTargets.Property)]
public class UniqueAttribute : IndexedAttribute
{
public override bool Unique {
get { return true; }
set { /* throw? */ }
}
}
[AttributeUsage (AttributeTargets.Property)]
public class MaxLengthAttribute : Attribute
{
public int Value { get; private set; }
public MaxLengthAttribute (int length)
{
Value = length;
}
}
public sealed class PreserveAttribute : System.Attribute
{
public bool AllMembers;
public bool Conditional;
}
/// <summary>
/// Select the collating sequence to use on a column.
/// "BINARY", "NOCASE", and "RTRIM" are supported.
/// "BINARY" is the default.
/// </summary>
[AttributeUsage (AttributeTargets.Property)]
public class CollationAttribute : Attribute
{
public string Value { get; private set; }
public CollationAttribute (string collation)
{
Value = collation;
}
}
[AttributeUsage (AttributeTargets.Property)]
public class NotNullAttribute : Attribute
{
}
[AttributeUsage (AttributeTargets.Enum)]
public class StoreAsTextAttribute : Attribute
{
}
public class TableMapping
{
public Type MappedType { get; private set; }
public string TableName { get; private set; }
public bool WithoutRowId { get; private set; }
public Column[] Columns { get; private set; }
public Column PK { get; private set; }
public string GetByPrimaryKeySql { get; private set; }
public CreateFlags CreateFlags { get; private set; }
internal MapMethod Method { get; private set; } = MapMethod.ByName;
readonly Column _autoPk;
readonly Column[] _insertColumns;
readonly Column[] _insertOrReplaceColumns;
public TableMapping (Type type, CreateFlags createFlags = CreateFlags.None)
{
MappedType = type;
CreateFlags = createFlags;
var typeInfo = type.GetTypeInfo ();
#if ENABLE_IL2CPP
var tableAttr = typeInfo.GetCustomAttribute<TableAttribute> ();
#else
var tableAttr =
typeInfo.CustomAttributes
.Where (x => x.AttributeType == typeof (TableAttribute))
.Select (x => (TableAttribute)Orm.InflateAttribute (x))
.FirstOrDefault ();
#endif
TableName = (tableAttr != null && !string.IsNullOrEmpty (tableAttr.Name)) ? tableAttr.Name : MappedType.Name;
WithoutRowId = tableAttr != null ? tableAttr.WithoutRowId : false;
var members = GetPublicMembers(type);
var cols = new List<Column>(members.Count);
foreach(var m in members)
{
var ignore = m.IsDefined(typeof(IgnoreAttribute), true);
if(!ignore)
cols.Add(new Column(m, createFlags));
}
Columns = cols.ToArray ();
foreach (var c in Columns) {
if (c.IsAutoInc && c.IsPK) {
_autoPk = c;
}
if (c.IsPK) {
PK = c;
}
}
HasAutoIncPK = _autoPk != null;
if (PK != null) {
GetByPrimaryKeySql = string.Format ("select * from \"{0}\" where \"{1}\" = ?", TableName, PK.Name);
}
else {
// People should not be calling Get/Find without a PK
GetByPrimaryKeySql = string.Format ("select * from \"{0}\" limit 1", TableName);
}
_insertColumns = Columns.Where (c => !c.IsAutoInc).ToArray ();
_insertOrReplaceColumns = Columns.ToArray ();
}
private IReadOnlyCollection<MemberInfo> GetPublicMembers(Type type)
{
if(type.Name.StartsWith("ValueTuple`"))
return GetFieldsFromValueTuple(type);
var members = new List<MemberInfo>();
var memberNames = new HashSet<string>();
var newMembers = new List<MemberInfo>();
do
{
var ti = type.GetTypeInfo();
newMembers.Clear();
newMembers.AddRange(
from p in ti.DeclaredProperties
where !memberNames.Contains(p.Name) &&
p.CanRead && p.CanWrite &&
p.GetMethod != null && p.SetMethod != null &&
p.GetMethod.IsPublic && p.SetMethod.IsPublic &&
!p.GetMethod.IsStatic && !p.SetMethod.IsStatic
select p);
members.AddRange(newMembers);
foreach(var m in newMembers)
memberNames.Add(m.Name);
type = ti.BaseType;
}
while(type != typeof(object));
return members;
}
private IReadOnlyCollection<MemberInfo> GetFieldsFromValueTuple(Type type)
{
Method = MapMethod.ByPosition;
var fields = type.GetFields();
// https://docs.microsoft.com/en-us/dotnet/api/system.valuetuple-8.rest
if(fields.Length >= 8)
throw new NotSupportedException("ValueTuple with more than 7 members not supported due to nesting; see https://docs.microsoft.com/en-us/dotnet/api/system.valuetuple-8.rest");
return fields;
}
public bool HasAutoIncPK { get; private set; }
public void SetAutoIncPK (object obj, long id)
{
if (_autoPk != null) {
_autoPk.SetValue (obj, Convert.ChangeType (id, _autoPk.ColumnType, null));
}
}
public Column[] InsertColumns {
get {
return _insertColumns;
}
}
public Column[] InsertOrReplaceColumns {
get {
return _insertOrReplaceColumns;
}
}
public Column FindColumnWithPropertyName (string propertyName)
{
var exact = Columns.FirstOrDefault (c => c.PropertyName == propertyName);
return exact;
}
public Column FindColumn (string columnName)
{
if(Method != MapMethod.ByName)
throw new InvalidOperationException($"This {nameof(TableMapping)} is not mapped by name, but {Method}.");
var exact = Columns.FirstOrDefault (c => c.Name.ToLower () == columnName.ToLower ());
return exact;
}
public class Column
{
MemberInfo _member;
public string Name { get; private set; }
public PropertyInfo PropertyInfo => _member as PropertyInfo;
public string PropertyName { get { return _member.Name; } }
public Type ColumnType { get; private set; }
public string Collation { get; private set; }
public bool IsAutoInc { get; private set; }
public bool IsAutoGuid { get; private set; }
public bool IsPK { get; private set; }
public IEnumerable<IndexedAttribute> Indices { get; set; }
public bool IsNullable { get; private set; }
public int? MaxStringLength { get; private set; }
public bool StoreAsText { get; private set; }
public Column (MemberInfo member, CreateFlags createFlags = CreateFlags.None)
{
_member = member;
var memberType = GetMemberType(member);
var colAttr = member.CustomAttributes.FirstOrDefault (x => x.AttributeType == typeof (ColumnAttribute));
#if ENABLE_IL2CPP
var ca = member.GetCustomAttribute(typeof(ColumnAttribute)) as ColumnAttribute;
Name = ca == null ? member.Name : ca.Name;
#else
Name = (colAttr != null && colAttr.ConstructorArguments.Count > 0) ?
colAttr.ConstructorArguments[0].Value?.ToString () :
member.Name;
#endif
//If this type is Nullable<T> then Nullable.GetUnderlyingType returns the T, otherwise it returns null, so get the actual type instead
ColumnType = Nullable.GetUnderlyingType (memberType) ?? memberType;
Collation = Orm.Collation (member);
IsPK = Orm.IsPK (member) ||
(((createFlags & CreateFlags.ImplicitPK) == CreateFlags.ImplicitPK) &&
string.Compare (member.Name, Orm.ImplicitPkName, StringComparison.OrdinalIgnoreCase) == 0);
var isAuto = Orm.IsAutoInc (member) || (IsPK && ((createFlags & CreateFlags.AutoIncPK) == CreateFlags.AutoIncPK));
IsAutoGuid = isAuto && ColumnType == typeof (Guid);
IsAutoInc = isAuto && !IsAutoGuid;
Indices = Orm.GetIndices (member);
if (!Indices.Any ()
&& !IsPK
&& ((createFlags & CreateFlags.ImplicitIndex) == CreateFlags.ImplicitIndex)
&& Name.EndsWith (Orm.ImplicitIndexSuffix, StringComparison.OrdinalIgnoreCase)
) {
Indices = new IndexedAttribute[] { new IndexedAttribute () };
}
IsNullable = !(IsPK || Orm.IsMarkedNotNull (member));
MaxStringLength = Orm.MaxStringLength (member);
StoreAsText = memberType.GetTypeInfo ().CustomAttributes.Any (x => x.AttributeType == typeof (StoreAsTextAttribute));
}
public Column (PropertyInfo member, CreateFlags createFlags = CreateFlags.None)
: this((MemberInfo)member, createFlags)
{ }
public void SetValue (object obj, object val)
{
if(_member is PropertyInfo propy)
{
if (val != null && ColumnType.GetTypeInfo ().IsEnum)
propy.SetValue (obj, Enum.ToObject (ColumnType, val));
else
propy.SetValue (obj, val);
}
else if(_member is FieldInfo field)
{
if (val != null && ColumnType.GetTypeInfo ().IsEnum)
field.SetValue (obj, Enum.ToObject (ColumnType, val));
else
field.SetValue (obj, val);
}
else
throw new InvalidProgramException("unreachable condition");
}
public object GetValue (object obj)
{
if(_member is PropertyInfo propy)
return propy.GetValue(obj);
else if(_member is FieldInfo field)
return field.GetValue(obj);
else
throw new InvalidProgramException("unreachable condition");
}
private static Type GetMemberType(MemberInfo m)
{
switch(m.MemberType)
{
case MemberTypes.Property: return ((PropertyInfo)m).PropertyType;
case MemberTypes.Field: return ((FieldInfo)m).FieldType;
default: throw new InvalidProgramException($"{nameof(TableMapping)} supports properties or fields only.");
}
}
}
internal enum MapMethod
{
ByName,
ByPosition
}
}
class EnumCacheInfo
{
public EnumCacheInfo (Type type)
{
var typeInfo = type.GetTypeInfo ();
IsEnum = typeInfo.IsEnum;
if (IsEnum) {
StoreAsText = typeInfo.CustomAttributes.Any (x => x.AttributeType == typeof (StoreAsTextAttribute));
if (StoreAsText) {
EnumValues = new Dictionary<int, string> ();
foreach (object e in Enum.GetValues (type)) {
EnumValues[Convert.ToInt32 (e)] = e.ToString ();
}
}
}
}
public bool IsEnum { get; private set; }
public bool StoreAsText { get; private set; }
public Dictionary<int, string> EnumValues { get; private set; }
}
static class EnumCache
{
static readonly Dictionary<Type, EnumCacheInfo> Cache = new Dictionary<Type, EnumCacheInfo> ();
public static EnumCacheInfo GetInfo<T> ()
{
return GetInfo (typeof (T));
}
public static EnumCacheInfo GetInfo (Type type)
{
lock (Cache) {
EnumCacheInfo info = null;
if (!Cache.TryGetValue (type, out info)) {
info = new EnumCacheInfo (type);
Cache[type] = info;
}
return info;
}
}
}
public static class Orm
{
public const int DefaultMaxStringLength = 140;
public const string ImplicitPkName = "Id";
public const string ImplicitIndexSuffix = "Id";
public static Type GetType (object obj)
{
if (obj == null)
return typeof (object);
var rt = obj as IReflectableType;
if (rt != null)
return rt.GetTypeInfo ().AsType ();
return obj.GetType ();
}
public static string SqlDecl (TableMapping.Column p, bool storeDateTimeAsTicks, bool storeTimeSpanAsTicks)
{
string decl = "\"" + p.Name + "\" " + SqlType (p, storeDateTimeAsTicks, storeTimeSpanAsTicks) + " ";
if (p.IsPK) {
decl += "primary key ";
}
if (p.IsAutoInc) {
decl += "autoincrement ";
}
if (!p.IsNullable) {
decl += "not null ";
}
if (!string.IsNullOrEmpty (p.Collation)) {
decl += "collate " + p.Collation + " ";
}
return decl;
}
public static string SqlType (TableMapping.Column p, bool storeDateTimeAsTicks, bool storeTimeSpanAsTicks)
{
var clrType = p.ColumnType;
if (clrType == typeof (Boolean) || clrType == typeof (Byte) || clrType == typeof (UInt16) || clrType == typeof (SByte) || clrType == typeof (Int16) || clrType == typeof (Int32) || clrType == typeof (UInt32) || clrType == typeof (Int64)) {
return "integer";
}
else if (clrType == typeof (Single) || clrType == typeof (Double) || clrType == typeof (Decimal)) {
return "float";
}
else if (clrType == typeof (String) || clrType == typeof (StringBuilder) || clrType == typeof (Uri) || clrType == typeof (UriBuilder)) {
int? len = p.MaxStringLength;
if (len.HasValue)
return "varchar(" + len.Value + ")";
return "varchar";
}
else if (clrType == typeof (TimeSpan)) {
return storeTimeSpanAsTicks ? "bigint" : "time";
}
else if (clrType == typeof (DateTime)) {
return storeDateTimeAsTicks ? "bigint" : "datetime";
}
else if (clrType == typeof (DateTimeOffset)) {
return "bigint";
}
else if (clrType.GetTypeInfo ().IsEnum) {
if (p.StoreAsText)
return "varchar";
else
return "integer";
}
else if (clrType == typeof (byte[])) {
return "blob";
}
else if (clrType == typeof (Guid)) {
return "varchar(36)";
}
else {
throw new NotSupportedException ("Don't know about " + clrType);
}
}
public static bool IsPK (MemberInfo p)
{
return p.CustomAttributes.Any (x => x.AttributeType == typeof (PrimaryKeyAttribute));
}
public static string Collation (MemberInfo p)
{
#if ENABLE_IL2CPP
return (p.GetCustomAttribute<CollationAttribute> ()?.Value) ?? "";
#else
return
(p.CustomAttributes
.Where (x => typeof (CollationAttribute) == x.AttributeType)
.Select (x => {
var args = x.ConstructorArguments;
return args.Count > 0 ? ((args[0].Value as string) ?? "") : "";
})
.FirstOrDefault ()) ?? "";
#endif
}
public static bool IsAutoInc (MemberInfo p)
{
return p.CustomAttributes.Any (x => x.AttributeType == typeof (AutoIncrementAttribute));
}
public static FieldInfo GetField (TypeInfo t, string name)
{
var f = t.GetDeclaredField (name);
if (f != null)
return f;
return GetField (t.BaseType.GetTypeInfo (), name);
}
public static PropertyInfo GetProperty (TypeInfo t, string name)
{
var f = t.GetDeclaredProperty (name);
if (f != null)
return f;
return GetProperty (t.BaseType.GetTypeInfo (), name);
}
public static object InflateAttribute (CustomAttributeData x)
{
var atype = x.AttributeType;
var typeInfo = atype.GetTypeInfo ();
#if ENABLE_IL2CPP
var r = Activator.CreateInstance (x.AttributeType);
#else
var args = x.ConstructorArguments.Select (a => a.Value).ToArray ();
var r = Activator.CreateInstance (x.AttributeType, args);
foreach (var arg in x.NamedArguments) {
if (arg.IsField) {
GetField (typeInfo, arg.MemberName).SetValue (r, arg.TypedValue.Value);
}
else {
GetProperty (typeInfo, arg.MemberName).SetValue (r, arg.TypedValue.Value);
}
}
#endif
return r;
}
public static IEnumerable<IndexedAttribute> GetIndices (MemberInfo p)
{
#if ENABLE_IL2CPP
return p.GetCustomAttributes<IndexedAttribute> ();
#else
var indexedInfo = typeof (IndexedAttribute).GetTypeInfo ();
return
p.CustomAttributes
.Where (x => indexedInfo.IsAssignableFrom (x.AttributeType.GetTypeInfo ()))
.Select (x => (IndexedAttribute)InflateAttribute (x));
#endif
}
public static int? MaxStringLength (MemberInfo p)
{
#if ENABLE_IL2CPP
return p.GetCustomAttribute<MaxLengthAttribute> ()?.Value;
#else
var attr = p.CustomAttributes.FirstOrDefault (x => x.AttributeType == typeof (MaxLengthAttribute));
if (attr != null) {
var attrv = (MaxLengthAttribute)InflateAttribute (attr);
return attrv.Value;
}
return null;
#endif
}
public static int? MaxStringLength (PropertyInfo p) => MaxStringLength((MemberInfo)p);
public static bool IsMarkedNotNull (MemberInfo p)
{
return p.CustomAttributes.Any (x => x.AttributeType == typeof (NotNullAttribute));
}
}
public partial class SQLiteCommand
{
SQLiteConnection _conn;
private List<Binding> _bindings;
public string CommandText { get; set; }
public SQLiteCommand (SQLiteConnection conn)
{
_conn = conn;
_bindings = new List<Binding> ();
CommandText = "";
}
public int ExecuteNonQuery ()
{
if (_conn.Trace) {
_conn.Tracer?.Invoke ("Executing: " + this);
}
var r = SQLite3.Result.OK;
var stmt = Prepare ();
r = SQLite3.Step (stmt);
Finalize (stmt);
if (r == SQLite3.Result.Done) {
int rowsAffected = SQLite3.Changes (_conn.Handle);
return rowsAffected;
}
else if (r == SQLite3.Result.Error) {
string msg = SQLite3.GetErrmsg (_conn.Handle);
throw SQLiteException.New (r, msg);
}
else if (r == SQLite3.Result.Constraint) {
if (SQLite3.ExtendedErrCode (_conn.Handle) == SQLite3.ExtendedResult.ConstraintNotNull) {
throw NotNullConstraintViolationException.New (r, SQLite3.GetErrmsg (_conn.Handle));
}
}
throw SQLiteException.New (r, SQLite3.GetErrmsg (_conn.Handle));
}
public IEnumerable<T> ExecuteDeferredQuery<T> ()
{
return ExecuteDeferredQuery<T> (_conn.GetMapping (typeof (T)));
}
public List<T> ExecuteQuery<T> ()
{
return ExecuteDeferredQuery<T> (_conn.GetMapping (typeof (T))).ToList ();
}
public List<T> ExecuteQuery<T> (TableMapping map)
{
return ExecuteDeferredQuery<T> (map).ToList ();
}
/// <summary>
/// Invoked every time an instance is loaded from the database.
/// </summary>
/// <param name='obj'>
/// The newly created object.
/// </param>
/// <remarks>
/// This can be overridden in combination with the <see cref="SQLiteConnection.NewCommand"/>
/// method to hook into the life-cycle of objects.
/// </remarks>
protected virtual void OnInstanceCreated (object obj)
{
// Can be overridden.
}
public IEnumerable<T> ExecuteDeferredQuery<T> (TableMapping map)
{
if (_conn.Trace) {
_conn.Tracer?.Invoke ("Executing Query: " + this);
}
var stmt = Prepare ();
try {
var cols = new TableMapping.Column[SQLite3.ColumnCount (stmt)];
var fastColumnSetters = new Action<object, Sqlite3Statement, int>[SQLite3.ColumnCount (stmt)];
if (map.Method == TableMapping.MapMethod.ByPosition)
{
Array.Copy(map.Columns, cols, Math.Min(cols.Length, map.Columns.Length));
}
else if (map.Method == TableMapping.MapMethod.ByName) {
MethodInfo getSetter = null;
if (typeof(T) != map.MappedType) {
getSetter = typeof(FastColumnSetter)
.GetMethod (nameof(FastColumnSetter.GetFastSetter),
BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod (map.MappedType);
}
for (int i = 0; i < cols.Length; i++) {
var name = SQLite3.ColumnName16 (stmt, i);
cols[i] = map.FindColumn (name);
if (cols[i] != null)
if (getSetter != null) {
fastColumnSetters[i] = (Action<object, Sqlite3Statement, int>)getSetter.Invoke(null, new object[]{ _conn, cols[i]});
}
else {
fastColumnSetters[i] = FastColumnSetter.GetFastSetter<T>(_conn, cols[i]);
}
}
}
while (SQLite3.Step (stmt) == SQLite3.Result.Row) {
var obj = Activator.CreateInstance (map.MappedType);
for (int i = 0; i < cols.Length; i++) {
if (cols[i] == null)
continue;
if (fastColumnSetters[i] != null) {
fastColumnSetters[i].Invoke (obj, stmt, i);
}
else {
var colType = SQLite3.ColumnType (stmt, i);
var val = ReadCol (stmt, i, colType, cols[i].ColumnType);
cols[i].SetValue (obj, val);
}
}
OnInstanceCreated (obj);
yield return (T)obj;
}
}
finally {
SQLite3.Finalize (stmt);
}
}
public T ExecuteScalar<T> ()
{
if (_conn.Trace) {
_conn.Tracer?.Invoke ("Executing Query: " + this);
}
T val = default (T);
var stmt = Prepare ();
try {
var r = SQLite3.Step (stmt);
if (r == SQLite3.Result.Row) {
var colType = SQLite3.ColumnType (stmt, 0);
var colval = ReadCol (stmt, 0, colType, typeof (T));
if (colval != null) {
val = (T)colval;
}
}
else if (r == SQLite3.Result.Done) {
}
else {
throw SQLiteException.New (r, SQLite3.GetErrmsg (_conn.Handle));
}
}
finally {
Finalize (stmt);
}
return val;
}
public IEnumerable<T> ExecuteQueryScalars<T> ()
{
if (_conn.Trace) {
_conn.Tracer?.Invoke ("Executing Query: " + this);
}
var stmt = Prepare ();
try {
if (SQLite3.ColumnCount (stmt) < 1) {
throw new InvalidOperationException ("QueryScalars should return at least one column");
}
while (SQLite3.Step (stmt) == SQLite3.Result.Row) {
var colType = SQLite3.ColumnType (stmt, 0);
var val = ReadCol (stmt, 0, colType, typeof (T));
if (val == null) {
yield return default (T);
}
else {
yield return (T)val;
}
}
}
finally {
Finalize (stmt);
}
}
public void Bind (string name, object val)
{
_bindings.Add (new Binding {
Name = name,
Value = val
});
}
public void Bind (object val)
{
Bind (null, val);
}
public override string ToString ()
{
var parts = new string[1 + _bindings.Count];
parts[0] = CommandText;
var i = 1;
foreach (var b in _bindings) {
parts[i] = string.Format (" {0}: {1}", i - 1, b.Value);
i++;
}
return string.Join (Environment.NewLine, parts);
}
Sqlite3Statement Prepare ()
{
var stmt = SQLite3.Prepare2 (_conn.Handle, CommandText);
BindAll (stmt);
return stmt;
}
void Finalize (Sqlite3Statement stmt)
{
SQLite3.Finalize (stmt);
}
void BindAll (Sqlite3Statement stmt)
{
int nextIdx = 1;
foreach (var b in _bindings) {
if (b.Name != null) {
b.Index = SQLite3.BindParameterIndex (stmt, b.Name);
}
else {
b.Index = nextIdx++;
}
BindParameter (stmt, b.Index, b.Value, _conn.StoreDateTimeAsTicks, _conn.DateTimeStringFormat, _conn.StoreTimeSpanAsTicks);
}
}
static IntPtr NegativePointer = new IntPtr (-1);
internal static void BindParameter (Sqlite3Statement stmt, int index, object value, bool storeDateTimeAsTicks, string dateTimeStringFormat, bool storeTimeSpanAsTicks)
{
if (value == null) {
SQLite3.BindNull (stmt, index);
}
else {
if (value is Int32) {
SQLite3.BindInt (stmt, index, (int)value);
}
else if (value is String) {
SQLite3.BindText (stmt, index, (string)value, -1, NegativePointer);
}
else if (value is Byte || value is UInt16 || value is SByte || value is Int16) {
SQLite3.BindInt (stmt, index, Convert.ToInt32 (value));
}
else if (value is Boolean) {
SQLite3.BindInt (stmt, index, (bool)value ? 1 : 0);
}
else if (value is UInt32 || value is Int64) {
SQLite3.BindInt64 (stmt, index, Convert.ToInt64 (value));
}
else if (value is Single || value is Double || value is Decimal) {
SQLite3.BindDouble (stmt, index, Convert.ToDouble (value));
}
else if (value is TimeSpan) {
if (storeTimeSpanAsTicks) {
SQLite3.BindInt64 (stmt, index, ((TimeSpan)value).Ticks);
}
else {
SQLite3.BindText (stmt, index, ((TimeSpan)value).ToString (), -1, NegativePointer);
}
}
else if (value is DateTime) {
if (storeDateTimeAsTicks) {
SQLite3.BindInt64 (stmt, index, ((DateTime)value).Ticks);
}
else {
SQLite3.BindText (stmt, index, ((DateTime)value).ToString (dateTimeStringFormat, System.Globalization.CultureInfo.InvariantCulture), -1, NegativePointer);
}
}
else if (value is DateTimeOffset) {
SQLite3.BindInt64 (stmt, index, ((DateTimeOffset)value).UtcTicks);
}
else if (value is byte[]) {
SQLite3.BindBlob (stmt, index, (byte[])value, ((byte[])value).Length, NegativePointer);
}
else if (value is Guid) {
SQLite3.BindText (stmt, index, ((Guid)value).ToString (), 72, NegativePointer);
}
else if (value is Uri) {
SQLite3.BindText (stmt, index, ((Uri)value).ToString (), -1, NegativePointer);
}
else if (value is StringBuilder) {
SQLite3.BindText (stmt, index, ((StringBuilder)value).ToString (), -1, NegativePointer);
}
else if (value is UriBuilder) {
SQLite3.BindText (stmt, index, ((UriBuilder)value).ToString (), -1, NegativePointer);
}
else {
// Now we could possibly get an enum, retrieve cached info
var valueType = value.GetType ();
var enumInfo = EnumCache.GetInfo (valueType);
if (enumInfo.IsEnum) {
var enumIntValue = Convert.ToInt32 (value);
if (enumInfo.StoreAsText)
SQLite3.BindText (stmt, index, enumInfo.EnumValues[enumIntValue], -1, NegativePointer);
else
SQLite3.BindInt (stmt, index, enumIntValue);
}
else {
throw new NotSupportedException ("Cannot store type: " + Orm.GetType (value));
}
}
}
}
class Binding
{
public string Name { get; set; }
public object Value { get; set; }
public int Index { get; set; }
}
object ReadCol (Sqlite3Statement stmt, int index, SQLite3.ColType type, Type clrType)
{
if (type == SQLite3.ColType.Null) {
return null;
}
else {
var clrTypeInfo = clrType.GetTypeInfo ();
if (clrTypeInfo.IsGenericType && clrTypeInfo.GetGenericTypeDefinition () == typeof (Nullable<>)) {
clrType = clrTypeInfo.GenericTypeArguments[0];
clrTypeInfo = clrType.GetTypeInfo ();
}
if (clrType == typeof (String)) {
return SQLite3.ColumnString (stmt, index);
}
else if (clrType == typeof (Int32)) {
return (int)SQLite3.ColumnInt (stmt, index);
}
else if (clrType == typeof (Boolean)) {
return SQLite3.ColumnInt (stmt, index) == 1;
}
else if (clrType == typeof (double)) {
return SQLite3.ColumnDouble (stmt, index);
}
else if (clrType == typeof (float)) {
return (float)SQLite3.ColumnDouble (stmt, index);
}
else if (clrType == typeof (TimeSpan)) {
if (_conn.StoreTimeSpanAsTicks) {
return new TimeSpan (SQLite3.ColumnInt64 (stmt, index));
}
else {
var text = SQLite3.ColumnString (stmt, index);
TimeSpan resultTime;
if (!TimeSpan.TryParseExact (text, "c", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.TimeSpanStyles.None, out resultTime)) {
resultTime = TimeSpan.Parse (text);
}
return resultTime;
}
}
else if (clrType == typeof (DateTime)) {
if (_conn.StoreDateTimeAsTicks) {
return new DateTime (SQLite3.ColumnInt64 (stmt, index));
}
else {
var text = SQLite3.ColumnString (stmt, index);
DateTime resultDate;
if (!DateTime.TryParseExact (text, _conn.DateTimeStringFormat, System.Globalization.CultureInfo.InvariantCulture, _conn.DateTimeStyle, out resultDate)) {
resultDate = DateTime.Parse (text);
}
return resultDate;
}
}
else if (clrType == typeof (DateTimeOffset)) {
return new DateTimeOffset (SQLite3.ColumnInt64 (stmt, index), TimeSpan.Zero);
}
else if (clrTypeInfo.IsEnum) {
if (type == SQLite3.ColType.Text) {
var value = SQLite3.ColumnString (stmt, index);
return Enum.Parse (clrType, value.ToString (), true);
}
else
return SQLite3.ColumnInt (stmt, index);
}
else if (clrType == typeof (Int64)) {
return SQLite3.ColumnInt64 (stmt, index);
}
else if (clrType == typeof (UInt32)) {
return (uint)SQLite3.ColumnInt64 (stmt, index);
}
else if (clrType == typeof (decimal)) {
return (decimal)SQLite3.ColumnDouble (stmt, index);
}
else if (clrType == typeof (Byte)) {
return (byte)SQLite3.ColumnInt (stmt, index);
}
else if (clrType == typeof (UInt16)) {
return (ushort)SQLite3.ColumnInt (stmt, index);
}
else if (clrType == typeof (Int16)) {
return (short)SQLite3.ColumnInt (stmt, index);
}
else if (clrType == typeof (sbyte)) {
return (sbyte)SQLite3.ColumnInt (stmt, index);
}
else if (clrType == typeof (byte[])) {
return SQLite3.ColumnByteArray (stmt, index);
}
else if (clrType == typeof (Guid)) {
var text = SQLite3.ColumnString (stmt, index);
return new Guid (text);
}
else if (clrType == typeof (Uri)) {
var text = SQLite3.ColumnString (stmt, index);
return new Uri (text);
}
else if (clrType == typeof (StringBuilder)) {
var text = SQLite3.ColumnString (stmt, index);
return new StringBuilder (text);
}
else if (clrType == typeof (UriBuilder)) {
var text = SQLite3.ColumnString (stmt, index);
return new UriBuilder (text);
}
else {
throw new NotSupportedException ("Don't know how to read " + clrType);
}
}
}
}
internal class FastColumnSetter
{
/// <summary>
/// Creates a delegate that can be used to quickly set object members from query columns.
///
/// Note that this frontloads the slow reflection-based type checking for columns to only happen once at the beginning of a query,
/// and then afterwards each row of the query can invoke the delegate returned by this function to get much better performance (up to 10x speed boost, depending on query size and platform).
/// </summary>
/// <typeparam name="T">The type of the destination object that the query will read into</typeparam>
/// <param name="conn">The active connection. Note that this is primarily needed in order to read preferences regarding how certain data types (such as TimeSpan / DateTime) should be encoded in the database.</param>
/// <param name="column">The table mapping used to map the statement column to a member of the destination object type</param>
/// <returns>
/// A delegate for fast-setting of object members from statement columns.
///
/// If no fast setter is available for the requested column (enums in particular cause headache), then this function returns null.
/// </returns>
internal static Action<object, Sqlite3Statement, int> GetFastSetter<T> (SQLiteConnection conn, TableMapping.Column column)
{
Action<object, Sqlite3Statement, int> fastSetter = null;
Type clrType = column.PropertyInfo.PropertyType;
var clrTypeInfo = clrType.GetTypeInfo ();
if (clrTypeInfo.IsGenericType && clrTypeInfo.GetGenericTypeDefinition () == typeof (Nullable<>)) {
clrType = clrTypeInfo.GenericTypeArguments[0];
clrTypeInfo = clrType.GetTypeInfo ();
}
if (clrType == typeof (String)) {
fastSetter = CreateTypedSetterDelegate<T, string> (column, (stmt, index) => {
return SQLite3.ColumnString (stmt, index);
});
}
else if (clrType == typeof (Int32)) {
fastSetter = CreateNullableTypedSetterDelegate<T, int> (column, (stmt, index)=>{
return SQLite3.ColumnInt (stmt, index);
});
}
else if (clrType == typeof (Boolean)) {
fastSetter = CreateNullableTypedSetterDelegate<T, bool> (column, (stmt, index) => {
return SQLite3.ColumnInt (stmt, index) == 1;
});
}
else if (clrType == typeof (double)) {
fastSetter = CreateNullableTypedSetterDelegate<T, double> (column, (stmt, index) => {
return SQLite3.ColumnDouble (stmt, index);
});
}
else if (clrType == typeof (float)) {
fastSetter = CreateNullableTypedSetterDelegate<T, float> (column, (stmt, index) => {
return (float) SQLite3.ColumnDouble (stmt, index);
});
}
else if (clrType == typeof (TimeSpan)) {
if (conn.StoreTimeSpanAsTicks) {
fastSetter = CreateNullableTypedSetterDelegate<T, TimeSpan> (column, (stmt, index) => {
return new TimeSpan (SQLite3.ColumnInt64 (stmt, index));
});
}
else {
fastSetter = CreateNullableTypedSetterDelegate<T, TimeSpan> (column, (stmt, index) => {
var text = SQLite3.ColumnString (stmt, index);
TimeSpan resultTime;
if (!TimeSpan.TryParseExact (text, "c", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.TimeSpanStyles.None, out resultTime)) {
resultTime = TimeSpan.Parse (text);
}
return resultTime;
});
}
}
else if (clrType == typeof (DateTime)) {
if (conn.StoreDateTimeAsTicks) {
fastSetter = CreateNullableTypedSetterDelegate<T, DateTime> (column, (stmt, index) => {
return new DateTime (SQLite3.ColumnInt64 (stmt, index));
});
}
else {
fastSetter = CreateNullableTypedSetterDelegate<T, DateTime> (column, (stmt, index) => {
var text = SQLite3.ColumnString (stmt, index);
DateTime resultDate;
if (!DateTime.TryParseExact (text, conn.DateTimeStringFormat, System.Globalization.CultureInfo.InvariantCulture, conn.DateTimeStyle, out resultDate)) {
resultDate = DateTime.Parse (text);
}
return resultDate;
});
}
}
else if (clrType == typeof (DateTimeOffset)) {
fastSetter = CreateNullableTypedSetterDelegate<T, DateTimeOffset> (column, (stmt, index) => {
return new DateTimeOffset (SQLite3.ColumnInt64 (stmt, index), TimeSpan.Zero);
});
}
else if (clrTypeInfo.IsEnum) {
// NOTE: Not sure of a good way (if any?) to do a strongly-typed fast setter like this for enumerated types -- for now, return null and column sets will revert back to the safe (but slow) Reflection-based method of column prop.Set()
}
else if (clrType == typeof (Int64)) {
fastSetter = CreateNullableTypedSetterDelegate<T, Int64> (column, (stmt, index) => {
return SQLite3.ColumnInt64 (stmt, index);
});
}
else if (clrType == typeof (UInt32)) {
fastSetter = CreateNullableTypedSetterDelegate<T, UInt32> (column, (stmt, index) => {
return (uint)SQLite3.ColumnInt64 (stmt, index);
});
}
else if (clrType == typeof (decimal)) {
fastSetter = CreateNullableTypedSetterDelegate<T, decimal> (column, (stmt, index) => {
return (decimal)SQLite3.ColumnDouble (stmt, index);
});
}
else if (clrType == typeof (Byte)) {
fastSetter = CreateNullableTypedSetterDelegate<T, Byte> (column, (stmt, index) => {
return (byte)SQLite3.ColumnInt (stmt, index);
});
}
else if (clrType == typeof (UInt16)) {
fastSetter = CreateNullableTypedSetterDelegate<T, UInt16> (column, (stmt, index) => {
return (ushort)SQLite3.ColumnInt (stmt, index);
});
}
else if (clrType == typeof (Int16)) {
fastSetter = CreateNullableTypedSetterDelegate<T, Int16> (column, (stmt, index) => {
return (short)SQLite3.ColumnInt (stmt, index);
});
}
else if (clrType == typeof (sbyte)) {
fastSetter = CreateNullableTypedSetterDelegate<T, sbyte> (column, (stmt, index) => {
return (sbyte)SQLite3.ColumnInt (stmt, index);
});
}
else if (clrType == typeof (byte[])) {
fastSetter = CreateTypedSetterDelegate<T, byte[]> (column, (stmt, index) => {
return SQLite3.ColumnByteArray (stmt, index);
});
}
else if (clrType == typeof (Guid)) {
fastSetter = CreateNullableTypedSetterDelegate<T, Guid> (column, (stmt, index) => {
var text = SQLite3.ColumnString (stmt, index);
return new Guid (text);
});
}
else if (clrType == typeof (Uri)) {
fastSetter = CreateTypedSetterDelegate<T, Uri> (column, (stmt, index) => {
var text = SQLite3.ColumnString (stmt, index);
return new Uri (text);
});
}
else if (clrType == typeof (StringBuilder)) {
fastSetter = CreateTypedSetterDelegate<T, StringBuilder> (column, (stmt, index) => {
var text = SQLite3.ColumnString (stmt, index);
return new StringBuilder (text);
});
}
else if (clrType == typeof (UriBuilder)) {
fastSetter = CreateTypedSetterDelegate<T, UriBuilder> (column, (stmt, index) => {
var text = SQLite3.ColumnString (stmt, index);
return new UriBuilder (text);
});
}
else {
// NOTE: Will fall back to the slow setter method in the event that we are unable to create a fast setter delegate for a particular column type
}
return fastSetter;
}
/// <summary>
/// This creates a strongly typed delegate that will permit fast setting of column values given a Sqlite3Statement and a column index.
///
/// Note that this is identical to CreateTypedSetterDelegate(), but has an extra check to see if it should create a nullable version of the delegate.
/// </summary>
/// <typeparam name="ObjectType">The type of the object whose member column is being set</typeparam>
/// <typeparam name="ColumnMemberType">The CLR type of the member in the object which corresponds to the given SQLite columnn</typeparam>
/// <param name="column">The column mapping that identifies the target member of the destination object</param>
/// <param name="getColumnValue">A lambda that can be used to retrieve the column value at query-time</param>
/// <returns>A strongly-typed delegate</returns>
private static Action<object, Sqlite3Statement, int> CreateNullableTypedSetterDelegate<ObjectType, ColumnMemberType> (TableMapping.Column column, Func<Sqlite3Statement, int, ColumnMemberType> getColumnValue) where ColumnMemberType : struct
{
var clrTypeInfo = column.PropertyInfo.PropertyType.GetTypeInfo();
bool isNullable = false;
if (clrTypeInfo.IsGenericType && clrTypeInfo.GetGenericTypeDefinition () == typeof (Nullable<>)) {
isNullable = true;
}
if (isNullable) {
var setProperty = (Action<ObjectType, ColumnMemberType?>)Delegate.CreateDelegate (
typeof (Action<ObjectType, ColumnMemberType?>), null,
column.PropertyInfo.GetSetMethod ());
return (o, stmt, i) => {
var colType = SQLite3.ColumnType (stmt, i);
if (colType != SQLite3.ColType.Null)
setProperty.Invoke ((ObjectType)o, getColumnValue.Invoke (stmt, i));
};
}
return CreateTypedSetterDelegate<ObjectType, ColumnMemberType> (column, getColumnValue);
}
/// <summary>
/// This creates a strongly typed delegate that will permit fast setting of column values given a Sqlite3Statement and a column index.
/// </summary>
/// <typeparam name="ObjectType">The type of the object whose member column is being set</typeparam>
/// <typeparam name="ColumnMemberType">The CLR type of the member in the object which corresponds to the given SQLite columnn</typeparam>
/// <param name="column">The column mapping that identifies the target member of the destination object</param>
/// <param name="getColumnValue">A lambda that can be used to retrieve the column value at query-time</param>
/// <returns>A strongly-typed delegate</returns>
private static Action<object, Sqlite3Statement, int> CreateTypedSetterDelegate<ObjectType, ColumnMemberType> (TableMapping.Column column, Func<Sqlite3Statement, int, ColumnMemberType> getColumnValue)
{
var setProperty = (Action<ObjectType, ColumnMemberType>)Delegate.CreateDelegate (
typeof (Action<ObjectType, ColumnMemberType>), null,
column.PropertyInfo.GetSetMethod ());
return (o, stmt, i) => {
var colType = SQLite3.ColumnType (stmt, i);
if (colType != SQLite3.ColType.Null)
setProperty.Invoke ((ObjectType)o, getColumnValue.Invoke (stmt, i));
};
}
}
/// <summary>
/// Since the insert never changed, we only need to prepare once.
/// </summary>
class PreparedSqlLiteInsertCommand : IDisposable
{
bool Initialized;
SQLiteConnection Connection;
string CommandText;
Sqlite3Statement Statement;
static readonly Sqlite3Statement NullStatement = default (Sqlite3Statement);
public PreparedSqlLiteInsertCommand (SQLiteConnection conn, string commandText)
{
Connection = conn;
CommandText = commandText;
}
public int ExecuteNonQuery (object[] source)
{
if (Initialized && Statement == NullStatement) {
throw new ObjectDisposedException (nameof (PreparedSqlLiteInsertCommand));
}
if (Connection.Trace) {
Connection.Tracer?.Invoke ("Executing: " + CommandText);
}
var r = SQLite3.Result.OK;
if (!Initialized) {
Statement = SQLite3.Prepare2 (Connection.Handle, CommandText);
Initialized = true;
}
//bind the values.
if (source != null) {
for (int i = 0; i < source.Length; i++) {
SQLiteCommand.BindParameter (Statement, i + 1, source[i], Connection.StoreDateTimeAsTicks, Connection.DateTimeStringFormat, Connection.StoreTimeSpanAsTicks);
}
}
r = SQLite3.Step (Statement);
if (r == SQLite3.Result.Done) {
int rowsAffected = SQLite3.Changes (Connection.Handle);
SQLite3.Reset (Statement);
return rowsAffected;
}
else if (r == SQLite3.Result.Error) {
string msg = SQLite3.GetErrmsg (Connection.Handle);
SQLite3.Reset (Statement);
throw SQLiteException.New (r, msg);
}
else if (r == SQLite3.Result.Constraint && SQLite3.ExtendedErrCode (Connection.Handle) == SQLite3.ExtendedResult.ConstraintNotNull) {
SQLite3.Reset (Statement);
throw NotNullConstraintViolationException.New (r, SQLite3.GetErrmsg (Connection.Handle));
}
else {
SQLite3.Reset (Statement);
throw SQLiteException.New (r, SQLite3.GetErrmsg (Connection.Handle));
}
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
void Dispose (bool disposing)
{
var s = Statement;
Statement = NullStatement;
Connection = null;
if (s != NullStatement) {
SQLite3.Finalize (s);
}
}
~PreparedSqlLiteInsertCommand ()
{
Dispose (false);
}
}
public enum CreateTableResult
{
Created,
Migrated,
}
public class CreateTablesResult
{
public Dictionary<Type, CreateTableResult> Results { get; private set; }
public CreateTablesResult ()
{
Results = new Dictionary<Type, CreateTableResult> ();
}
}
public abstract class BaseTableQuery
{
protected class Ordering
{
public string ColumnName { get; set; }
public bool Ascending { get; set; }
}
}
public class TableQuery<T> : BaseTableQuery, IEnumerable<T>
{
public SQLiteConnection Connection { get; private set; }
public TableMapping Table { get; private set; }
Expression _where;
List<Ordering> _orderBys;
int? _limit;
int? _offset;
BaseTableQuery _joinInner;
Expression _joinInnerKeySelector;
BaseTableQuery _joinOuter;
Expression _joinOuterKeySelector;
Expression _joinSelector;
Expression _selector;
TableQuery (SQLiteConnection conn, TableMapping table)
{
Connection = conn;
Table = table;
}
public TableQuery (SQLiteConnection conn)
{
Connection = conn;
Table = Connection.GetMapping (typeof (T));
}
public TableQuery<U> Clone<U> ()
{
var q = new TableQuery<U> (Connection, Table);
q._where = _where;
q._deferred = _deferred;
if (_orderBys != null) {
q._orderBys = new List<Ordering> (_orderBys);
}
q._limit = _limit;
q._offset = _offset;
q._joinInner = _joinInner;
q._joinInnerKeySelector = _joinInnerKeySelector;
q._joinOuter = _joinOuter;
q._joinOuterKeySelector = _joinOuterKeySelector;
q._joinSelector = _joinSelector;
q._selector = _selector;
return q;
}
/// <summary>
/// Filters the query based on a predicate.
/// </summary>
public TableQuery<T> Where (Expression<Func<T, bool>> predExpr)
{
if (predExpr.NodeType == ExpressionType.Lambda) {
var lambda = (LambdaExpression)predExpr;
var pred = lambda.Body;
var q = Clone<T> ();
q.AddWhere (pred);
return q;
}
else {
throw new NotSupportedException ("Must be a predicate");
}
}
/// <summary>
/// Delete all the rows that match this query.
/// </summary>
public int Delete ()
{
return Delete (null);
}
/// <summary>
/// Delete all the rows that match this query and the given predicate.
/// </summary>
public int Delete (Expression<Func<T, bool>> predExpr)
{
if (_limit.HasValue || _offset.HasValue)
throw new InvalidOperationException ("Cannot delete with limits or offsets");
if (_where == null && predExpr == null)
throw new InvalidOperationException ("No condition specified");
var pred = _where;
if (predExpr != null && predExpr.NodeType == ExpressionType.Lambda) {
var lambda = (LambdaExpression)predExpr;
pred = pred != null ? Expression.AndAlso (pred, lambda.Body) : lambda.Body;
}
var args = new List<object> ();
var cmdText = "delete from \"" + Table.TableName + "\"";
var w = CompileExpr (pred, args);
cmdText += " where " + w.CommandText;
var command = Connection.CreateCommand (cmdText, args.ToArray ());
int result = command.ExecuteNonQuery ();
return result;
}
/// <summary>
/// Yields a given number of elements from the query and then skips the remainder.
/// </summary>
public TableQuery<T> Take (int n)
{
var q = Clone<T> ();
q._limit = n;
return q;
}
/// <summary>
/// Skips a given number of elements from the query and then yields the remainder.
/// </summary>
public TableQuery<T> Skip (int n)
{
var q = Clone<T> ();
q._offset = n;
return q;
}
/// <summary>
/// Returns the element at a given index
/// </summary>
public T ElementAt (int index)
{
return Skip (index).Take (1).First ();
}
bool _deferred;
public TableQuery<T> Deferred ()
{
var q = Clone<T> ();
q._deferred = true;
return q;
}
/// <summary>
/// Order the query results according to a key.
/// </summary>
public TableQuery<T> OrderBy<U> (Expression<Func<T, U>> orderExpr)
{
return AddOrderBy<U> (orderExpr, true);
}
/// <summary>
/// Order the query results according to a key.
/// </summary>
public TableQuery<T> OrderByDescending<U> (Expression<Func<T, U>> orderExpr)
{
return AddOrderBy<U> (orderExpr, false);
}
/// <summary>
/// Order the query results according to a key.
/// </summary>
public TableQuery<T> ThenBy<U> (Expression<Func<T, U>> orderExpr)
{
return AddOrderBy<U> (orderExpr, true);
}
/// <summary>
/// Order the query results according to a key.
/// </summary>
public TableQuery<T> ThenByDescending<U> (Expression<Func<T, U>> orderExpr)
{
return AddOrderBy<U> (orderExpr, false);
}
TableQuery<T> AddOrderBy<U> (Expression<Func<T, U>> orderExpr, bool asc)
{
if (orderExpr.NodeType == ExpressionType.Lambda) {
var lambda = (LambdaExpression)orderExpr;
MemberExpression mem = null;
var unary = lambda.Body as UnaryExpression;
if (unary != null && unary.NodeType == ExpressionType.Convert) {
mem = unary.Operand as MemberExpression;
}
else {
mem = lambda.Body as MemberExpression;
}
if (mem != null && (mem.Expression.NodeType == ExpressionType.Parameter)) {
var q = Clone<T> ();
if (q._orderBys == null) {
q._orderBys = new List<Ordering> ();
}
q._orderBys.Add (new Ordering {
ColumnName = Table.FindColumnWithPropertyName (mem.Member.Name).Name,
Ascending = asc
});
return q;
}
else {
throw new NotSupportedException ("Order By does not support: " + orderExpr);
}
}
else {
throw new NotSupportedException ("Must be a predicate");
}
}
private void AddWhere (Expression pred)
{
if (_where == null) {
_where = pred;
}
else {
_where = Expression.AndAlso (_where, pred);
}
}
///// <summary>
///// Performs an inner join of two queries based on matching keys extracted from the elements.
///// </summary>
//public TableQuery<TResult> Join<TInner, TKey, TResult> (
// TableQuery<TInner> inner,
// Expression<Func<T, TKey>> outerKeySelector,
// Expression<Func<TInner, TKey>> innerKeySelector,
// Expression<Func<T, TInner, TResult>> resultSelector)
//{
// var q = new TableQuery<TResult> (Connection, Connection.GetMapping (typeof (TResult))) {
// _joinOuter = this,
// _joinOuterKeySelector = outerKeySelector,
// _joinInner = inner,
// _joinInnerKeySelector = innerKeySelector,
// _joinSelector = resultSelector,
// };
// return q;
//}
// Not needed until Joins are supported
// Keeping this commented out forces the default Linq to objects processor to run
//public TableQuery<TResult> Select<TResult> (Expression<Func<T, TResult>> selector)
//{
// var q = Clone<TResult> ();
// q._selector = selector;
// return q;
//}
private SQLiteCommand GenerateCommand (string selectionList)
{
if (_joinInner != null && _joinOuter != null) {
throw new NotSupportedException ("Joins are not supported.");
}
else {
var cmdText = "select " + selectionList + " from \"" + Table.TableName + "\"";
var args = new List<object> ();
if (_where != null) {
var w = CompileExpr (_where, args);
cmdText += " where " + w.CommandText;
}
if ((_orderBys != null) && (_orderBys.Count > 0)) {
var t = string.Join (", ", _orderBys.Select (o => "\"" + o.ColumnName + "\"" + (o.Ascending ? "" : " desc")).ToArray ());
cmdText += " order by " + t;
}
if (_limit.HasValue) {
cmdText += " limit " + _limit.Value;
}
if (_offset.HasValue) {
if (!_limit.HasValue) {
cmdText += " limit -1 ";
}
cmdText += " offset " + _offset.Value;
}
return Connection.CreateCommand (cmdText, args.ToArray ());
}
}
class CompileResult
{
public string CommandText { get; set; }
public object Value { get; set; }
}
private CompileResult CompileExpr (Expression expr, List<object> queryArgs)
{
if (expr == null) {
throw new NotSupportedException ("Expression is NULL");
}
else if (expr is BinaryExpression) {
var bin = (BinaryExpression)expr;
// VB turns 'x=="foo"' into 'CompareString(x,"foo",true/false)==0', so we need to unwrap it
// http://blogs.msdn.com/b/vbteam/archive/2007/09/18/vb-expression-trees-string-comparisons.aspx
if (bin.Left.NodeType == ExpressionType.Call) {
var call = (MethodCallExpression)bin.Left;
if (call.Method.DeclaringType.FullName == "Microsoft.VisualBasic.CompilerServices.Operators"
&& call.Method.Name == "CompareString")
bin = Expression.MakeBinary (bin.NodeType, call.Arguments[0], call.Arguments[1]);
}
var leftr = CompileExpr (bin.Left, queryArgs);
var rightr = CompileExpr (bin.Right, queryArgs);
//If either side is a parameter and is null, then handle the other side specially (for "is null"/"is not null")
string text;
if (leftr.CommandText == "?" && leftr.Value == null)
text = CompileNullBinaryExpression (bin, rightr);
else if (rightr.CommandText == "?" && rightr.Value == null)
text = CompileNullBinaryExpression (bin, leftr);
else
text = "(" + leftr.CommandText + " " + GetSqlName (bin) + " " + rightr.CommandText + ")";
return new CompileResult { CommandText = text };
}
else if (expr.NodeType == ExpressionType.Not) {
var operandExpr = ((UnaryExpression)expr).Operand;
var opr = CompileExpr (operandExpr, queryArgs);
object val = opr.Value;
if (val is bool)
val = !((bool)val);
return new CompileResult {
CommandText = "NOT(" + opr.CommandText + ")",
Value = val
};
}
else if (expr.NodeType == ExpressionType.Call) {
var call = (MethodCallExpression)expr;
var args = new CompileResult[call.Arguments.Count];
var obj = call.Object != null ? CompileExpr (call.Object, queryArgs) : null;
for (var i = 0; i < args.Length; i++) {
args[i] = CompileExpr (call.Arguments[i], queryArgs);
}
var sqlCall = "";
if (call.Method.Name == "Like" && args.Length == 2) {
sqlCall = "(" + args[0].CommandText + " like " + args[1].CommandText + ")";
}
else if (call.Method.Name == "Contains" && args.Length == 2) {
sqlCall = "(" + args[1].CommandText + " in " + args[0].CommandText + ")";
}
else if (call.Method.Name == "Contains" && args.Length == 1) {
if (call.Object != null && call.Object.Type == typeof (string)) {
sqlCall = "( instr(" + obj.CommandText + "," + args[0].CommandText + ") >0 )";
}
else {
sqlCall = "(" + args[0].CommandText + " in " + obj.CommandText + ")";
}
}
else if (call.Method.Name == "StartsWith" && args.Length >= 1) {
var startsWithCmpOp = StringComparison.CurrentCulture;
if (args.Length == 2) {
startsWithCmpOp = (StringComparison)args[1].Value;
}
switch (startsWithCmpOp) {
case StringComparison.Ordinal:
case StringComparison.CurrentCulture:
sqlCall = "( substr(" + obj.CommandText + ", 1, " + args[0].Value.ToString ().Length + ") = " + args[0].CommandText + ")";
break;
case StringComparison.OrdinalIgnoreCase:
case StringComparison.CurrentCultureIgnoreCase:
sqlCall = "(" + obj.CommandText + " like (" + args[0].CommandText + " || '%'))";
break;
}
}
else if (call.Method.Name == "EndsWith" && args.Length >= 1) {
var endsWithCmpOp = StringComparison.CurrentCulture;
if (args.Length == 2) {
endsWithCmpOp = (StringComparison)args[1].Value;
}
switch (endsWithCmpOp) {
case StringComparison.Ordinal:
case StringComparison.CurrentCulture:
sqlCall = "( substr(" + obj.CommandText + ", length(" + obj.CommandText + ") - " + args[0].Value.ToString ().Length + "+1, " + args[0].Value.ToString ().Length + ") = " + args[0].CommandText + ")";
break;
case StringComparison.OrdinalIgnoreCase:
case StringComparison.CurrentCultureIgnoreCase:
sqlCall = "(" + obj.CommandText + " like ('%' || " + args[0].CommandText + "))";
break;
}
}
else if (call.Method.Name == "Equals" && args.Length == 1) {
sqlCall = "(" + obj.CommandText + " = (" + args[0].CommandText + "))";
}
else if (call.Method.Name == "ToLower") {
sqlCall = "(lower(" + obj.CommandText + "))";
}
else if (call.Method.Name == "ToUpper") {
sqlCall = "(upper(" + obj.CommandText + "))";
}
else if (call.Method.Name == "Replace" && args.Length == 2) {
sqlCall = "(replace(" + obj.CommandText + "," + args[0].CommandText + "," + args[1].CommandText + "))";
}
else if (call.Method.Name == "IsNullOrEmpty" && args.Length == 1) {
sqlCall = "(" + args[0].CommandText + " is null or" + args[0].CommandText + " ='' )";
}
else {
sqlCall = call.Method.Name.ToLower () + "(" + string.Join (",", args.Select (a => a.CommandText).ToArray ()) + ")";
}
return new CompileResult { CommandText = sqlCall };
}
else if (expr.NodeType == ExpressionType.Constant) {
var c = (ConstantExpression)expr;
queryArgs.Add (c.Value);
return new CompileResult {
CommandText = "?",
Value = c.Value
};
}
else if (expr.NodeType == ExpressionType.Convert) {
var u = (UnaryExpression)expr;
var ty = u.Type;
var valr = CompileExpr (u.Operand, queryArgs);
return new CompileResult {
CommandText = valr.CommandText,
Value = valr.Value != null ? ConvertTo (valr.Value, ty) : null
};
}
else if (expr.NodeType == ExpressionType.MemberAccess) {
var mem = (MemberExpression)expr;
var paramExpr = mem.Expression as ParameterExpression;
if (paramExpr == null) {
var convert = mem.Expression as UnaryExpression;
if (convert != null && convert.NodeType == ExpressionType.Convert) {
paramExpr = convert.Operand as ParameterExpression;
}
}
if (paramExpr != null) {
//
// This is a column of our table, output just the column name
// Need to translate it if that column name is mapped
//
var columnName = Table.FindColumnWithPropertyName (mem.Member.Name).Name;
return new CompileResult { CommandText = "\"" + columnName + "\"" };
}
else {
object obj = null;
if (mem.Expression != null) {
var r = CompileExpr (mem.Expression, queryArgs);
if (r.Value == null) {
throw new NotSupportedException ("Member access failed to compile expression");
}
if (r.CommandText == "?") {
queryArgs.RemoveAt (queryArgs.Count - 1);
}
obj = r.Value;
}
//
// Get the member value
//
object val = null;
if (mem.Member is PropertyInfo) {
var m = (PropertyInfo)mem.Member;
val = m.GetValue (obj, null);
}
else if (mem.Member is FieldInfo) {
var m = (FieldInfo)mem.Member;
val = m.GetValue (obj);
}
else {
throw new NotSupportedException ("MemberExpr: " + mem.Member.GetType ());
}
//
// Work special magic for enumerables
//
if (val != null && val is System.Collections.IEnumerable && !(val is string) && !(val is System.Collections.Generic.IEnumerable<byte>)) {
var sb = new System.Text.StringBuilder ();
sb.Append ("(");
var head = "";
foreach (var a in (System.Collections.IEnumerable)val) {
queryArgs.Add (a);
sb.Append (head);
sb.Append ("?");
head = ",";
}
sb.Append (")");
return new CompileResult {
CommandText = sb.ToString (),
Value = val
};
}
else {
queryArgs.Add (val);
return new CompileResult {
CommandText = "?",
Value = val
};
}
}
}
throw new NotSupportedException ("Cannot compile: " + expr.NodeType.ToString ());
}
static object ConvertTo (object obj, Type t)
{
Type nut = Nullable.GetUnderlyingType (t);
if (nut != null) {
if (obj == null)
return null;
return Convert.ChangeType (obj, nut);
}
else {
return Convert.ChangeType (obj, t);
}
}
/// <summary>
/// Compiles a BinaryExpression where one of the parameters is null.
/// </summary>
/// <param name="expression">The expression to compile</param>
/// <param name="parameter">The non-null parameter</param>
private string CompileNullBinaryExpression (BinaryExpression expression, CompileResult parameter)
{
if (expression.NodeType == ExpressionType.Equal)
return "(" + parameter.CommandText + " is ?)";
else if (expression.NodeType == ExpressionType.NotEqual)
return "(" + parameter.CommandText + " is not ?)";
else if (expression.NodeType == ExpressionType.GreaterThan
|| expression.NodeType == ExpressionType.GreaterThanOrEqual
|| expression.NodeType == ExpressionType.LessThan
|| expression.NodeType == ExpressionType.LessThanOrEqual)
return "(" + parameter.CommandText + " < ?)"; // always false
else
throw new NotSupportedException ("Cannot compile Null-BinaryExpression with type " + expression.NodeType.ToString ());
}
string GetSqlName (Expression expr)
{
var n = expr.NodeType;
if (n == ExpressionType.GreaterThan)
return ">";
else if (n == ExpressionType.GreaterThanOrEqual) {
return ">=";
}
else if (n == ExpressionType.LessThan) {
return "<";
}
else if (n == ExpressionType.LessThanOrEqual) {
return "<=";
}
else if (n == ExpressionType.And) {
return "&";
}
else if (n == ExpressionType.AndAlso) {
return "and";
}
else if (n == ExpressionType.Or) {
return "|";
}
else if (n == ExpressionType.OrElse) {
return "or";
}
else if (n == ExpressionType.Equal) {
return "=";
}
else if (n == ExpressionType.NotEqual) {
return "!=";
}
else {
throw new NotSupportedException ("Cannot get SQL for: " + n);
}
}
/// <summary>
/// Execute SELECT COUNT(*) on the query
/// </summary>
public int Count ()
{
return GenerateCommand ("count(*)").ExecuteScalar<int> ();
}
/// <summary>
/// Execute SELECT COUNT(*) on the query with an additional WHERE clause.
/// </summary>
public int Count (Expression<Func<T, bool>> predExpr)
{
return Where (predExpr).Count ();
}
public IEnumerator<T> GetEnumerator ()
{
if (!_deferred)
return GenerateCommand ("*").ExecuteQuery<T> ().GetEnumerator ();
return GenerateCommand ("*").ExecuteDeferredQuery<T> ().GetEnumerator ();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator ()
{
return GetEnumerator ();
}
/// <summary>
/// Queries the database and returns the results as a List.
/// </summary>
public List<T> ToList ()
{
return GenerateCommand ("*").ExecuteQuery<T> ();
}
/// <summary>
/// Queries the database and returns the results as an array.
/// </summary>
public T[] ToArray ()
{
return GenerateCommand ("*").ExecuteQuery<T> ().ToArray ();
}
/// <summary>
/// Returns the first element of this query.
/// </summary>
public T First ()
{
var query = Take (1);
return query.ToList ().First ();
}
/// <summary>
/// Returns the first element of this query, or null if no element is found.
/// </summary>
public T FirstOrDefault ()
{
var query = Take (1);
return query.ToList ().FirstOrDefault ();
}
/// <summary>
/// Returns the first element of this query that matches the predicate.
/// </summary>
public T First (Expression<Func<T, bool>> predExpr)
{
return Where (predExpr).First ();
}
/// <summary>
/// Returns the first element of this query that matches the predicate, or null
/// if no element is found.
/// </summary>
public T FirstOrDefault (Expression<Func<T, bool>> predExpr)
{
return Where (predExpr).FirstOrDefault ();
}
}
public static class SQLite3
{
public enum Result : int
{
OK = 0,
Error = 1,
Internal = 2,
Perm = 3,
Abort = 4,
Busy = 5,
Locked = 6,
NoMem = 7,
ReadOnly = 8,
Interrupt = 9,
IOError = 10,
Corrupt = 11,
NotFound = 12,
Full = 13,
CannotOpen = 14,
LockErr = 15,
Empty = 16,
SchemaChngd = 17,
TooBig = 18,
Constraint = 19,
Mismatch = 20,
Misuse = 21,
NotImplementedLFS = 22,
AccessDenied = 23,
Format = 24,
Range = 25,
NonDBFile = 26,
Notice = 27,
Warning = 28,
Row = 100,
Done = 101
}
public enum ExtendedResult : int
{
IOErrorRead = (Result.IOError | (1 << 8)),
IOErrorShortRead = (Result.IOError | (2 << 8)),
IOErrorWrite = (Result.IOError | (3 << 8)),
IOErrorFsync = (Result.IOError | (4 << 8)),
IOErrorDirFSync = (Result.IOError | (5 << 8)),
IOErrorTruncate = (Result.IOError | (6 << 8)),
IOErrorFStat = (Result.IOError | (7 << 8)),
IOErrorUnlock = (Result.IOError | (8 << 8)),
IOErrorRdlock = (Result.IOError | (9 << 8)),
IOErrorDelete = (Result.IOError | (10 << 8)),
IOErrorBlocked = (Result.IOError | (11 << 8)),
IOErrorNoMem = (Result.IOError | (12 << 8)),
IOErrorAccess = (Result.IOError | (13 << 8)),
IOErrorCheckReservedLock = (Result.IOError | (14 << 8)),
IOErrorLock = (Result.IOError | (15 << 8)),
IOErrorClose = (Result.IOError | (16 << 8)),
IOErrorDirClose = (Result.IOError | (17 << 8)),
IOErrorSHMOpen = (Result.IOError | (18 << 8)),
IOErrorSHMSize = (Result.IOError | (19 << 8)),
IOErrorSHMLock = (Result.IOError | (20 << 8)),
IOErrorSHMMap = (Result.IOError | (21 << 8)),
IOErrorSeek = (Result.IOError | (22 << 8)),
IOErrorDeleteNoEnt = (Result.IOError | (23 << 8)),
IOErrorMMap = (Result.IOError | (24 << 8)),
LockedSharedcache = (Result.Locked | (1 << 8)),
BusyRecovery = (Result.Busy | (1 << 8)),
CannottOpenNoTempDir = (Result.CannotOpen | (1 << 8)),
CannotOpenIsDir = (Result.CannotOpen | (2 << 8)),
CannotOpenFullPath = (Result.CannotOpen | (3 << 8)),
CorruptVTab = (Result.Corrupt | (1 << 8)),
ReadonlyRecovery = (Result.ReadOnly | (1 << 8)),
ReadonlyCannotLock = (Result.ReadOnly | (2 << 8)),
ReadonlyRollback = (Result.ReadOnly | (3 << 8)),
AbortRollback = (Result.Abort | (2 << 8)),
ConstraintCheck = (Result.Constraint | (1 << 8)),
ConstraintCommitHook = (Result.Constraint | (2 << 8)),
ConstraintForeignKey = (Result.Constraint | (3 << 8)),
ConstraintFunction = (Result.Constraint | (4 << 8)),
ConstraintNotNull = (Result.Constraint | (5 << 8)),
ConstraintPrimaryKey = (Result.Constraint | (6 << 8)),
ConstraintTrigger = (Result.Constraint | (7 << 8)),
ConstraintUnique = (Result.Constraint | (8 << 8)),
ConstraintVTab = (Result.Constraint | (9 << 8)),
NoticeRecoverWAL = (Result.Notice | (1 << 8)),
NoticeRecoverRollback = (Result.Notice | (2 << 8))
}
public enum ConfigOption : int
{
SingleThread = 1,
MultiThread = 2,
Serialized = 3
}
const string LibraryPath = "sqlite3";
#if !USE_CSHARP_SQLITE && !USE_WP8_NATIVE_SQLITE && !USE_SQLITEPCL_RAW
[DllImport(LibraryPath, EntryPoint = "sqlite3_threadsafe", CallingConvention=CallingConvention.Cdecl)]
public static extern int Threadsafe ();
[DllImport(LibraryPath, EntryPoint = "sqlite3_open", CallingConvention=CallingConvention.Cdecl)]
public static extern Result Open ([MarshalAs(UnmanagedType.LPStr)] string filename, out IntPtr db);
[DllImport(LibraryPath, EntryPoint = "sqlite3_open_v2", CallingConvention=CallingConvention.Cdecl)]
public static extern Result Open ([MarshalAs(UnmanagedType.LPStr)] string filename, out IntPtr db, int flags, [MarshalAs (UnmanagedType.LPStr)] string zvfs);
[DllImport(LibraryPath, EntryPoint = "sqlite3_open_v2", CallingConvention = CallingConvention.Cdecl)]
public static extern Result Open(byte[] filename, out IntPtr db, int flags, [MarshalAs (UnmanagedType.LPStr)] string zvfs);
[DllImport(LibraryPath, EntryPoint = "sqlite3_open16", CallingConvention = CallingConvention.Cdecl)]
public static extern Result Open16([MarshalAs(UnmanagedType.LPWStr)] string filename, out IntPtr db);
[DllImport(LibraryPath, EntryPoint = "sqlite3_enable_load_extension", CallingConvention=CallingConvention.Cdecl)]
public static extern Result EnableLoadExtension (IntPtr db, int onoff);
[DllImport(LibraryPath, EntryPoint = "sqlite3_close", CallingConvention=CallingConvention.Cdecl)]
public static extern Result Close (IntPtr db);
[DllImport(LibraryPath, EntryPoint = "sqlite3_close_v2", CallingConvention = CallingConvention.Cdecl)]
public static extern Result Close2(IntPtr db);
[DllImport(LibraryPath, EntryPoint = "sqlite3_initialize", CallingConvention=CallingConvention.Cdecl)]
public static extern Result Initialize();
[DllImport(LibraryPath, EntryPoint = "sqlite3_shutdown", CallingConvention=CallingConvention.Cdecl)]
public static extern Result Shutdown();
[DllImport(LibraryPath, EntryPoint = "sqlite3_config", CallingConvention=CallingConvention.Cdecl)]
public static extern Result Config (ConfigOption option);
[DllImport(LibraryPath, EntryPoint = "sqlite3_win32_set_directory", CallingConvention=CallingConvention.Cdecl, CharSet=CharSet.Unicode)]
public static extern int SetDirectory (uint directoryType, string directoryPath);
[DllImport(LibraryPath, EntryPoint = "sqlite3_busy_timeout", CallingConvention=CallingConvention.Cdecl)]
public static extern Result BusyTimeout (IntPtr db, int milliseconds);
[DllImport(LibraryPath, EntryPoint = "sqlite3_changes", CallingConvention=CallingConvention.Cdecl)]
public static extern int Changes (IntPtr db);
[DllImport(LibraryPath, EntryPoint = "sqlite3_prepare_v2", CallingConvention=CallingConvention.Cdecl)]
public static extern Result Prepare2 (IntPtr db, [MarshalAs(UnmanagedType.LPStr)] string sql, int numBytes, out IntPtr stmt, IntPtr pzTail);
#if NETFX_CORE
[DllImport (LibraryPath, EntryPoint = "sqlite3_prepare_v2", CallingConvention = CallingConvention.Cdecl)]
public static extern Result Prepare2 (IntPtr db, byte[] queryBytes, int numBytes, out IntPtr stmt, IntPtr pzTail);
#endif
public static IntPtr Prepare2 (IntPtr db, string query)
{
IntPtr stmt;
#if NETFX_CORE
byte[] queryBytes = System.Text.UTF8Encoding.UTF8.GetBytes (query);
var r = Prepare2 (db, queryBytes, queryBytes.Length, out stmt, IntPtr.Zero);
#else
var r = Prepare2 (db, query, System.Text.UTF8Encoding.UTF8.GetByteCount (query), out stmt, IntPtr.Zero);
#endif
if (r != Result.OK) {
throw SQLiteException.New (r, GetErrmsg (db));
}
return stmt;
}
[DllImport(LibraryPath, EntryPoint = "sqlite3_step", CallingConvention=CallingConvention.Cdecl)]
public static extern Result Step (IntPtr stmt);
[DllImport(LibraryPath, EntryPoint = "sqlite3_reset", CallingConvention=CallingConvention.Cdecl)]
public static extern Result Reset (IntPtr stmt);
[DllImport(LibraryPath, EntryPoint = "sqlite3_finalize", CallingConvention=CallingConvention.Cdecl)]
public static extern Result Finalize (IntPtr stmt);
[DllImport(LibraryPath, EntryPoint = "sqlite3_last_insert_rowid", CallingConvention=CallingConvention.Cdecl)]
public static extern long LastInsertRowid (IntPtr db);
[DllImport(LibraryPath, EntryPoint = "sqlite3_errmsg16", CallingConvention=CallingConvention.Cdecl)]
public static extern IntPtr Errmsg (IntPtr db);
public static string GetErrmsg (IntPtr db)
{
return Marshal.PtrToStringUni (Errmsg (db));
}
[DllImport(LibraryPath, EntryPoint = "sqlite3_bind_parameter_index", CallingConvention=CallingConvention.Cdecl)]
public static extern int BindParameterIndex (IntPtr stmt, [MarshalAs(UnmanagedType.LPStr)] string name);
[DllImport(LibraryPath, EntryPoint = "sqlite3_bind_null", CallingConvention=CallingConvention.Cdecl)]
public static extern int BindNull (IntPtr stmt, int index);
[DllImport(LibraryPath, EntryPoint = "sqlite3_bind_int", CallingConvention=CallingConvention.Cdecl)]
public static extern int BindInt (IntPtr stmt, int index, int val);
[DllImport(LibraryPath, EntryPoint = "sqlite3_bind_int64", CallingConvention=CallingConvention.Cdecl)]
public static extern int BindInt64 (IntPtr stmt, int index, long val);
[DllImport(LibraryPath, EntryPoint = "sqlite3_bind_double", CallingConvention=CallingConvention.Cdecl)]
public static extern int BindDouble (IntPtr stmt, int index, double val);
[DllImport(LibraryPath, EntryPoint = "sqlite3_bind_text16", CallingConvention=CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
public static extern int BindText (IntPtr stmt, int index, [MarshalAs(UnmanagedType.LPWStr)] string val, int n, IntPtr free);
[DllImport(LibraryPath, EntryPoint = "sqlite3_bind_blob", CallingConvention=CallingConvention.Cdecl)]
public static extern int BindBlob (IntPtr stmt, int index, byte[] val, int n, IntPtr free);
[DllImport(LibraryPath, EntryPoint = "sqlite3_column_count", CallingConvention=CallingConvention.Cdecl)]
public static extern int ColumnCount (IntPtr stmt);
[DllImport(LibraryPath, EntryPoint = "sqlite3_column_name", CallingConvention=CallingConvention.Cdecl)]
public static extern IntPtr ColumnName (IntPtr stmt, int index);
[DllImport(LibraryPath, EntryPoint = "sqlite3_column_name16", CallingConvention=CallingConvention.Cdecl)]
static extern IntPtr ColumnName16Internal (IntPtr stmt, int index);
public static string ColumnName16(IntPtr stmt, int index)
{
return Marshal.PtrToStringUni(ColumnName16Internal(stmt, index));
}
[DllImport(LibraryPath, EntryPoint = "sqlite3_column_type", CallingConvention=CallingConvention.Cdecl)]
public static extern ColType ColumnType (IntPtr stmt, int index);
[DllImport(LibraryPath, EntryPoint = "sqlite3_column_int", CallingConvention=CallingConvention.Cdecl)]
public static extern int ColumnInt (IntPtr stmt, int index);
[DllImport(LibraryPath, EntryPoint = "sqlite3_column_int64", CallingConvention=CallingConvention.Cdecl)]
public static extern long ColumnInt64 (IntPtr stmt, int index);
[DllImport(LibraryPath, EntryPoint = "sqlite3_column_double", CallingConvention=CallingConvention.Cdecl)]
public static extern double ColumnDouble (IntPtr stmt, int index);
[DllImport(LibraryPath, EntryPoint = "sqlite3_column_text", CallingConvention=CallingConvention.Cdecl)]
public static extern IntPtr ColumnText (IntPtr stmt, int index);
[DllImport(LibraryPath, EntryPoint = "sqlite3_column_text16", CallingConvention=CallingConvention.Cdecl)]
public static extern IntPtr ColumnText16 (IntPtr stmt, int index);
[DllImport(LibraryPath, EntryPoint = "sqlite3_column_blob", CallingConvention=CallingConvention.Cdecl)]
public static extern IntPtr ColumnBlob (IntPtr stmt, int index);
[DllImport(LibraryPath, EntryPoint = "sqlite3_column_bytes", CallingConvention=CallingConvention.Cdecl)]
public static extern int ColumnBytes (IntPtr stmt, int index);
public static string ColumnString (IntPtr stmt, int index)
{
return Marshal.PtrToStringUni (SQLite3.ColumnText16 (stmt, index));
}
public static byte[] ColumnByteArray (IntPtr stmt, int index)
{
int length = ColumnBytes (stmt, index);
var result = new byte[length];
if (length > 0)
Marshal.Copy (ColumnBlob (stmt, index), result, 0, length);
return result;
}
[DllImport (LibraryPath, EntryPoint = "sqlite3_errcode", CallingConvention = CallingConvention.Cdecl)]
public static extern Result GetResult (Sqlite3DatabaseHandle db);
[DllImport (LibraryPath, EntryPoint = "sqlite3_extended_errcode", CallingConvention = CallingConvention.Cdecl)]
public static extern ExtendedResult ExtendedErrCode (IntPtr db);
[DllImport (LibraryPath, EntryPoint = "sqlite3_libversion_number", CallingConvention = CallingConvention.Cdecl)]
public static extern int LibVersionNumber ();
[DllImport (LibraryPath, EntryPoint = "sqlite3_backup_init", CallingConvention = CallingConvention.Cdecl)]
public static extern Sqlite3BackupHandle BackupInit (Sqlite3DatabaseHandle destDb, [MarshalAs (UnmanagedType.LPStr)] string destName, Sqlite3DatabaseHandle sourceDb, [MarshalAs (UnmanagedType.LPStr)] string sourceName);
[DllImport (LibraryPath, EntryPoint = "sqlite3_backup_step", CallingConvention = CallingConvention.Cdecl)]
public static extern Result BackupStep (Sqlite3BackupHandle backup, int numPages);
[DllImport (LibraryPath, EntryPoint = "sqlite3_backup_finish", CallingConvention = CallingConvention.Cdecl)]
public static extern Result BackupFinish (Sqlite3BackupHandle backup);
#else
public static Result Open (string filename, out Sqlite3DatabaseHandle db)
{
return (Result)Sqlite3.sqlite3_open (filename, out db);
}
public static Result Open (string filename, out Sqlite3DatabaseHandle db, int flags, string vfsName)
{
#if USE_WP8_NATIVE_SQLITE
return (Result)Sqlite3.sqlite3_open_v2(filename, out db, flags, vfsName ?? "");
#else
return (Result)Sqlite3.sqlite3_open_v2 (filename, out db, flags, vfsName);
#endif
}
public static Result Close (Sqlite3DatabaseHandle db)
{
return (Result)Sqlite3.sqlite3_close (db);
}
public static Result Close2 (Sqlite3DatabaseHandle db)
{
return (Result)Sqlite3.sqlite3_close_v2 (db);
}
public static Result BusyTimeout (Sqlite3DatabaseHandle db, int milliseconds)
{
return (Result)Sqlite3.sqlite3_busy_timeout (db, milliseconds);
}
public static int Changes (Sqlite3DatabaseHandle db)
{
return Sqlite3.sqlite3_changes (db);
}
public static Sqlite3Statement Prepare2 (Sqlite3DatabaseHandle db, string query)
{
Sqlite3Statement stmt = default (Sqlite3Statement);
#if USE_WP8_NATIVE_SQLITE || USE_SQLITEPCL_RAW
var r = Sqlite3.sqlite3_prepare_v2 (db, query, out stmt);
#else
stmt = new Sqlite3Statement();
var r = Sqlite3.sqlite3_prepare_v2(db, query, -1, ref stmt, 0);
#endif
if (r != 0) {
throw SQLiteException.New ((Result)r, GetErrmsg (db));
}
return stmt;
}
public static Result Step (Sqlite3Statement stmt)
{
return (Result)Sqlite3.sqlite3_step (stmt);
}
public static Result Reset (Sqlite3Statement stmt)
{
return (Result)Sqlite3.sqlite3_reset (stmt);
}
public static Result Finalize (Sqlite3Statement stmt)
{
return (Result)Sqlite3.sqlite3_finalize (stmt);
}
public static long LastInsertRowid (Sqlite3DatabaseHandle db)
{
return Sqlite3.sqlite3_last_insert_rowid (db);
}
public static string GetErrmsg (Sqlite3DatabaseHandle db)
{
return Sqlite3.sqlite3_errmsg (db).utf8_to_string ();
}
public static int BindParameterIndex (Sqlite3Statement stmt, string name)
{
return Sqlite3.sqlite3_bind_parameter_index (stmt, name);
}
public static int BindNull (Sqlite3Statement stmt, int index)
{
return Sqlite3.sqlite3_bind_null (stmt, index);
}
public static int BindInt (Sqlite3Statement stmt, int index, int val)
{
return Sqlite3.sqlite3_bind_int (stmt, index, val);
}
public static int BindInt64 (Sqlite3Statement stmt, int index, long val)
{
return Sqlite3.sqlite3_bind_int64 (stmt, index, val);
}
public static int BindDouble (Sqlite3Statement stmt, int index, double val)
{
return Sqlite3.sqlite3_bind_double (stmt, index, val);
}
public static int BindText (Sqlite3Statement stmt, int index, string val, int n, IntPtr free)
{
#if USE_WP8_NATIVE_SQLITE
return Sqlite3.sqlite3_bind_text(stmt, index, val, n);
#elif USE_SQLITEPCL_RAW
return Sqlite3.sqlite3_bind_text (stmt, index, val);
#else
return Sqlite3.sqlite3_bind_text(stmt, index, val, n, null);
#endif
}
public static int BindBlob (Sqlite3Statement stmt, int index, byte[] val, int n, IntPtr free)
{
#if USE_WP8_NATIVE_SQLITE
return Sqlite3.sqlite3_bind_blob(stmt, index, val, n);
#elif USE_SQLITEPCL_RAW
return Sqlite3.sqlite3_bind_blob (stmt, index, val);
#else
return Sqlite3.sqlite3_bind_blob(stmt, index, val, n, null);
#endif
}
public static int ColumnCount (Sqlite3Statement stmt)
{
return Sqlite3.sqlite3_column_count (stmt);
}
public static string ColumnName (Sqlite3Statement stmt, int index)
{
return Sqlite3.sqlite3_column_name (stmt, index).utf8_to_string ();
}
public static string ColumnName16 (Sqlite3Statement stmt, int index)
{
return Sqlite3.sqlite3_column_name (stmt, index).utf8_to_string ();
}
public static ColType ColumnType (Sqlite3Statement stmt, int index)
{
return (ColType)Sqlite3.sqlite3_column_type (stmt, index);
}
public static int ColumnInt (Sqlite3Statement stmt, int index)
{
return Sqlite3.sqlite3_column_int (stmt, index);
}
public static long ColumnInt64 (Sqlite3Statement stmt, int index)
{
return Sqlite3.sqlite3_column_int64 (stmt, index);
}
public static double ColumnDouble (Sqlite3Statement stmt, int index)
{
return Sqlite3.sqlite3_column_double (stmt, index);
}
public static string ColumnText (Sqlite3Statement stmt, int index)
{
return Sqlite3.sqlite3_column_text (stmt, index).utf8_to_string ();
}
public static string ColumnText16 (Sqlite3Statement stmt, int index)
{
return Sqlite3.sqlite3_column_text (stmt, index).utf8_to_string ();
}
public static byte[] ColumnBlob (Sqlite3Statement stmt, int index)
{
return Sqlite3.sqlite3_column_blob (stmt, index).ToArray ();
}
public static int ColumnBytes (Sqlite3Statement stmt, int index)
{
return Sqlite3.sqlite3_column_bytes (stmt, index);
}
public static string ColumnString (Sqlite3Statement stmt, int index)
{
return Sqlite3.sqlite3_column_text (stmt, index).utf8_to_string ();
}
public static byte[] ColumnByteArray (Sqlite3Statement stmt, int index)
{
int length = ColumnBytes (stmt, index);
if (length > 0) {
return ColumnBlob (stmt, index);
}
return new byte[0];
}
public static Result EnableLoadExtension (Sqlite3DatabaseHandle db, int onoff)
{
return (Result)Sqlite3.sqlite3_enable_load_extension (db, onoff);
}
public static int LibVersionNumber ()
{
return Sqlite3.sqlite3_libversion_number ();
}
public static Result GetResult (Sqlite3DatabaseHandle db)
{
return (Result)Sqlite3.sqlite3_errcode (db);
}
public static ExtendedResult ExtendedErrCode (Sqlite3DatabaseHandle db)
{
return (ExtendedResult)Sqlite3.sqlite3_extended_errcode (db);
}
public static Sqlite3BackupHandle BackupInit (Sqlite3DatabaseHandle destDb, string destName, Sqlite3DatabaseHandle sourceDb, string sourceName)
{
return Sqlite3.sqlite3_backup_init (destDb, destName, sourceDb, sourceName);
}
public static Result BackupStep (Sqlite3BackupHandle backup, int numPages)
{
return (Result)Sqlite3.sqlite3_backup_step (backup, numPages);
}
public static Result BackupFinish (Sqlite3BackupHandle backup)
{
return (Result)Sqlite3.sqlite3_backup_finish (backup);
}
#endif
public enum ColType : int
{
Integer = 1,
Float = 2,
Text = 3,
Blob = 4,
Null = 5
}
}
}
| praeclarum/sqlite-net | src/SQLite.cs | C# | mit | 158,773 |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="nl" version="2.1">
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About IadixCoin</source>
<translation>Over IadixCoin</translation>
</message>
<message>
<location line="+39"/>
<source><b>IadixCoin</b> version</source>
<translation><b>IadixCoin</b> versie</translation>
</message>
<message>
<location line="+41"/>
<source>Copyright © 2009-2014 The Bitcoin developers
Copyright © 2012-2014 The NovaCoin developers
Copyright © 2014 The IadixCoin developers</source>
<translation>Copyright © 2009-2014 De Bitcoin ontwikkelaars
Copyright © 2012-2014 De NovaCoin ontwikkelaars
Copyright © 2014 De IadixCoin ontwikkelaars</translation>
</message>
<message>
<location line="+15"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or <a href="http://www.opensource.org/licenses/mit-license.php">http://www.opensource.org/licenses/mit-license.php</a>.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (<a href="https://www.openssl.org/">https://www.openssl.org/</a>) and cryptographic software written by Eric Young (<a href="mailto:eay@cryptsoft.com">eay@cryptsoft.com</a>) and UPnP software written by Thomas Bernard.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Adresboek</translation>
</message>
<message>
<location line="+22"/>
<source>Double-click to edit address or label</source>
<translation>Dubbelklik om het adres of label te wijzigen</translation>
</message>
<message>
<location line="+24"/>
<source>Create a new address</source>
<translation>Maak een nieuw adres aan</translation>
</message>
<message>
<location line="+10"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Kopieer het huidig geselecteerde adres naar het klembord</translation>
</message>
<message>
<location line="-7"/>
<source>&New Address</source>
<translation>&Nieuw adres</translation>
</message>
<message>
<location line="-43"/>
<source>These are your IadixCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation>Dit zijn al jou IadixCoin adressen om betalingen mee te ontvangen. Je kunt iedere verzender een apart adres geven zodat je kunt volgen wie jou betaald.</translation>
</message>
<message>
<location line="+53"/>
<source>&Copy Address</source>
<translation>&Kopiëer Adres</translation>
</message>
<message>
<location line="+7"/>
<source>Show &QR Code</source>
<translation>Toon &QR Code</translation>
</message>
<message>
<location line="+7"/>
<source>Sign a message to prove you own a IadixCoin address</source>
<translation>Teken een bericht om te bewijzen dat je een IadixCoin adres bezit.</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Teken &Bericht</translation>
</message>
<message>
<location line="+17"/>
<source>Delete the currently selected address from the list</source>
<translation>Verwijder het geselecteerde adres van de lijst</translation>
</message>
<message>
<location line="-10"/>
<source>Verify a message to ensure it was signed with a specified IadixCoin address</source>
<translation>Verifieer een bericht om zeker te zijn dat deze is ondertekend met een specifiek IadixCoin adres</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>&Verifieer Bericht</translation>
</message>
<message>
<location line="+10"/>
<source>&Delete</source>
<translation>&Verwijder</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+66"/>
<source>Copy &Label</source>
<translation>Kopiëer &Label</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>&Bewerk</translation>
</message>
<message>
<location line="+248"/>
<source>Export Address Book Data</source>
<translation>Exporteer Adresboek Data</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Kommagescheiden bestand (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Fout bij exporteren</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Kan niet schrijven naat bestand %1</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+145"/>
<source>Label</source>
<translation>Label</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(geen label)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Wachtwoordscherm</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Voer wachtwoord in</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Nieuw wachtwoord</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Herhaal wachtwoord</translation>
</message>
<message>
<location line="+33"/>
<source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source>
<translation>Bedoeld om het command 'sendmoney' uit te schakelen indien het OS niet meer veilig is. Geeft geen echte beveiliging.</translation>
</message>
<message>
<location line="+3"/>
<source>For staking only</source>
<translation>Alleen voor staking</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+38"/>
<source>Encrypt wallet</source>
<translation>Versleutel portemonnee</translation>
</message>
<message>
<location line="+7"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Deze operatie vereist uw portemonneewachtwoord om de portemonnee te openen.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Open portemonnee</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Deze operatie vereist uw portemonneewachtwoord om de portemonnee te ontsleutelen</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Ontsleutel portemonnee</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Wijzig wachtwoord</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Vul uw oude en nieuwe portemonneewachtwoord in.</translation>
</message>
<message>
<location line="+45"/>
<source>Confirm wallet encryption</source>
<translation>Bevestig versleuteling van de portemonnee</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!</source>
<translation>Waarschuwing: Als je je portemonnee versleuteld en je verliest je wachtwoord zul je <b>AL JE MUNTEN VERLIEZEN</b>!</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Weet u zeker dat u uw portemonnee wilt versleutelen?</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation>BELANGRIJK: Elke eerder gemaakte backup van uw portemonneebestand dient u te vervangen door het nieuw gegenereerde, versleutelde portemonneebestand. Om veiligheidsredenen zullen eerdere backups van het niet-versleutelde portemonneebestand onbruikbaar worden zodra u uw nieuwe, versleutelde, portemonnee begint te gebruiken.</translation>
</message>
<message>
<location line="+103"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Waarschuwing: De Caps-Lock-toets staat aan!</translation>
</message>
<message>
<location line="-133"/>
<location line="+60"/>
<source>Wallet encrypted</source>
<translation>Portemonnee versleuteld</translation>
</message>
<message>
<location line="-140"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>ten or more random characters</b>, or <b>eight or more words</b>.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<source>IadixCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source>
<translation>IadixCoin zal nu sluiten om het versleutel proces te voltooien. Onthou dat het versleutelen van je portemonnee je niet volledig beschermt tegen diefstal van munten door malware op je computer.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+44"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Portemonneeversleuteling mislukt</translation>
</message>
<message>
<location line="-56"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Portemonneeversleuteling mislukt door een interne fout. Uw portemonnee is niet versleuteld.</translation>
</message>
<message>
<location line="+7"/>
<location line="+50"/>
<source>The supplied passphrases do not match.</source>
<translation>De opgegeven wachtwoorden komen niet overeen</translation>
</message>
<message>
<location line="-38"/>
<source>Wallet unlock failed</source>
<translation>Portemonnee openen mislukt</translation>
</message>
<message>
<location line="+1"/>
<location line="+12"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Het opgegeven wachtwoord voor de portemonnee-ontsleuteling is niet correct.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Portemonnee-ontsleuteling mislukt</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Portemonneewachtwoord is met succes gewijzigd.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+297"/>
<source>Sign &message...</source>
<translation>&Onderteken bericht...</translation>
</message>
<message>
<location line="-64"/>
<source>Show general overview of wallet</source>
<translation>Toon algemeen overzicht van de portemonnee</translation>
</message>
<message>
<location line="+17"/>
<source>&Transactions</source>
<translation>&Transacties</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Blader door transactieverleden</translation>
</message>
<message>
<location line="+5"/>
<source>&Address Book</source>
<translation>&Adresboek</translation>
</message>
<message>
<location line="+1"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Wijzig de lijst met bewaarde adressen en labels</translation>
</message>
<message>
<location line="-18"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Toon de lijst aan adressen voor ontvangen betalingen</translation>
</message>
<message>
<location line="+34"/>
<source>E&xit</source>
<translation>&Afsluiten</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Programma afsluiten</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about IadixCoin</source>
<translation>Toon informatie over IadixCoin</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>Over &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Toon informatie over Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Opties...</translation>
</message>
<message>
<location line="+4"/>
<source>&Encrypt Wallet...</source>
<translation>&Versleutel Portemonnee...</translation>
</message>
<message>
<location line="+2"/>
<source>&Backup Wallet...</source>
<translation>&Backup Portemonnee...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Wijzig Wachtwoord</translation>
</message>
<message>
<location line="+9"/>
<source>&Export...</source>
<translation>&Exporteren...</translation>
</message>
<message>
<location line="-55"/>
<source>Send coins to a IadixCoin address</source>
<translation>Verstuur munten naar een IadixCoin adres</translation>
</message>
<message>
<location line="+39"/>
<source>Modify configuration options for IadixCoin</source>
<translation>Verander configuratie opties voor IadixCoin</translation>
</message>
<message>
<location line="+17"/>
<source>Export the data in the current tab to a file</source>
<translation>Exporteer de data in de huidige tab naar een bestand</translation>
</message>
<message>
<location line="-13"/>
<source>Encrypt or decrypt wallet</source>
<translation>Versleutel of ontsleutel de portemonnee</translation>
</message>
<message>
<location line="+2"/>
<source>Backup wallet to another location</source>
<translation>Backup portemonnee naar een andere locatie</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Wijzig het wachtwoord voor uw portemonneversleuteling</translation>
</message>
<message>
<location line="+10"/>
<source>&Debug window</source>
<translation>&Debugscherm</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Open debugging en diagnostische console</translation>
</message>
<message>
<location line="-5"/>
<source>&Verify message...</source>
<translation>&Verifiëer bericht...</translation>
</message>
<message>
<location line="-214"/>
<location line="+555"/>
<source>IadixCoin</source>
<translation>IadixCoin</translation>
</message>
<message>
<location line="-555"/>
<source>Wallet</source>
<translation>Portemonnee</translation>
</message>
<message>
<location line="+193"/>
<source>&About IadixCoin</source>
<translation>&Over IadixCoin</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&Toon / Verberg</translation>
</message>
<message>
<location line="+8"/>
<source>Unlock wallet</source>
<translation>Open portemonnee</translation>
</message>
<message>
<location line="+1"/>
<source>&Lock Wallet</source>
<translation>&Sluit portemonnee</translation>
</message>
<message>
<location line="+1"/>
<source>Lock wallet</source>
<translation>Sluit portemonnee</translation>
</message>
<message>
<location line="+32"/>
<source>&File</source>
<translation>&Bestand</translation>
</message>
<message>
<location line="+8"/>
<source>&Settings</source>
<translation>&Instellingen</translation>
</message>
<message>
<location line="+8"/>
<source>&Help</source>
<translation>&Hulp</translation>
</message>
<message>
<location line="+17"/>
<source>Tabs toolbar</source>
<translation>Tab-werkbalk</translation>
</message>
<message>
<location line="+46"/>
<location line="+9"/>
<source>[testnet]</source>
<translation>[testnetwerk]</translation>
</message>
<message>
<location line="+0"/>
<location line="+58"/>
<source>IadixCoin client</source>
<translation>IadixCoin client</translation>
</message>
<message numerus="yes">
<location line="+70"/>
<source>%n active connection(s) to IadixCoin network</source>
<translation><numerusform>%n actieve verbinding naar IadixCoin netwerk</numerusform><numerusform>%n actieve verbindingen naar IadixCoin netwerk</numerusform></translation>
</message>
<message>
<location line="+488"/>
<source>Staking.<br>Your weight is %1<br>Network weight is %2<br>Expected time to earn reward is %3</source>
<translation>Staking. <br> Uw gewicht wordt %1 <br> Network gewicht is %2 <br> Verwachte tijd om beloning te verdienen is %3</translation>
</message>
<message>
<location line="+6"/>
<source>Not staking because wallet is locked</source>
<translation>Niet staking omdat portemonnee beveiligd is</translation>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is offline</source>
<translation>Niet staking omdat portemonnee offline is</translation>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is syncing</source>
<translation>Niet staking omdat portemonnee aan het synchroniseren is.</translation>
</message>
<message>
<location line="+2"/>
<source>Not staking because you don't have mature coins</source>
<translation>Niet staking omdat je geen mature munten hebt</translation>
</message>
<message>
<location line="-812"/>
<source>&Dashboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>&Receive</source>
<translation>&Ontvangen</translation>
</message>
<message>
<location line="+6"/>
<source>&Send</source>
<translation>&Verzenden</translation>
</message>
<message>
<location line="+49"/>
<source>&Unlock Wallet...</source>
<translation>Ontgrendel portemonnee...</translation>
</message>
<message>
<location line="+277"/>
<source>Up to date</source>
<translation>Bijgewerkt</translation>
</message>
<message>
<location line="+43"/>
<source>Catching up...</source>
<translation>Aan het bijwerken...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation>Bevestig transactie kosten</translation>
</message>
<message>
<location line="+27"/>
<source>Sent transaction</source>
<translation>Verzonden transactie</translation>
</message>
<message>
<location line="+1"/>
<source>Incoming transaction</source>
<translation>Binnenkomende transactie</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Datum: %1
Bedrag: %2
Type: %3
Adres: %4
</translation>
</message>
<message>
<location line="+100"/>
<location line="+15"/>
<source>URI handling</source>
<translation>URI-behandeling</translation>
</message>
<message>
<location line="-15"/>
<location line="+15"/>
<source>URI can not be parsed! This can be caused by an invalid IadixCoin address or malformed URI parameters.</source>
<translation>URI kan niet ontleedt worden! Mogelijke oorzaken zijn een ongeldig IadixCoin adres of incorrecte URI parameters.</translation>
</message>
<message>
<location line="+9"/>
<source>Wallet is <b>not encrypted</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Portemonnee is <b>versleuteld</b> en momenteel <b>geopend</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Portemonnee is <b>versleuteld</b> en momenteel <b>gesloten</b></translation>
</message>
<message>
<location line="+24"/>
<source>Backup Wallet</source>
<translation>Backup Portemonnee</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>Portemonnee bestanden (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>Backup mislukt</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>Er was een fout opgetreden bij het opslaan van de wallet data naar de nieuwe locatie.</translation>
</message>
<message numerus="yes">
<location line="+91"/>
<source>%n second(s)</source>
<translation><numerusform>%n seconden</numerusform><numerusform>%n seconden</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n minute(s)</source>
<translation><numerusform>%n minuut</numerusform><numerusform>%n minuten</numerusform></translation>
</message>
<message numerus="yes">
<location line="-429"/>
<location line="+433"/>
<source>%n hour(s)</source>
<translation><numerusform>%n uur</numerusform><numerusform>%n uur</numerusform></translation>
</message>
<message>
<location line="-456"/>
<source>Processed %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+27"/>
<location line="+433"/>
<source>%n day(s)</source>
<translation><numerusform>%n dag</numerusform><numerusform>%n dagen</numerusform></translation>
</message>
<message numerus="yes">
<location line="-429"/>
<location line="+6"/>
<source>%n week(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+0"/>
<source>%1 and %2</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+0"/>
<source>%n year(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>%1 behind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Last received block was generated %1 ago.</source>
<translation>Laatst ontvangen block was %1 geleden</translation>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation>Waarschuwing</translation>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation>Informatie</translation>
</message>
<message>
<location line="+69"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+324"/>
<source>Not staking</source>
<translation>Niet aan het staken.</translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+104"/>
<source>A fatal error occurred. IadixCoin can no longer continue safely and will quit.</source>
<translation>Een fatale fout . Iadixcoin kan niet langer veilig doorgaan en sluit af.</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+110"/>
<source>Network Alert</source>
<translation>Netwerkwaarschuwing</translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<location filename="../forms/coincontroldialog.ui" line="+14"/>
<source>Coin Control</source>
<translation>Coin controle opties</translation>
</message>
<message>
<location line="+31"/>
<source>Quantity:</source>
<translation>Kwantiteit</translation>
</message>
<message>
<location line="+32"/>
<source>Bytes:</source>
<translation>Bytes:</translation>
</message>
<message>
<location line="+48"/>
<source>Amount:</source>
<translation>Bedrag:</translation>
</message>
<message>
<location line="+32"/>
<source>Priority:</source>
<translation>Prioriteit:</translation>
</message>
<message>
<location line="+48"/>
<source>Fee:</source>
<translation>Vergoeding:</translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation>Lage uitvoer:</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="+537"/>
<source>no</source>
<translation>nee</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="+51"/>
<source>After Fee:</source>
<translation>Na vergoeding:</translation>
</message>
<message>
<location line="+35"/>
<source>Change:</source>
<translation>Wijzigen:</translation>
</message>
<message>
<location line="+69"/>
<source>(un)select all</source>
<translation>(de)selecteer alles</translation>
</message>
<message>
<location line="+13"/>
<source>Tree mode</source>
<translation>Boom modus</translation>
</message>
<message>
<location line="+16"/>
<source>List mode</source>
<translation>Lijst modus</translation>
</message>
<message>
<location line="+45"/>
<source>Amount</source>
<translation>Bedrag</translation>
</message>
<message>
<location line="+5"/>
<source>Label</source>
<translation>Label</translation>
</message>
<message>
<location line="+5"/>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<location line="+5"/>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<location line="+5"/>
<source>Confirmations</source>
<translation>Bevestigingen</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed</source>
<translation>Bevestigd</translation>
</message>
<message>
<location line="+5"/>
<source>Priority</source>
<translation>Prioriteit</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="-500"/>
<source>Copy address</source>
<translation>Kopieer adres</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Kopieer label</translation>
</message>
<message>
<location line="+1"/>
<location line="+26"/>
<source>Copy amount</source>
<translation>Kopieer bedrag</translation>
</message>
<message>
<location line="-25"/>
<source>Copy transaction ID</source>
<translation>Kopieer transactie-ID</translation>
</message>
<message>
<location line="+24"/>
<source>Copy quantity</source>
<translation>Kopieer aantal</translation>
</message>
<message>
<location line="+2"/>
<source>Copy fee</source>
<translation>Kopieer vergoeding</translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation>Kopieer na vergoeding</translation>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation>Kopieer bytes</translation>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation>Kopieer prioriteit</translation>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation>Kopieer lage uitvoer</translation>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation>Kopieer wijzig</translation>
</message>
<message>
<location line="+317"/>
<source>highest</source>
<translation>hoogste</translation>
</message>
<message>
<location line="+1"/>
<source>high</source>
<translation>hoog</translation>
</message>
<message>
<location line="+1"/>
<source>medium-high</source>
<translation>gemiddeld hoog</translation>
</message>
<message>
<location line="+1"/>
<source>medium</source>
<translation>gemiddeld</translation>
</message>
<message>
<location line="+4"/>
<source>low-medium</source>
<translation>laag gemiddeld</translation>
</message>
<message>
<location line="+1"/>
<source>low</source>
<translation>laag</translation>
</message>
<message>
<location line="+1"/>
<source>lowest</source>
<translation>laagste</translation>
</message>
<message>
<location line="+140"/>
<source>DUST</source>
<translation>STOF</translation>
</message>
<message>
<location line="+0"/>
<source>yes</source>
<translation>ja</translation>
</message>
<message>
<location line="+10"/>
<source>This label turns red, if the transaction size is bigger than 10000 bytes.
This means a fee of at least %1 per kb is required.
Can vary +/- 1 Byte per input.</source>
<translation>Dit label wordt rood, als de transactie grootte groter is dan 10000 bytes.<br>
Dit betekend een fee van minimaal %1 per kb is noodzakelijk.<br>
Kan varieren van +/- 1 Byte per invulling</translation>
</message>
<message>
<location line="+1"/>
<source>Transactions with higher priority get more likely into a block.
This label turns red, if the priority is smaller than "medium".
This means a fee of at least %1 per kb is required.</source>
<translation>Transacties met hogere prioriteit komen sneller in een blok
Dit label wordt rood, als de prioriteit kleiner is dan "normaal".
Dit betekend een fee van minimaal %1 per kb is noodzakelijk.</translation>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if any recipient receives an amount smaller than %1.
This means a fee of at least %2 is required.
Amounts below 0.546 times the minimum relay fee are shown as DUST.</source>
<translation>Dit label wordt rood, als elke ontvanger ontvangt een bedrag dat kleiner is dan 1%.
Dit betekent dat een vergoeding van ten minste 2% is vereist.
Bedragen onder 0.546 keer het minimum vergoeding worden weergegeven als DUST.</translation>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if the change is smaller than %1.
This means a fee of at least %2 is required.</source>
<translation>Dit label wordt rood, als de verandering kleiner is dan %1.
Dit betekend dat een fee van %2 is vereist.</translation>
</message>
<message>
<location line="+36"/>
<location line="+66"/>
<source>(no label)</source>
<translation>(geen label)</translation>
</message>
<message>
<location line="-9"/>
<source>change from %1 (%2)</source>
<translation>wijzig van %1 (%2)</translation>
</message>
<message>
<location line="+1"/>
<source>(change)</source>
<translation>(wijzig)</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Bewerk Adres</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Label</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>Het label geassocieerd met deze notitie in het adresboek</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Adres</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>Het adres geassocieerd met deze notitie in het adresboek. Dit kan enkel aangepast worden bij verzend-adressen.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>Nieuw ontvangstadres</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Nieuw adres om naar te verzenden</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Bewerk ontvangstadres</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Bewerk adres om naar te verzenden</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Het opgegeven adres "%1" bestaat al in uw adresboek.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid IadixCoin address.</source>
<translation>Het ingevoerde adres "%1" is geen geldig Iadixcoin adres.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Kon de portemonnee niet openen.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Genereren nieuwe sleutel mislukt.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+426"/>
<location line="+12"/>
<source>IadixCoin-Qt</source>
<translation>IadixCoin-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>versie</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Gebruik:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>Commandoregel-opties</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>Gebruikerinterface-opties</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Stel taal in, bijvoorbeeld "de_DE" (standaard: systeeminstellingen)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Geminimaliseerd starten</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>Laat laadscherm zien bij het opstarten. (standaard: 1)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Opties</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Algemeen</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source>
<translation>Optioneel transactiekosten per kB dat helpt ervoor zorgen dat uw transacties worden snel verwerkt. De meeste transacties zijn 1 kB. Fee 0.01 aanbevolen.</translation>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Betaal &transactiekosten</translation>
</message>
<message>
<location line="+31"/>
<source>Reserved amount does not participate in staking and is therefore spendable at any time.</source>
<translation>Gereserveerde hoeveelheid doet niet mee in staking en is daarom altijd uitgeefbaar.</translation>
</message>
<message>
<location line="+15"/>
<source>Reserve</source>
<translation>Gereserveerd</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start IadixCoin after logging in to the system.</source>
<translation>Automatisch starten van Iadixcoin na inloggen van het systeem.</translation>
</message>
<message>
<location line="+3"/>
<source>&Start IadixCoin on system login</source>
<translation>&Start Iadixcoin bij systeem aanmelding</translation>
</message>
<message>
<location line="+21"/>
<source>&Network</source>
<translation>&Netwerk</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the IadixCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>De IadixCoin client poort automatisch openen op de router. Dit werkt alleen wanneer uw router UPnP ondersteunt en deze is ingeschakeld.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Portmapping via &UPnP</translation>
</message>
<message>
<location line="+19"/>
<source>Proxy &IP:</source>
<translation>Proxy &IP:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>IP Adres van de proxy (bijv. 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Poort:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Poort van de proxy (bijv. 9050)</translation>
</message>
<message>
<location line="-57"/>
<source>Connect to the IadixCoin network through a SOCKS5 proxy (e.g. when connecting through Tor).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS5 proxy:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+90"/>
<source>&Window</source>
<translation>&Scherm</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Laat alleen een systeemvak-icoon zien wanneer het venster geminimaliseerd is</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Minimaliseer naar het systeemvak in plaats van de taakbalk</translation>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>Minimaliseer het venster in de plaats van de applicatie af te sluiten als het venster gesloten wordt. Wanneer deze optie aan staan, kan de applicatie alleen worden afgesloten door Afsluiten te kiezen in het menu.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>Minimaliseer bij sluiten van het &venster</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Interface</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>Taal &Gebruikersinterface:</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting IadixCoin.</source>
<translation>De user interface-taal kan hier ingesteld worden. Deze instelling word toegepast na IadixCoin opnieuw op te starten.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Eenheid om bedrag in te tonen:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Kies de standaard onderverdelingseenheid om weer te geven in uw programma, en voor het versturen van munten</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show coin control features or not.</source>
<translation>Munt controle functies weergeven of niet.</translation>
</message>
<message>
<location line="+3"/>
<source>Display coin &control features (experts only!)</source>
<translation>Laat coin & control functies zien (enkel voor gevorderden!)</translation>
</message>
<message>
<location line="+7"/>
<source>Whether to select the coin outputs randomly or with minimal coin age.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Minimize weight consumption (experimental)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Use black visual theme (requires restart)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&OK</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>Ann&uleren</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>&Toepassen</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+47"/>
<source>default</source>
<translation>standaard</translation>
</message>
<message>
<location line="+148"/>
<location line="+9"/>
<source>Warning</source>
<translation>Waarschuwing</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting IadixCoin.</source>
<translation>Deze instelling word toegepast na een restart van IadixCoin.</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>Het opgegeven proxyadres is ongeldig.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Vorm</translation>
</message>
<message>
<location line="+46"/>
<location line="+247"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the IadixCoin network after a connection is established, but this process has not completed yet.</source>
<translation>De weergegeven informatie kan verouderd zijn, Je portemonnee synchroniseerd automatisch met het IadixCoin netwerk nadat er verbindig is gemaakt, maar dit proces is nog niet voltooid.</translation>
</message>
<message>
<location line="-173"/>
<source>Stake:</source>
<translation>Stake:</translation>
</message>
<message>
<location line="+32"/>
<source>Unconfirmed:</source>
<translation>Onbevestigd:</translation>
</message>
<message>
<location line="-113"/>
<source>Wallet</source>
<translation>Portemonnee</translation>
</message>
<message>
<location line="+49"/>
<source>Spendable:</source>
<translation>Uitgeefbaar:</translation>
</message>
<message>
<location line="+16"/>
<source>Your current spendable balance</source>
<translation>Uw beschikbare saldo</translation>
</message>
<message>
<location line="+80"/>
<source>Immature:</source>
<translation>Immatuur:</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>Gedolven saldo dat nog niet tot wasdom is gekomen</translation>
</message>
<message>
<location line="+23"/>
<source>Total:</source>
<translation>Totaal:</translation>
</message>
<message>
<location line="+16"/>
<source>Your current total balance</source>
<translation>Uw totale saldo</translation>
</message>
<message>
<location line="+50"/>
<source><b>Recent transactions</b></source>
<translation><b>Recente transacties</b></translation>
</message>
<message>
<location line="-118"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>Totaal van de transacties die nog moeten worden bevestigd, en nog niet mee voor het huidige balans</translation>
</message>
<message>
<location line="-32"/>
<source>Total of coins that was staked, and do not yet count toward the current balance</source>
<translation>Totaal aantal munten dat was staked, en nog niet telt voor huidige balans.</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation>niet gesynchroniseerd</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start iadixcoin: click-to-pay handler</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>QR Code Scherm</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Vraag betaling</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Hoeveelheid:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Label:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Bericht:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&Opslaan als...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>Fout tijdens encoderen URI in QR-code</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>De ingevoerde hoeveel is ongeldig, controleer aub.</translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>Resulterende URI te lang, probeer de tekst korter te maken voor het label/bericht.</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>Sla QR Code op.</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>PNG Afbeeldingen (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Clientnaam</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<source>N/A</source>
<translation>N.v.t.</translation>
</message>
<message>
<location line="-194"/>
<source>Client version</source>
<translation>Clientversie</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Informatie</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Gebruikt OpenSSL versie</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Opstarttijd</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Netwerk</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Aantal connecties</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>Op testnetwerk</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Blokketen</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Huidig aantal blokken</translation>
</message>
<message>
<location line="+197"/>
<source>&Network Traffic</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>&Clear</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Totals</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<source>In:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+80"/>
<source>Out:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-383"/>
<source>Last block time</source>
<translation>Tijd laatste blok</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Open</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>Commandoregel-opties</translation>
</message>
<message>
<location line="+7"/>
<source>Show the IadixCoin-Qt help message to get a list with possible IadixCoin command-line options.</source>
<translation>Laat het Iadixcoin-QT help bericht zien om een lijst te krijgen met mogelijke Iadixcoin command-regel opties.</translation>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>&Show</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Console</translation>
</message>
<message>
<location line="-237"/>
<source>Build date</source>
<translation>Bouwdatum</translation>
</message>
<message>
<location line="-104"/>
<source>IadixCoin - Debug window</source>
<translation>Iadixcoin - Debugscherm</translation>
</message>
<message>
<location line="+25"/>
<source>IadixCoin Core</source>
<translation>IadixCoin Kern</translation>
</message>
<message>
<location line="+256"/>
<source>Debug log file</source>
<translation>Debug-logbestand</translation>
</message>
<message>
<location line="+7"/>
<source>Open the IadixCoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation>Open het IadixCoin debug log bestand van de huidige data map. Dit kan een paar seconden duren voor grote log bestanden.</translation>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Maak console leeg</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="+325"/>
<source>Welcome to the IadixCoin RPC console.</source>
<translation>Welkom bij de IadixCoin RPC console.</translation>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Gebruik de pijltjestoetsen om door de geschiedenis te navigeren, en <b>Ctrl-L</b> om het scherm leeg te maken.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Typ <b>help</b> voor een overzicht van de beschikbare commando's.</translation>
</message>
<message>
<location line="+127"/>
<source>%1 B</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 KB</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 MB</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 GB</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>%1 m</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>%1 h</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 h %2 m</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+182"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Verstuur munten</translation>
</message>
<message>
<location line="+76"/>
<source>Coin Control Features</source>
<translation>Coin controle opties</translation>
</message>
<message>
<location line="+20"/>
<source>Inputs...</source>
<translation>Invoer...</translation>
</message>
<message>
<location line="+7"/>
<source>automatically selected</source>
<translation>automatisch geselecteerd</translation>
</message>
<message>
<location line="+19"/>
<source>Insufficient funds!</source>
<translation>Onvoldoende fonds!</translation>
</message>
<message>
<location line="+77"/>
<source>Quantity:</source>
<translation>Kwantiteit</translation>
</message>
<message>
<location line="+22"/>
<location line="+35"/>
<source>0</source>
<translation>0</translation>
</message>
<message>
<location line="-19"/>
<source>Bytes:</source>
<translation>Bytes:</translation>
</message>
<message>
<location line="+51"/>
<source>Amount:</source>
<translation>Bedrag:</translation>
</message>
<message>
<location line="+35"/>
<source>Priority:</source>
<translation>Prioriteit:</translation>
</message>
<message>
<location line="+19"/>
<source>medium</source>
<translation>gemiddeld</translation>
</message>
<message>
<location line="+32"/>
<source>Fee:</source>
<translation>Vergoeding:</translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation>Lage uitvoer:</translation>
</message>
<message>
<location line="+19"/>
<source>no</source>
<translation>nee</translation>
</message>
<message>
<location line="+32"/>
<source>After Fee:</source>
<translation>Na vergoeding:</translation>
</message>
<message>
<location line="+35"/>
<source>Change</source>
<translation>Wijzigen</translation>
</message>
<message>
<location line="+50"/>
<source>custom change address</source>
<translation>handmatig veranderen adres</translation>
</message>
<message>
<location line="+106"/>
<source>Send to multiple recipients at once</source>
<translation>Verstuur aan verschillende ontvangers ineens</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>Voeg &Ontvanger Toe</translation>
</message>
<message>
<location line="+16"/>
<source>Remove all transaction fields</source>
<translation>Verwijder alles in de invulvelden</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>Verwijder &Alles</translation>
</message>
<message>
<location line="+24"/>
<source>Balance:</source>
<translation>Saldo:</translation>
</message>
<message>
<location line="+47"/>
<source>Confirm the send action</source>
<translation>Bevestig de verstuuractie</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>&Verstuur</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-174"/>
<source>Enter a IadixCoin address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation>Voeg een Iadixcoin adres in (bijv. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</translation>
</message>
<message>
<location line="+15"/>
<source>Copy quantity</source>
<translation>Kopieer aantal</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Kopieer bedrag</translation>
</message>
<message>
<location line="+1"/>
<source>Copy fee</source>
<translation>Kopieer vergoeding</translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation>Kopieer na vergoeding</translation>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation>Kopieer bytes</translation>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation>Kopieer prioriteit</translation>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation>Kopieer lage uitvoer</translation>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation>Kopieer wijzig</translation>
</message>
<message>
<location line="+87"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b> %1 </b> to %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Bevestig versturen munten</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>Weet je zeker dat je %1 wilt verzenden?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation>en</translation>
</message>
<message>
<location line="+29"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>Het ontvangstadres is niet geldig, controleer uw invoer.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Het ingevoerde bedrag moet groter zijn dan 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>Bedrag is hoger dan uw huidige saldo</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Totaal overschrijdt uw huidige saldo wanneer de %1 transactiekosten worden meegerekend</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Dubbel adres gevonden, u kunt slechts eenmaal naar een bepaald adres verzenden per verstuurtransactie</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Fout: De transactie was geweigerd, Dit kan gebeuren als sommige munten in je portemonnee al gebruikt zijn, door het gebruik van een kopie van wallet.dat en de munten in de kopie zijn niet gemarkeerd als gebruikt.</translation>
</message>
<message>
<location line="+247"/>
<source>WARNING: Invalid IadixCoin address</source>
<translation>WAARSCHUWING: Ongeldig Iadixcoin adres</translation>
</message>
<message>
<location line="+13"/>
<source>(no label)</source>
<translation>(geen label)</translation>
</message>
<message>
<location line="+4"/>
<source>WARNING: unknown change address</source>
<translation>WAARSCHUWING: Onbekend adres</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Vorm</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>Bedra&g:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>Betaal &Aan:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Vul een label in voor dit adres om het toe te voegen aan uw adresboek</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>&Label:</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>Kies adres uit adresboek</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Plak adres vanuit klembord</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation>Verwijder deze ontvanger</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a IadixCoin address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation>Voeg een Iadixcoin adres in (bijv. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>Handtekeningen - Onderteken een bericht / Verifiëer een handtekening</translation>
</message>
<message>
<location line="+13"/>
<location line="+124"/>
<source>&Sign Message</source>
<translation>O&nderteken Bericht</translation>
</message>
<message>
<location line="-118"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>U kunt berichten ondertekenen met een van uw adressen om te bewijzen dat u dit adres bezit. Pas op dat u geen onduidelijke dingen ondertekent, want phishingaanvallen zouden u kunnen misleiden om zo uw identiteit te stelen. Onderteken alleen berichten waarmee u het volledig eens bent.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation>Het adres om het bericht te ondertekenen (bijv. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i) </translation>
</message>
<message>
<location line="+10"/>
<location line="+203"/>
<source>Choose an address from the address book</source>
<translation>Kies een adres uit het adresboek</translation>
</message>
<message>
<location line="-193"/>
<location line="+203"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-193"/>
<source>Paste address from clipboard</source>
<translation>Plak adres vanuit klembord</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation>Typ hier het bericht dat u wilt ondertekenen</translation>
</message>
<message>
<location line="+24"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Kopieer de huidige handtekening naar het systeemklembord</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this IadixCoin address</source>
<translation>Teken een bericht om te bewijzen dat je een IadixCoin adres bezit.</translation>
</message>
<message>
<location line="+17"/>
<source>Reset all sign message fields</source>
<translation>Verwijder alles in de invulvelden</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>Verwijder &Alles</translation>
</message>
<message>
<location line="-87"/>
<location line="+70"/>
<source>&Verify Message</source>
<translation>&Verifiëer Bericht</translation>
</message>
<message>
<location line="-64"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation>Voer het ondertekenende adres, bericht en handtekening hieronder in (let erop dat u nieuwe regels, spaties en tabs juist overneemt) om de handtekening te verifiëren. Let erop dat u niet meer uit het bericht interpreteert dan er daadwerkelijk staat, om te voorkomen dat u wordt misleid in een man-in-the-middle-aanval.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation>Het adres van het bericht is ondertekend met (bijv. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified IadixCoin address</source>
<translation>Verifieer een bericht om zeker te zijn dat deze is ondertekend met een specifiek IadixCoin adres</translation>
</message>
<message>
<location line="+17"/>
<source>Reset all verify message fields</source>
<translation>Verwijder alles in de invulvelden</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a IadixCoin address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation>Voeg een Iadixcoin adres in (bijv. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Klik "Onderteken Bericht" om de handtekening te genereren</translation>
</message>
<message>
<location line="+3"/>
<source>Enter IadixCoin signature</source>
<translation>Voer IadixCoin handtekening in</translation>
</message>
<message>
<location line="+85"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>Het opgegeven adres is ongeldig.</translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>Controleer s.v.p. het adres en probeer het opnieuw.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>Het opgegeven adres verwijst niet naar een sleutel.</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>Portemonnee-ontsleuteling is geannuleerd</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>Geheime sleutel voor het ingevoerde adres is niet beschikbaar.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Ondertekenen van het bericht is mislukt.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Bericht ondertekend.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>De handtekening kon niet worden gedecodeerd.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>Controleer s.v.p. de handtekening en probeer het opnieuw.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>De handtekening hoort niet bij het bericht.</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>Berichtverificatie mislukt.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Bericht correct geverifiëerd.</translation>
</message>
</context>
<context>
<name>TrafficGraphWidget</name>
<message>
<location filename="../trafficgraphwidget.cpp" line="+75"/>
<source>KB/s</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+25"/>
<source>Open until %1</source>
<translation>Openen totdat %1</translation>
</message>
<message>
<location line="+6"/>
<source>conflicted</source>
<translation>conflicted</translation>
</message>
<message>
<location line="+2"/>
<source>%1/offline</source>
<translation>%1/offline</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/onbevestigd</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 bevestigingen</translation>
</message>
<message>
<location line="+17"/>
<source>Status</source>
<translation>Status</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>, uitgezonden naar %n node</numerusform><numerusform>, uitgezonden naar %n nodes</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Bron</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Gegenereerd</translation>
</message>
<message>
<location line="+5"/>
<location line="+13"/>
<source>From</source>
<translation>Van</translation>
</message>
<message>
<location line="+1"/>
<location line="+19"/>
<location line="+58"/>
<source>To</source>
<translation>Aan</translation>
</message>
<message>
<location line="-74"/>
<location line="+2"/>
<source>own address</source>
<translation>eigen adres</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>label</translation>
</message>
<message>
<location line="+34"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Credit</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation><numerusform>komt tot wasdom na %n nieuw blok</numerusform><numerusform>komt tot wasdom na %n nieuwe blokken</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>niet geaccepteerd</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Debet</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Transactiekosten</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Netto bedrag</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Bericht</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Opmerking</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>Transactie-ID:</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 510 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>Gegenereerd munten moeten 510 blokken maturen voordat ze kunnen worden besteed. Wanneer je een blok genereerd, het naar het netwerk is verzonden en toegevoegd aan de blokketen, zal de status veranderen naar "niet geaccepteerd"and kan het niet uitgegeven worden. Dit kan soms gebeuren als een ander knooppunt genereert een blok binnen een paar seconden na jou.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Debug-informatie</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Transactie</translation>
</message>
<message>
<location line="+5"/>
<source>Inputs</source>
<translation>Inputs</translation>
</message>
<message>
<location line="+21"/>
<source>Amount</source>
<translation>Bedrag</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>waar</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>onwaar</translation>
</message>
<message>
<location line="-202"/>
<source>, has not been successfully broadcast yet</source>
<translation>, is nog niet met succes uitgezonden</translation>
</message>
<message numerus="yes">
<location line="-36"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+67"/>
<source>unknown</source>
<translation>onbekend</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Transactiedetails</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Dit venster laat een uitgebreide beschrijving van de transactie zien</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+231"/>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Type</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Bedrag</translation>
</message>
<message>
<location line="+52"/>
<source>Open until %1</source>
<translation>Open tot %1</translation>
</message>
<message>
<location line="+12"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Bevestigd (%1 bevestigingen)</translation>
</message>
<message numerus="yes">
<location line="-15"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Open voor nog %n blok</numerusform><numerusform>Open voor nog %n blokken</numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Offline</source>
<translation>Offline</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed</source>
<translation>Onbevestigd:</translation>
</message>
<message>
<location line="+3"/>
<source>Confirming (%1 of %2 recommended confirmations)</source>
<translation>Bevestigen.. (%1 van de %2 bevestigingen)</translation>
</message>
<message>
<location line="+6"/>
<source>Conflicted</source>
<translation>Conflicted</translation>
</message>
<message>
<location line="+3"/>
<source>Immature (%1 confirmations, will be available after %2)</source>
<translation>Immature (%1 bevestiging, word beschikbaar na %2)</translation>
</message>
<message>
<location line="+3"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Dit blok is niet ontvangen bij andere nodes en zal waarschijnlijk niet worden geaccepteerd!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Gegenereerd maar niet geaccepteerd</translation>
</message>
<message>
<location line="+42"/>
<source>Received with</source>
<translation>Ontvangen met</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Ontvangen van</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Verzonden aan</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Betaling aan uzelf</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Gedolven</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(nvt)</translation>
</message>
<message>
<location line="+194"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Transactiestatus. Houd de muiscursor boven dit veld om het aantal bevestigingen te laten zien.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Datum en tijd waarop deze transactie is ontvangen.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Type transactie.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Ontvangend adres van transactie.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Bedrag verwijderd van of toegevoegd aan saldo</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+54"/>
<location line="+17"/>
<source>All</source>
<translation>Alles</translation>
</message>
<message>
<location line="-16"/>
<source>Today</source>
<translation>Vandaag</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Deze week</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Deze maand</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Vorige maand</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Dit jaar</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Bereik...</translation>
</message>
<message>
<location line="+12"/>
<source>Received with</source>
<translation>Ontvangen met</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Verzonden aan</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Aan uzelf</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Gedolven</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Anders</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Vul adres of label in om te zoeken</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Min. bedrag</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Kopieer adres</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Kopieer label</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Kopieer bedrag</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>Kopieer transactie-ID</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Bewerk label</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Toon transactiedetails</translation>
</message>
<message>
<location line="+138"/>
<source>Export Transaction Data</source>
<translation>Exporteer Transactie Data</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Kommagescheiden bestand (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Bevestigd</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Type</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Label</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Bedrag</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Fout bij exporteren</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Kan niet schrijven naar bestand %1</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Bereik:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>naar</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+212"/>
<source>Sending...</source>
<translation>Versturen...</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+171"/>
<source>IadixCoin version</source>
<translation>IadixCoin versie</translation>
</message>
<message>
<location line="+1"/>
<source>Usage:</source>
<translation>Gebruik:</translation>
</message>
<message>
<location line="+1"/>
<source>Send command to -server or iadixcoind</source>
<translation>Verstuur commando naar -server of iadixcoind</translation>
</message>
<message>
<location line="+1"/>
<source>List commands</source>
<translation>Lijst van commando's</translation>
</message>
<message>
<location line="+1"/>
<source>Get help for a command</source>
<translation>Toon hulp voor een commando</translation>
</message>
<message>
<location line="-145"/>
<source>Options:</source>
<translation>Opties:</translation>
</message>
<message>
<location line="+2"/>
<source>Specify configuration file (default: iadixcoin.conf)</source>
<translation>Selecteer configuratie bestand (standaard: iadixcoin.conf)</translation>
</message>
<message>
<location line="+1"/>
<source>Specify pid file (default: iadixcoind.pid)</source>
<translation>Selecteer pid bestand (standaard: iadixcoin.conf)</translation>
</message>
<message>
<location line="+2"/>
<source>Specify wallet file (within data directory)</source>
<translation>Specificeer het portemonnee bestand (vanuit de gegevensmap)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Stel datamap in</translation>
</message>
<message>
<location line="-25"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=iadixcoinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "IadixCoin Alert" admin@foo.com
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Stel databankcachegrootte in in megabytes (standaard: 25)</translation>
</message>
<message>
<location line="+1"/>
<source>Set database disk log size in megabytes (default: 100)</source>
<translation>Stel database cache grootte in in megabytes (standaard: 100)</translation>
</message>
<message>
<location line="+5"/>
<source>Listen for connections on <port> (default: 15714 or testnet: 25714)</source>
<translation>Luister voor verbindingen op <poort> (standaard: 15714 of testnet: 25714)</translation>
</message>
<message>
<location line="+1"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Onderhoud maximaal <n> verbindingen naar peers (standaard: 125)</translation>
</message>
<message>
<location line="+3"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Verbind naar een node om adressen van anderen op te halen, en verbreek vervolgens de verbinding</translation>
</message>
<message>
<location line="+1"/>
<source>Specify your own public address</source>
<translation>Specificeer uw eigen publieke adres</translation>
</message>
<message>
<location line="+4"/>
<source>Bind to given address. Use [host]:port notation for IPv6</source>
<translation>Koppel aan gegeven adres. Gebruik [host]:poort notatie voor IPv6</translation>
</message>
<message>
<location line="+1"/>
<source>Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Always query for peer addresses via DNS lookup (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Drempel om verbinding te verbreken naar zich misdragende peers (standaard: 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Aantal seconden dat zich misdragende peers niet opnieuw mogen verbinden (standaard: 86400)</translation>
</message>
<message>
<location line="-35"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation>Er is een fout opgetreden tijdens het instellen van de inkomende RPC-poort %u op IPv4: %s</translation>
</message>
<message>
<location line="+62"/>
<source>Listen for JSON-RPC connections on <port> (default: 15715 or testnet: 25715)</source>
<translation>Wacht op JSON-RPC-connecties op <poort> (standaard: 15715 of testnet: 25715) </translation>
</message>
<message>
<location line="-16"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Aanvaard commandoregel- en JSON-RPC-commando's</translation>
</message>
<message>
<location line="+1"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Draai in de achtergrond als daemon en aanvaard commando's</translation>
</message>
<message>
<location line="+1"/>
<source>Use the test network</source>
<translation>Gebruik het testnetwerk</translation>
</message>
<message>
<location line="-23"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Accepteer verbindingen van buitenaf (standaard: 1 als geen -proxy of -connect is opgegeven)</translation>
</message>
<message>
<location line="-28"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation>Er is een fout opgetreden tijdens het instellen van de inkomende RPC-poort %u op IPv6, terugval naar IPv4: %s</translation>
</message>
<message>
<location line="+93"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation>Stel maximale grootte van high-priority/low-fee transacties in bytes (standaard: 27000)</translation>
</message>
<message>
<location line="+15"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Waarschuwing: -paytxfee is zeer hoog ingesteld. Dit zijn de transactiekosten die u betaalt bij het versturen van een transactie.</translation>
</message>
<message>
<location line="-103"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong IadixCoin will not work properly.</source>
<translation>Waarschuwing: Controleer of de datum en tijd van de computer juist zijn! Als uw klok verkeerd is IadixCoin zal niet goed werken.</translation>
</message>
<message>
<location line="+130"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation>Waarschuwing: Fout bij het lezen van wallet.dat! Alle sleutels zijn in goede orde uitgelezen, maar transactiedata of adresboeklemma's zouden kunnen ontbreken of fouten bevatten.</translation>
</message>
<message>
<location line="-16"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation>Waarschuwing: wallet.dat is corrupt, data is veiliggesteld! Originele wallet.dat is opgeslagen als wallet.{tijdstip}.bak in %s; als uw balans of transacties incorrect zijn dient u een backup terug te zetten.</translation>
</message>
<message>
<location line="-34"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>Poog de geheime sleutels uit een corrupt wallet.dat bestand terug te halen</translation>
</message>
<message>
<location line="+5"/>
<source>Block creation options:</source>
<translation>Blokcreatie-opties:</translation>
</message>
<message>
<location line="-67"/>
<source>Connect only to the specified node(s)</source>
<translation>Verbind alleen naar de gespecificeerde node(s)</translation>
</message>
<message>
<location line="+4"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Ontdek eigen IP-adres (standaard: 1 als er wordt geluisterd en geen -externalip is opgegeven)</translation>
</message>
<message>
<location line="+101"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Mislukt om op welke poort dan ook te luisteren. Gebruik -listen=0 as u dit wilt.</translation>
</message>
<message>
<location line="-2"/>
<source>Invalid -tor address: '%s'</source>
<translation>Ongeldig-tor adres: '%s'</translation>
</message>
<message>
<location line="+4"/>
<source>Invalid amount for -reservebalance=<amount></source>
<translation>Ongeldig bedrag voor -reservebalance = <bedrag></translation>
</message>
<message>
<location line="-89"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Maximum per-connectie ontvangstbuffer, <n>*1000 bytes (standaard: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Maximum per-connectie zendbuffer, <n>*1000 bytes (standaard: 1000)</translation>
</message>
<message>
<location line="-16"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>Verbind alleen naar nodes in netwerk <net> (IPv4, IPv6 of Tor)</translation>
</message>
<message>
<location line="+30"/>
<source>Prepend debug output with timestamp</source>
<translation>Voeg een tijdstempel toe aan debug output</translation>
</message>
<message>
<location line="+40"/>
<source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation>SSL-opties: (zie de Bitcoin wiki voor SSL-instructies)</translation>
</message>
<message>
<location line="-38"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Stuur trace/debug-info naar de console in plaats van het debug.log bestand</translation>
</message>
<message>
<location line="+34"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation>Stel maximale block grootte in bytes in (standaard: 250000)</translation>
</message>
<message>
<location line="-1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Stel minimum blokgrootte in in bytes (standaard: 0)</translation>
</message>
<message>
<location line="-34"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Verklein debug.log-bestand bij het opstarten van de client (standaard: 1 als geen -debug)</translation>
</message>
<message>
<location line="-41"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Specificeer de time-outtijd in milliseconden (standaard: 5000)</translation>
</message>
<message>
<location line="+28"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Gebruik UPnP om de luisterende poort te mappen (standaard: 0)</translation>
</message>
<message>
<location line="-1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Gebruik UPnP om de luisterende poort te mappen (standaard: 1 als er wordt geluisterd)</translation>
</message>
<message>
<location line="-25"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation>Gebruik proxy tor verborgen diensten (standaard: zelfde als -proxy)</translation>
</message>
<message>
<location line="+45"/>
<source>Username for JSON-RPC connections</source>
<translation>Gebruikersnaam voor JSON-RPC-verbindingen</translation>
</message>
<message>
<location line="+54"/>
<source>Verifying database integrity...</source>
<translation>Database integriteit wordt geverifieërd</translation>
</message>
<message>
<location line="+42"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Error: Transaction creation failed!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Waarschuwing: Deze versie is verouderd, een upgrade is vereist!</translation>
</message>
<message>
<location line="-52"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>wallet.dat corrupt, veiligstellen mislukt</translation>
</message>
<message>
<location line="-59"/>
<source>Password for JSON-RPC connections</source>
<translation>Wachtwoord voor JSON-RPC-verbindingen</translation>
</message>
<message>
<location line="-47"/>
<source>Connect through SOCKS5 proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source>
<translation>Synchroniseer tijd met andere connecties. Uitschakelen als de tijd op uw systeem nauwkeurig is bijv. synchroniseren met NTP (standaard: 1)</translation>
</message>
<message>
<location line="+12"/>
<source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source>
<translation>Bij het maken van transacties, negeer ingangen met waarde minder dan dit (standaard: 0,01)</translation>
</message>
<message>
<location line="+6"/>
<source>Output debugging information (default: 0, supplying <category> is optional)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>If <category> is not supplied, output all debugging information.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source><category> can be:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly. This is intended for regression testing tools and app development.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Sta JSON-RPC verbindingen van opgegeven IP-adres toe</translation>
</message>
<message>
<location line="+1"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Verstuur commando's naar proces dat op <ip> draait (standaard: 127.0.0.1)</translation>
</message>
<message>
<location line="+1"/>
<source>Wait for RPC server to start</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Voer commando uit zodra het beste blok verandert (%s in cmd wordt vervangen door blockhash)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Voer opdracht uit zodra een portemonneetransactie verandert (%s in cmd wordt vervangen door TxID)</translation>
</message>
<message>
<location line="+3"/>
<source>Require a confirmations for change (default: 0)</source>
<translation>Vereist een bevestiging voor verandering (standaard: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation>Voer opdracht uit zodra een relevante waarschuwing wordt ontvangen (%s in cmd wordt vervangen door bericht)</translation>
</message>
<message>
<location line="+3"/>
<source>Upgrade wallet to latest format</source>
<translation>Vernieuw portemonnee naar nieuwste versie</translation>
</message>
<message>
<location line="+1"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Stel sleutelpoelgrootte in op <n> (standaard: 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Doorzoek de blokketen op ontbrekende portemonnee-transacties</translation>
</message>
<message>
<location line="+3"/>
<source>How thorough the block verification is (0-6, default: 1)</source>
<translation>Hoe grondig het blokverificatie is (0-6, standaard: 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Imports blocks from external blk000?.dat file</source>
<translation>Importeer blokken van extern blk000?.dat bestand</translation>
</message>
<message>
<location line="+1"/>
<source>Keep at most <n> MiB of unconnectable blocks in memory (default: %u)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Gebruik OpenSSL (https) voor JSON-RPC-verbindingen</translation>
</message>
<message>
<location line="+1"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Certificaat-bestand voor server (standaard: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Geheime sleutel voor server (standaard: server.pem)</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Initialization sanity check failed. IadixCoin is shutting down.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Error loading block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Error: Wallet unlocked for staking only, unable to create transaction.</source>
<translation>Fout: Portemonnee ontgrendeld voor alleen staking, niet in staat om de transactie te maken.</translation>
</message>
<message>
<location line="+16"/>
<source>Error: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-168"/>
<source>This help message</source>
<translation>Dit helpbericht</translation>
</message>
<message>
<location line="+104"/>
<source>Wallet %s resides outside data directory %s.</source>
<translation>Portemonnee %s bevindt zich buiten de datamap %s.</translation>
</message>
<message>
<location line="+35"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Niet in staat om aan %s te binden op deze computer (bind gaf error %d, %s)</translation>
</message>
<message>
<location line="-129"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Sta DNS-naslag toe voor -addnode, -seednode en -connect</translation>
</message>
<message>
<location line="+125"/>
<source>Loading addresses...</source>
<translation>Adressen aan het laden...</translation>
</message>
<message>
<location line="-10"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Fout bij laden wallet.dat: Portemonnee corrupt</translation>
</message>
<message>
<location line="+4"/>
<source>Error loading wallet.dat: Wallet requires newer version of IadixCoin</source>
<translation>Fout bij laden van wallet.dat: Portemonnee vereist een nieuwere versie van IadixCoin</translation>
</message>
<message>
<location line="+1"/>
<source>Wallet needed to be rewritten: restart IadixCoin to complete</source>
<translation>Portemonnee moet herschreven worden: herstart IadixCoin om te voltooien</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat</source>
<translation>Fout bij laden wallet.dat</translation>
</message>
<message>
<location line="-15"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Ongeldig -proxy adres: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Onbekend netwerk gespecificeerd in -onlynet: '%s'</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>Kan -bind adres niet herleiden: '%s'</translation>
</message>
<message>
<location line="+2"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>Kan -externlip adres niet herleiden: '%s'</translation>
</message>
<message>
<location line="-22"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Ongeldig bedrag voor -paytxfee=<bedrag>: '%s'</translation>
</message>
<message>
<location line="+58"/>
<source>Sending...</source>
<translation>Versturen...</translation>
</message>
<message>
<location line="+5"/>
<source>Invalid amount</source>
<translation>Ongeldig bedrag</translation>
</message>
<message>
<location line="+1"/>
<source>Insufficient funds</source>
<translation>Ontoereikend saldo</translation>
</message>
<message>
<location line="-40"/>
<source>Loading block index...</source>
<translation>Blokindex aan het laden...</translation>
</message>
<message>
<location line="-109"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Voeg een node om naar te verbinden toe en probeer de verbinding open te houden</translation>
</message>
<message>
<location line="+124"/>
<source>Unable to bind to %s on this computer. IadixCoin is probably already running.</source>
<translation>Niet mogelijk om %s op deze computer. IadixCoin is waarschijnlijk al geopened.</translation>
</message>
<message>
<location line="-101"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Vergoeding per KB toe te voegen aan de transacties die u verzendt</translation>
</message>
<message>
<location line="+33"/>
<source>Minimize weight consumption (experimental) (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>How many blocks to check at startup (default: 500, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Acceptable ciphers (default: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Deprecated argument -debugnet ignored, use -debug=net</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Invalid amount for -mininput=<amount>: '%s'</source>
<translation>Ongeldig bedrag voor -mininput = <bedrag>: '%s'</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. IadixCoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error initializing wallet database environment %s!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Loading wallet...</source>
<translation>Portemonnee aan het laden...</translation>
</message>
<message>
<location line="+8"/>
<source>Cannot downgrade wallet</source>
<translation>Kan portemonnee niet downgraden</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot write default address</source>
<translation>Kan standaardadres niet schrijven</translation>
</message>
<message>
<location line="+1"/>
<source>Rescanning...</source>
<translation>Blokketen aan het doorzoeken...</translation>
</message>
<message>
<location line="+2"/>
<source>Done loading</source>
<translation>Klaar met laden</translation>
</message>
<message>
<location line="-159"/>
<source>To use the %s option</source>
<translation>Om de %s optie te gebruiken</translation>
</message>
<message>
<location line="+186"/>
<source>Error</source>
<translation>Fout</translation>
</message>
<message>
<location line="-18"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation>U dient rpcpassword=<wachtwoord> in te stellen in het configuratiebestand:
%s
Als het bestand niet bestaat, maak het dan aan, met een alleen-lezen permissie.</translation>
</message>
</context>
</TS> | iadix/iadixcoin | src/qt/locale/bitcoin_nl.ts | TypeScript | mit | 126,834 |
;(function(){
'use strict';
angular.module('TTT')
.config(function($routeProvider){
$routeProvider
.when('/emu',{
templateUrl: 'views/emu.html',
controller: 'emuController',
controllerAs: 'emu'
});
});
})();
| beck410/GJ_Timetravel | app/js/config/emu.config.js | JavaScript | mit | 247 |
<?php
namespace EloquentJs\ScriptGenerator\Model;
class Metadata
{
/**
* @var string
*/
public $name;
/**
* @var string
*/
public $endpoint;
/**
* @var array
*/
public $dates;
/**
* @var array
*/
public $scopes;
/**
* @var array
*/
public $relations;
/**
* @param string $name
* @param string $endpoint
* @param array $dates
* @param array $scopes
*/
public function __construct($name, $endpoint, array $dates = [], array $scopes = [], array $relations = [])
{
$this->name = $name;
$this->endpoint = $endpoint;
$this->dates = $dates;
$this->scopes = $scopes;
$this->relations = $relations;
}
}
| parsnick/eloquentjs | src/ScriptGenerator/Model/Metadata.php | PHP | mit | 772 |
@extends('admin.layout')
@section('title')
Payment
@endsection
@section('content')
<a href="/admin/ff/payment/create/{{$pledge->id}}" class="ui teal button right floated">New Payment</a>
<h1 class="ui header">Payments</h1>
<div class="ui horizontal divider">{{$pledge->name}}'s <br> Summary </div>
<table class="ui unstackable table">
<thead>
<tr>
<th class="center aligned"> {{trans('futurefund.total_pledge')}} </th>
<th class="center aligned"> {{trans('futurefund.collected')}} </th>
<th class="center aligned"> {{trans('futurefund.balance')}} </th>
</tr>
</thead>
<tr>
<td class="center aligned">RM {{number_format($pledge->amount, 2)}}</td>
<td class="center aligned">RM {{number_format($pledge_collected, 2)}}</td>
<td class="center aligned">RM {{number_format(($pledge->amount - $pledge_collected), 2)}}</td>
</tr>
</table>
<div class="ui horizontal divider">{{$pledge->name}}'s <br> Payments </div>
<div class="ui segment">
{!! Form::select('is_cleared', ['0' => 'Not cleared', '1' => 'Cleared', 'all' => 'All'], $filter['is_cleared'], ['class' => 'ui dropdown']) !!}
{!! Form::select('is_cancelled', ['0' => 'Not cancelled', '1' => 'Cancelled', 'all' => 'All'], $filter['is_cancelled'], ['class' => 'ui dropdown']) !!}
<div class="clearfix field">
<a href="{{ url()->current() }}" class="ui basic right floated right labeled icon tiny button">
Reset <i class="undo icon"></i>
</a>
<button class="ui teal right floated right labeled icon tiny button">
Filter <i class="filter icon"></i>
</button>
</div>
<div class="ui hidden divider"></div>
{!! Form::close() !!}
</div>
<table class="ui very compact unstackable table">
<thead>
<tr>
<th >{!! sort_by('id', 'ID' ) !!}</th>
<th class="three wide">Amount</th>
<th >Status</th>
<th >Created at</th>
<th >Actions</th>
</tr>
</thead>
<tbody>
@forelse ($payments as $payment)
<tr>
<td>
<h5 class="ui header">
{{ prefix()->wrap($payment) }}
</h5>
</td>
<td>
<h5 class="ui header">
RM {{ $payment->amount }}
@if ($payment->remarks)
<div class="sub uppercased header">{{ $payment->remarks }}</div>
@endif
</h5>
</td>
<td>
<div>
@if ($payment->is_cancelled)
<div class="ui grey label">cancelled</div>
@else
@if ($payment->is_cleared)
<div class="ui green label">cleared</div>
@else
<div class="ui orange label">pending</div>
@endif
@endif
</div>
</td>
<td>
{{ $payment->created_at->format('Y-m-d') }}
<div>{{ $payment->created_at->format('h:i a') }}</div>
</td>
<td>
<div class="ui small icon buttons">
<a href="/admin/ff/payment/update/{{$payment->id}}" class="ui button">
<i class="pencil icon"></i>
</a>
</div>
</td>
</tr>
@empty
<tr>
<td colspan="5"> No payment record yet, change filter or come back later </td>
</tr>
@endforelse
</tbody>
</table>
@endsection
| yilliot/souls | resources/views/admin/ff/payment_index.blade.php | PHP | mit | 3,322 |
module ActiveSurvey
class Visitor
def visit_items(items)
res = items.map { |item| item.accept(self) }
after_visit_items(items, res)
end
def after_visit_items(items, result)
result
end
def visit_question(item)
end
def visit_section(item)
self.visit_items item.items
end
def visit_text_item(item)
end
end
end | bcardiff/active_survey | lib/active_survey/visitor.rb | Ruby | mit | 378 |
/*
The main entry point for the client side of the app
*/
// Create the main app object
this.App = {};
// Create the needed collections on the client side
this.Surprises = new Meteor.Collection("surprises");
// Subscribe to the publishes in server/collections
Meteor.subscribe('surprises');
// Start the app
Meteor.startup(function() {
$(function() {
App.routes = new Routes();
});
});
| angelwong/giftedfromus | client/js/main.js | JavaScript | mit | 405 |
// -*- coding: utf-8 -*-
// Copyright (C) 2016 Laboratoire de Recherche et Développement
// de l'Epita (LRDE).
//
// This file is part of Spot, a model checking library.
//
// Spot is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// Spot is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
// License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#include <cassert>
#include <ctime>
#include <vector>
#include <spot/twaalgos/dualize.hh>
#include <spot/twaalgos/hoa.hh>
#include <spot/twaalgos/iscolored.hh>
#include <spot/twaalgos/parity.hh>
#include <spot/twaalgos/product.hh>
#include <spot/twaalgos/randomgraph.hh>
#include <spot/misc/random.hh>
#include <spot/twaalgos/complete.hh>
#include <spot/twa/twagraph.hh>
#include <spot/twa/fwd.hh>
#include <spot/twa/acc.hh>
#include <spot/misc/trival.hh>
#include <utility>
#include <string>
#include <iostream>
#define LAST_AUT result.back().first
#define LAST_NUM_SETS result.back().second
#define NEW_AUT() do { \
result.emplace_back(spot::random_graph(6, 0.5, &apf, \
current_bdd, 0, 0, 0.5, true), 0); \
LAST_NUM_SETS = 0; \
/* print_hoa need this */ \
LAST_AUT->prop_state_acc(spot::trival::maybe()); \
} while (false)
#define SET_TR(t, value) do { \
unsigned value_tmp = value; \
if (value_tmp + 1 > LAST_NUM_SETS) \
LAST_NUM_SETS = value_tmp + 1; \
t.acc.set(value_tmp); \
} while (false)
static std::vector<std::pair<spot::twa_graph_ptr, unsigned>>
generate_aut(const spot::bdd_dict_ptr& current_bdd)
{
spot::atomic_prop_set apf = spot::create_atomic_prop_set(3);
std::vector<std::pair<spot::twa_graph_ptr, unsigned>> result;
// No accset on any transition
NEW_AUT();
// The same accset on every transitions
NEW_AUT();
for (auto& t: LAST_AUT->edges())
SET_TR(t, 0);
// All used / First unused / Last unused / First and last unused
for (auto incr_ext: { 0, 1 })
for (auto used: { 1, 2 })
for (auto modulo: { 4, 5, 6 })
if (incr_ext + modulo <= 6)
{
NEW_AUT();
unsigned count = 0;
for (auto& t: LAST_AUT->edges())
if (std::rand() % used == 0)
{
auto value = ++count % modulo + incr_ext;
SET_TR(t, value);
}
}
// One-Three in middle not used
for (auto i: { 0, 1 })
for (auto start: { 1, 2 })
for (auto unused: { 1, 2, 3 })
{
NEW_AUT();
auto count = 0;
for (auto& t: LAST_AUT->edges())
{
int val = 0;
if (count % (3 + i) < start)
val = count % (3 + i);
else
val = count % (3 + i) + unused;
SET_TR(t, val);
}
}
// All accset on all transitions
for (auto i: { 0, 1 })
{
NEW_AUT();
for (auto& t: LAST_AUT->edges())
for (auto acc = 0; acc < 5 + i; ++acc)
SET_TR(t, acc);
}
// Some random automata
std::vector<std::vector<int>> cont_sets;
for (auto i = 0; i <= 6; ++i)
{
std::vector<int> cont_set;
for (auto j = 0; j < i; ++j)
cont_set.push_back(j);
cont_sets.push_back(cont_set);
}
for (auto min: { 0, 1 })
{
for (auto num_sets: { 1, 2, 5, 6 })
for (auto i = 0; i < 10; ++i)
{
NEW_AUT();
for (auto& t: LAST_AUT->edges())
{
auto nb_acc = std::rand() % (num_sets - min + 1) + min;
std::random_shuffle(cont_sets[num_sets].begin(),
cont_sets[num_sets].end());
for (auto j = 0; j < nb_acc; ++j)
SET_TR(t, cont_sets[num_sets][j]);
}
}
for (auto num_sets: {2, 3})
for (auto even: {0, 1})
if ((num_sets - 1) * 2 + even < 6)
{
NEW_AUT();
for (auto& t: LAST_AUT->edges())
{
auto nb_acc = std::rand() % (num_sets - min + 1) + min;
std::random_shuffle(cont_sets[num_sets].begin(),
cont_sets[num_sets].end());
for (auto j = 0; j < nb_acc; ++j)
{
auto value = cont_sets[num_sets][j] * 2 + even;
SET_TR(t, value);
}
}
}
}
return result;
}
static std::vector<std::tuple<spot::acc_cond::acc_code, bool, bool, unsigned>>
generate_acc()
{
std::vector<std::tuple<spot::acc_cond::acc_code, bool, bool, unsigned>>
result;
for (auto max: { true, false })
for (auto odd: { true, false })
for (auto num_sets: { 0, 1, 2, 5, 6 })
result.emplace_back(spot::acc_cond::acc_code::parity(max, odd,
num_sets), max, odd, num_sets);
return result;
}
static bool is_included(spot::const_twa_graph_ptr left,
spot::const_twa_graph_ptr right, bool first_left)
{
auto tmp = spot::dualize(right);
auto product = spot::product(left, tmp);
if (!product->is_empty())
{
std::cerr << "======Not included======" << std::endl;
if (first_left)
std::cerr << "======First automaton======" << std::endl;
else
std::cerr << "======Second automaton======" << std::endl;
spot::print_hoa(std::cerr, left);
std::cerr << std::endl;
if (first_left)
std::cerr << "======Second automaton======" << std::endl;
else
std::cerr << "======First automaton======" << std::endl;
spot::print_hoa(std::cerr, right);
std::cerr << std::endl;
if (first_left)
std::cerr << "======!Second automaton======" << std::endl;
else
std::cerr << "======!First automaton======" << std::endl;
spot::print_hoa(std::cerr, tmp);
std::cerr << std::endl;
if (first_left)
std::cerr << "======First X !Second======" <<std::endl;
else
std::cerr << "======Second X !First======" <<std::endl;
spot::print_hoa(std::cerr, product);
std::cerr << std::endl;
return false;
}
return true;
}
static bool are_equiv(spot::const_twa_graph_ptr left,
spot::const_twa_graph_ptr right)
{
return is_included(left, right, true) && is_included(right, left, false);
}
static bool is_right_parity(spot::const_twa_graph_ptr aut,
spot::parity_kind target_kind,
spot::parity_style target_style,
bool origin_max, bool origin_odd, unsigned num_sets)
{
bool is_max;
bool is_odd;
if (!aut->acc().is_parity(is_max, is_odd))
return false;
bool target_max;
bool target_odd;
if (aut->num_sets() <= 1 || num_sets <= 1
|| target_kind == spot::parity_kind_any)
target_max = is_max;
else if (target_kind == spot::parity_kind_max)
target_max = true;
else if (target_kind == spot::parity_kind_min)
target_max = false;
else
target_max = origin_max;
if (aut->num_sets() == 0 || num_sets == 0
|| target_style == spot::parity_style_any)
target_odd = is_odd;
else if (target_style == spot::parity_style_odd)
target_odd = true;
else if (target_style == spot::parity_style_even)
target_odd = false;
else
target_odd = origin_odd;
if (!(is_max == target_max && is_odd == target_odd))
{
std::cerr << "======Wrong accceptance======" << std::endl;
std::string kind[] = { "max", "min", "same", "any" };
std::string style[] = { "odd", "even", "same", "any" };
std::cerr << "target: " << kind[target_kind] << ' '
<< style[target_style] << std::endl;
std::cerr << "origin: " << kind[origin_max ? 0 : 1] << ' '
<< style[origin_odd ? 0 : 1] << ' '
<< num_sets << std::endl;
std::cerr << "actually: " << kind[is_max ? 0 : 1] << ' '
<< style[is_odd ? 0 : 1] << ' '
<< aut->num_sets() << std::endl;
std::cerr << std::endl;
return false;
}
return true;
}
static bool is_almost_colored(spot::const_twa_graph_ptr aut)
{
for (auto t: aut->edges())
if (t.acc.count() > 1)
{
std::cerr << "======Not colored======" << std::endl;
spot::print_hoa(std::cerr, aut);
std::cerr << std::endl;
return false;
}
return true;
}
static bool is_colored_printerr(spot::const_twa_graph_ptr aut)
{
bool result = is_colored(aut);
if (!result)
{
std::cerr << "======Not colored======" << std::endl;
spot::print_hoa(std::cerr, aut);
std::cerr << std::endl;
}
return result;
}
static spot::parity_kind to_parity_kind(bool is_max)
{
if (is_max)
return spot::parity_kind_max;
return spot::parity_kind_min;
}
static spot::parity_style to_parity_style(bool is_odd)
{
if (is_odd)
return spot::parity_style_odd;
return spot::parity_style_even;
}
int main()
{
auto current_bdd = spot::make_bdd_dict();
spot::srand(0);
auto parity_kinds =
{
spot::parity_kind_max,
spot::parity_kind_min,
spot::parity_kind_same,
spot::parity_kind_any,
};
auto parity_styles =
{
spot::parity_style_odd,
spot::parity_style_even,
spot::parity_style_same,
spot::parity_style_any,
};
auto acceptance_sets = generate_acc();
auto automata_tuples = generate_aut(current_bdd);
unsigned num_automata = automata_tuples.size();
unsigned num_acceptance = acceptance_sets.size();
std::cerr << "num of automata: " << num_automata << '\n';
std::cerr << "num of acceptance expression: " << num_acceptance << '\n';
for (auto acc_tuple: acceptance_sets)
for (auto& aut_tuple: automata_tuples)
{
auto& aut = aut_tuple.first;
auto aut_num_sets = aut_tuple.second;
auto acc = std::get<0>(acc_tuple);
auto is_max = std::get<1>(acc_tuple);
auto is_odd = std::get<2>(acc_tuple);
auto acc_num_sets = std::get<3>(acc_tuple);
if (aut_num_sets <= acc_num_sets)
{
aut->set_acceptance(acc_num_sets, acc);
// Check change_parity
for (auto kind: parity_kinds)
for (auto style: parity_styles)
{
auto output = spot::change_parity(aut, kind, style);
assert(is_right_parity(output, kind, style,
is_max, is_odd, acc_num_sets)
&& "change_parity: wrong acceptance.");
assert(are_equiv(aut, output)
&& "change_parity: not equivalent.");
assert(is_almost_colored(output)
&& "change_parity: too many acc on a transition");
}
// Check colorize_parity
for (auto keep_style: { true, false })
{
auto output = spot::colorize_parity(aut, keep_style);
assert(is_colored_printerr(output)
&& "colorize_parity: not colored.");
assert(are_equiv(aut, output)
&& "colorize_parity: not equivalent.");
auto target_kind = to_parity_kind(is_max);
auto target_style = keep_style ? to_parity_style(is_odd)
: spot::parity_style_any;
assert(is_right_parity(output, target_kind, target_style,
is_max, is_odd, acc_num_sets)
&& "change_parity: wrong acceptance.");
}
// Check cleanup_parity
for (auto keep_style: { true, false })
{
auto output = spot::cleanup_parity(aut, keep_style);
assert(is_almost_colored(output)
&& "cleanup_parity: too many acc on a transition.");
assert(are_equiv(aut, output)
&& "cleanup_parity: not equivalent.");
auto target_kind = to_parity_kind(is_max);
auto target_style = keep_style ? to_parity_style(is_odd)
: spot::parity_style_any;
assert(is_right_parity(output, target_kind, target_style,
is_max, is_odd, acc_num_sets)
&& "cleanup_parity: wrong acceptance.");
}
}
}
std::random_shuffle(automata_tuples.begin(), automata_tuples.end());
unsigned num_left = 15;
unsigned num_right = 15;
unsigned acc_index = 0;
unsigned nb = 0;
// Parity product and sum
for (unsigned left_index = 0; left_index < num_left; ++left_index)
{
auto& aut_tuple_first = automata_tuples[left_index % num_automata];
auto& left = aut_tuple_first.first;
auto aut_num_sets_first = aut_tuple_first.second;
while (std::get<3>(acceptance_sets[acc_index]) < aut_num_sets_first)
acc_index = (acc_index + 1) % num_acceptance;
auto acc_tuple_first = acceptance_sets[acc_index];
acc_index = (acc_index + 1) % num_acceptance;
auto acc_first = std::get<0>(acc_tuple_first);
auto acc_num_sets_first = std::get<3>(acc_tuple_first);
left->set_acceptance(acc_num_sets_first, acc_first);
for (unsigned right_index = 0; right_index < num_right; ++right_index)
{
auto& aut_tuple_second =
automata_tuples[(num_left + right_index) % num_automata];
auto& right = aut_tuple_second.first;
auto aut_num_sets_second = aut_tuple_second.second;
while (std::get<3>(acceptance_sets[acc_index]) < aut_num_sets_second)
acc_index = (acc_index + 1) % num_acceptance;
auto acc_tuple_second = acceptance_sets[acc_index];
acc_index = (acc_index + 1) % num_acceptance;
auto acc_second = std::get<0>(acc_tuple_second);
auto acc_num_sets_second = std::get<3>(acc_tuple_second);
right->set_acceptance(acc_num_sets_second, acc_second);
auto result_prod = spot::parity_product(left, right);
auto ref_prod = spot::product(left, right);
if (!are_equiv(result_prod, ref_prod))
{
std::cerr << nb << ": parity_product: Not equivalent.\n"
<< "=====First Automaton=====\n";
spot::print_hoa(std::cerr, left);
std::cerr << "=====Second Automaton=====\n";
spot::print_hoa(std::cerr, right);
assert(false && "parity_product: Not equivalent.\n");
}
assert(is_colored_printerr(result_prod)
&& "parity_product: not colored.");
assert(is_right_parity(result_prod, spot::parity_kind_any,
spot::parity_style_any,
true, true, 2)
&& "parity_product: not a parity acceptance condition");
auto result_sum = spot::parity_product_or(left, right);
auto ref_sum = spot::product_or(left, right);
if (!are_equiv(result_sum, ref_sum))
{
std::cerr << nb << ": parity_product_or: Not equivalent.\n"
<< "=====First Automaton=====\n";
spot::print_hoa(std::cerr, left);
std::cerr << "=====Second Automaton=====\n";
spot::print_hoa(std::cerr, right);
assert(false && "parity_product_or: Not equivalent.\n");
}
assert(is_colored_printerr(result_sum)
&& "parity_product_or: not colored.");
assert(is_right_parity(result_sum, spot::parity_kind_any,
spot::parity_style_any,
true, true, 2)
&& "parity_product_or: not a parity acceptance condition");
++nb;
}
}
return 0;
}
| mcc-petrinets/formulas | spot/tests/core/parity.cc | C++ | mit | 16,809 |
namespace Meeko
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.SuspendLayout();
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 261);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "Form1";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Meeko";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
}
#endregion
}
}
| henrikac/Me-e-ko | Meeko/Meeko/Form1.Designer.cs | C# | mit | 1,734 |
// Copyright (c) 2016, Frappe Technologies and contributors
// For license information, please see license.txt
frappe.ui.form.on('Address Template', {
refresh: function(frm) {
if(frm.is_new() && !frm.doc.template) {
// set default template via js so that it is translated
frappe.call({
method: 'frappe.geo.doctype.address_template.address_template.get_default_address_template',
callback: function(r) {
frm.set_value('template', r.message);
}
});
}
}
});
| rohitwaghchaure/frappe | frappe/geo/doctype/address_template/address_template.js | JavaScript | mit | 488 |
using System.Web;
using System.Web.Optimization;
namespace InsectCatalog
{
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new ScriptBundle("~/bundles/angular").Include(
"~/Scripts/angular.min.js",
"~/Scripts/angular-route.min.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
}
}
}
| NewEvolution/InsectCatalog | InsectCatalog/App_Start/BundleConfig.cs | C# | mit | 1,459 |
class NdlStatAccept < ActiveRecord::Base
default_scope :order => :region
belongs_to :ndl_statistic
attr_accessible :donation, :production, :purchase, :region, :item_type
item_type_list = ['book', 'magazine', 'other_micro', 'other_av', 'other_file']
region_list = ['domestic', 'foreign', 'none']
validates_presence_of :item_type
validates_inclusion_of :item_type, :in => item_type_list
validates_inclusion_of :region, :in => region_list
end
| MiraitSystems/enju_trunk_statistics | app/models/ndl_stat_accept.rb | Ruby | mit | 462 |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class User extends CI_Controller {
public function __construct(){
parent:: __construct();
$this->load->model('engine_model');
}
public function add_url(){
$url = $_POST['url'];
$id = $_POST['id'];
$this->engine_model->add_user_url($id, $url);
}
public function remove_url(){
$url = $_POST['value'];
$this->engine_model->remove_user_url($url);
}
public function logout(){
if (!empty( $this->input->cookie('user') )) {
delete_cookie('user');
}
$this->load->view('welcome_message');
}
} | dav34111/bookmarks | application/controllers/user.php | PHP | mit | 591 |
require "day/tracker/version"
module Day
module Tracker
class Cli < Thor
FILE_PATH = File.expand_path("~/.day-tracker")
def initialize(*args)
super
FileUtils.touch FILE_PATH
end
desc "list", "list recorded days"
def list
puts File.read(FILE_PATH)
end
desc "add PROJECT_NAME [FRACTION]", "add a project for today"
def add(project, fraction=1)
entry = format_entry(project, fraction)
return if entry_exists?(entry)
open(FILE_PATH, 'a') do |file|
file.puts entry
end
list
end
no_commands do
def entry_exists?(entry)
File.readlines(FILE_PATH).grep(entry).any?
end
def format_entry(project, fraction)
Time.now.strftime("%B %d - #{project} - #{formatted_fraction(fraction)}")
end
def formatted_fraction(fraction)
{
"0.5" => "half",
".5" => "half",
"1" => "full"
}[fraction]
end
end
default_task :list
end
end
end
| opsb/day-tracker | lib/day/tracker.rb | Ruby | mit | 1,005 |
<?php
defined('C5_EXECUTE') or die("Access Denied.");
global $c;
// grab all the collections belong to the collection type that we're looking at
Loader::model('collection_types');
$ctID = $c->getCollectionTypeID();
$ct = CollectionType::getByID($ctID);
$cList = $ct->getPages();
?>
<div class="ccm-ui">
<form method="post" id="ccmBlockMasterCollectionForm" action="<?php echo $b->getBlockMasterCollectionAliasAction()?>">
<?php if (count($cList) == 0) { ?>
<?php echo t("There are no pages of this type added to your website. If there were, you'd be able to choose which of those pages this block appears on.")?>
<?php } else { ?>
<p><?php echo t("Choose which pages below this particular block should appear on. Any previously selected blocks may also be removed using the checkbox. Click the checkbox in the header to select/deselect all pages.")?></p>
<br/>
<table class="zebra-stripped" >
<tr>
<th>ID</th>
<th><?php echo t('Name')?></th>
<th ><?php echo t('Date Created')?></th>
<th ><?php echo t('Date Modified')?></th>
<th ><input type="checkbox" id="mc-cb-all" /></th>
</tr>
<?php
foreach($cList as $p) { ?>
<tr class="active">
<td><?php echo $p->getCollectionID()?></td>
<td><a href="<?php echo DIR_REL?>/<?php echo DISPATCHER_FILENAME?>?cID=<?php echo $p->getCollectionID()?>" target="_blank"><?php echo $p->getCollectionName()?></a></td>
<td ><?php echo $p->getCollectionDateAdded('m/d/Y','user')?></td>
<td ><?php if ($b->isAlias($p)) { ?> <input type="hidden" name="checkedCIDs[]" value="<?php echo $p->getCollectionID()?>" /><?php } ?><?php echo $p->getCollectionDateLastModified('m/d/Y','user')?></td>
<td ><input class="mc-cb" type="checkbox" name="cIDs[]" value="<?php echo $p->getCollectionID()?>" <?php if ($b->isAlias($p)) { ?> checked <?php } ?> /></td>
</tr>
<?php } ?>
</table>
<?php } ?>
<div class="dialog-buttons">
<a href="#" class="ccm-dialog-close ccm-button-left btn cancel"><?php echo t('Cancel')?></a>
<a href="javascript:void(0)" onclick="$('#ccmBlockMasterCollectionForm').submit()" class="btn primary ccm-button-right accept"><?php echo t('Save')?></a>
</div>
<script type="text/javascript">
$(function() {
$('#mc-cb-all').click(function() {
if (this.checked) {
$('input.mc-cb').each(function() {
$(this).get(0).checked = true;
});
} else {
$('input.mc-cb').each(function() {
$(this).get(0).checked = false;
});
}
});
$('#ccmBlockMasterCollectionForm').each(function() {
ccm_setupBlockForm($(this), '<?php echo $b->getBlockID()?>', 'edit');
});
});
</script>
</form>
</div> | tayeke/Klein-Instruments | concrete/elements/block_master_collection_alias.php | PHP | mit | 2,644 |
<?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model AlexanderEmelyanov\yii\modules\articles\models\Article */
$this->title = Yii::t('app', 'Update {modelClass}: ', [
'modelClass' => 'Article',
]) . ' ' . $model->article_id;
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Articles'), 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => $model->article_id, 'url' => ['view', 'id' => $model->article_id]];
$this->params['breadcrumbs'][] = Yii::t('app', 'Update');
?>
<div class="article-update">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
]) ?>
</div> | alexander-emelyanov/yii2-articles-module | views/articles/update.php | PHP | mit | 682 |
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateRoadblockTagAndContextTables extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
if (!Schema::hasTable('roadblocks'))
{
Schema::create('roadblocks', function(Blueprint $table)
{
$table->increments('id');
$table->string('description');
$table->integer('user_id')->unsigned()->nullable();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
}
if (!Schema::hasTable('project_roadblock'))
{
Schema::create('project_roadblock', function(Blueprint $table)
{
$table->increments('id');
$table->integer('project_id')->unsigned();
$table->foreign('project_id')->references('id')->on('projects');
$table->integer('roadblock_id')->unsigned();
$table->foreign('roadblock_id')->references('id')->on('roadblocks');
$table->timestamps();
});
}
if (!Schema::hasTable('tags'))
{
Schema::create('tags', function(Blueprint $table)
{
$table->increments('id');
$table->string('description');
$table->integer('user_id')->unsigned()->nullable();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
}
if (!Schema::hasTable('project_tag'))
{
Schema::create('project_tag', function(Blueprint $table)
{
$table->increments('id');
$table->integer('project_id')->unsigned();
$table->foreign('project_id')->references('id')->on('projects');
$table->integer('tag_id')->unsigned();
$table->foreign('tag_id')->references('id')->on('tags');
$table->timestamps();
});
}
if (!Schema::hasTable('contexts'))
{
Schema::create('contexts', function(Blueprint $table)
{
$table->increments('id');
$table->string('description');
$table->integer('user_id')->unsigned()->nullable();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
}
if (!Schema::hasTable('context_project'))
{
Schema::create('context_project', function(Blueprint $table)
{
$table->increments('id');
$table->integer('project_id')->unsigned();
$table->foreign('project_id')->references('id')->on('projects');
$table->integer('context_id')->unsigned();
$table->foreign('context_id')->references('id')->on('contexts');
$table->timestamps();
});
}
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
if (Schema::hasTable('project_roadblock'))
{
Schema::drop('project_roadblock');
}
if (Schema::hasTable('roadblocks'))
{
Schema::drop('roadblocks');
}
if (Schema::hasTable('project_tag'))
{
Schema::drop('project_tag');
}
if (Schema::hasTable('tags'))
{
Schema::drop('tags');
}
if (Schema::hasTable('context_project'))
{
Schema::drop('context_project');
}
if (Schema::hasTable('contexts'))
{
Schema::drop('contexts');
}
}
}
| BBBThunda/projectify | app/database/migrations/2014_09_04_132444_create_roadblock_tag_and_context_tables.php | PHP | mit | 3,901 |
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 111;
int arr[maxn];
int main()
{
//freopen("in.txt", "r", stdin);
int n, m;
while(2 == scanf("%d%d", &n, &m) && !(n==0 && m==0)) {
for(int i = 0; i < n; ++i)
scanf("%d", &arr[i]);
arr[n] = m;
sort(arr, arr+n+1);
printf("%d", arr[0]);
for(int i = 1; i < n+1; ++i)
printf(" %d", arr[i]);
printf("\n");
}
return 0;
}
| bashell/oj | hdu/2019.cpp | C++ | mit | 485 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace ContosoUniversity.WebApi.Controllers
{
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
}
| ChauThan/WebApi101 | src/ContosoUniversity.WebApi/Controllers/ValuesController.cs | C# | mit | 791 |
/**
* A debounce method that has a sliding window, there's a minimum and maximum wait time
**/
module.exports = function (cb, min, max, settings) {
var ctx, args, next, limit, timeout;
if (!settings) {
settings = {};
}
function fire() {
limit = null;
cb.apply(settings.context || ctx, args);
}
function run() {
var now = Date.now();
if (now >= limit || now >= next) {
fire();
} else {
timeout = setTimeout(run, Math.min(limit, next) - now);
}
}
let fn = function windowed() {
var now = Date.now();
ctx = this;
args = arguments;
next = now + min;
if (!limit) {
limit = now + max;
timeout = setTimeout(run, min);
}
};
fn.clear = function () {
clearTimeout(timeout);
timeout = null;
limit = null;
};
fn.flush = function () {
fire();
fn.clear();
};
fn.shift = function (diff) {
limit += diff;
};
fn.active = function () {
return !!limit;
};
return fn;
};
| b-heilman/bmoor | src/flow/window.js | JavaScript | mit | 935 |
# -*- coding: utf-8 -*-
from flask import Blueprint
from jotonce.api import route
from jotonce.passphrases.models import Passphrase
bp = Blueprint('passphrase', __name__, url_prefix='/passphrase')
@route(bp, '/')
def get():
p = Passphrase.get_random()
return {"results": p}
| nficano/jotonce.com | jotonce/api/passphrases.py | Python | mit | 285 |
package ru.lanbilling.webservice.wsdl;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Generated;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="ret" type="{urn:api3}soapVgroupsAddonsStaff" maxOccurs="unbounded"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"ret"
})
@XmlRootElement(name = "getVgroupsAddonsStaffResponse")
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
public class GetVgroupsAddonsStaffResponse {
@XmlElement(required = true)
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
protected List<SoapVgroupsAddonsStaff> ret;
/**
* Gets the value of the ret property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the ret property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getRet().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link SoapVgroupsAddonsStaff }
*
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
public List<SoapVgroupsAddonsStaff> getRet() {
if (ret == null) {
ret = new ArrayList<SoapVgroupsAddonsStaff>();
}
return this.ret;
}
}
| kanonirov/lanb-client | src/main/java/ru/lanbilling/webservice/wsdl/GetVgroupsAddonsStaffResponse.java | Java | mit | 2,337 |
class AddIndicesToPartialFlow < ActiveRecord::Migration[5.1]
def change
add_index :partial_flows, [ :is_syn, :state ]
add_index :partial_flows, [ :src_ip, :dst_ip, :src_port, :dst_port, :state ], name: 'identify_index'
end
end
| GetPhage/phage | db/migrate/20171029040306_add_indices_to_partial_flow.rb | Ruby | mit | 239 |
#include "background_extractor.h"
namespace TooManyPeeps {
BackgroundExtractor::BackgroundExtractor(const cv::Mat& original, cv::Mat& result,
int historySize, double threshold)
: ProcessFilter(original, result) {
backgroundExtractor = cv::createBackgroundSubtractorMOG2(historySize, threshold, TRACK_SHADOWS);
// If TRACK_SHADOWS = true, shadows are also marked in result with value = 127
}
BackgroundExtractor::BackgroundExtractor(cv::Mat& image, int historySize, double threshold)
: BackgroundExtractor(image, image, historySize, threshold) {
}
BackgroundExtractor::~BackgroundExtractor(void) {
delete backgroundExtractor;
}
void BackgroundExtractor::execute(void) {
backgroundExtractor->apply(get_original(), get_result());
}
};
| 99-bugs/toomanypeeps | opencv_detector/src/lib/filter/background_extractor.cpp | C++ | mit | 783 |
<?php
namespace App;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\MappedSuperclass
* @ORM\HasLifecycleCallbacks()
*/
abstract class Entity
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="datetime")
* @var \DateTime
*/
protected $created;
/**
* @ORM\Column(type="datetime")
* @var \DateTime
*/
protected $updated;
/**
* Constructor
*/
public function __construct()
{
$this->setCreated(new \DateTime());
$this->setUpdated(new \DateTime());
}
/**
* @ORM\PreUpdate
*/
public function setUpdatedValue()
{
$this->setUpdated(new \DateTime());
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* @param $created
*/
public function setCreated($created)
{
$this->created = $created;
}
/**
* @return \DateTime
*/
public function getCreated()
{
return $this->created;
}
/**
* @param $updated
*/
public function setUpdated($updated)
{
$this->updated = $updated;
}
/**
* @return \DateTime
*/
public function getUpdated()
{
return $this->updated;
}
public function toArray(){
return [
"id"=>$this->id,
"creation_time"=>$this->getCreated()->format('d/m/Y H:i:s'),
"last_update_time"=>$this->getUpdated()->format('d/m/Y H:i:s')
];
}
} | Meshredded/slim-framework_doctrine_mini_web-service | src/App/Entity.php | PHP | mit | 1,676 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace RepertoryGridGUI.ufos
{
public partial class ufoConstructAlternative : Form
{
public ufoConstructAlternative()
{
InitializeComponent();
}
}
}
| felixlindemann/RepertoryGrid | RepertoryGrid/RepertoryGridGUI/ufos/ufoConstructAlternative.cs | C# | mit | 407 |
using System.ComponentModel.DataAnnotations;
using EPiServer;
using EPiServer.DataAbstraction;
using EPiServer.DataAnnotations;
using ImageProcessor.Web.Episerver.UI.Blocks.Business;
namespace ImageProcessor.Web.Episerver.UI.Blocks.Models.Blocks
{
[ContentType(DisplayName = "Detect Edges",
GUID = "d4909010-f701-4c60-85ff-53789ca59743",
Description = "Detects the edges in the current image using various one and two dimensional algorithms.",
GroupName = Global.GroupName,
Order = 9)]
[Icon]
public class DetectEdgesBlock : ImageProcessorMethodBaseBlock
{
[Display(Name = "Filter")]
[EnumAttribute(typeof(DetectEdgesFilter))]
public virtual DetectEdgesFilter Filter { get; set; }
public virtual bool Greyscale { get; set; }
public override UrlBuilder GetMethod(UrlBuilder url)
{
return url.DetectEdges(Filter, Greyscale);
}
public override void SetDefaultValues(ContentType contentType)
{
base.SetDefaultValues(contentType);
Greyscale = false;
}
}
} | vnbaaij/ImageProcessor.Web.Episerver | src/ImageProcessor.Web.Episerver.UI.Blocks/Models/Blocks/DetectEdgesBlock.cs | C# | mit | 1,125 |
public class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> result = new ArrayList<>();
ArrayList<Integer> tmp = new ArrayList<>();
for (int i = 0; i < numRows; i++) {
tmp.add(0, 1);
for (int j = 1; j < tmp.size() - 1; j++) {
tmp.set(j, tmp.get(j) + tmp.get(j + 1));
}
result.add(new ArrayList<>(tmp));
}
return result;
}
}
| liupangzi/codekata | leetcode/Algorithms/118.Pascal'sTriangle/Solution.java | Java | mit | 471 |
if (typeof window !== 'undefined') {
var less = require('npm:less/lib/less-browser/index')(window, window.less || {})
var head = document.getElementsByTagName('head')[0];
// get all injected style tags in the page
var styles = document.getElementsByTagName('style');
var styleIds = [];
for (var i = 0; i < styles.length; i++) {
if (!styles[i].hasAttribute("data-href")) continue;
styleIds.push(styles[i].getAttribute("data-href"));
}
var loadStyle = function (url) {
return new Promise(function (resolve, reject) {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.onload = function () {
if (request.status >= 200 && request.status < 400) {
// Success!
var data = request.responseText;
var options = window.less || {};
options.filename = url;
options.rootpath = url.replace(/[^\/]*$/, '');
//render it using less
less.render(data, options).then(function (data) {
//inject it into the head as a style tag
var style = document.createElement('style');
style.textContent = '\r\n' + data.css;
style.setAttribute('type', 'text/css');
//store original type in the data-type attribute
style.setAttribute('data-type', 'text/less');
//store the url in the data-href attribute
style.setAttribute('data-href', url);
head.appendChild(style);
resolve('');
});
} else {
// We reached our target server, but it returned an error
reject()
}
};
request.onerror = function (e) {
reject(e)
};
request.send();
});
}
exports.fetch = function (load) {
// don't reload styles loaded in the head
for (var i = 0; i < styleIds.length; i++)
if (load.address == styleIds[i])
return '';
return loadStyle(load.address);
}
}
else {
exports.translate = function (load) {
// setting format = 'defined' means we're managing our own output
load.metadata.format = 'defined';
};
exports.bundle = function (loads, opts) {
var loader = this;
if (loader.buildCSS === false)
return '';
return loader.import('./less-builder', {name: module.id}).then(function (builder) {
return builder.call(loader, loads, opts);
});
}
}
| Aaike/jspm-less-plugin | less.js | JavaScript | mit | 2,820 |
(function () {
"use strict";
angular.module("myApp.components.notifications")
.factory("KudosNotificationService", KudosNotificationService);
KudosNotificationService.$inject = [
"Transaction"
];
function KudosNotificationService(transactionBackend) {
var service = {
getNewTransactions: getNewTransactions,
setLastTransaction: setLastSeenTransaction
};
return service;
function getNewTransactions() {
return transactionBackend.getNewTransactions()
}
function setLastSeenTransaction(timestamp) {
return transactionBackend.setLastSeenTransactionTimestamp(timestamp)
}
}
})(); | open-kudos/open-kudos-intern-web | src/app/components/kudos-notifications-transaction/kudos-notification-transaction.service.js | JavaScript | mit | 722 |
import numpy as np
from pycqed.analysis import measurement_analysis as ma
from pycqed.analysis_v2 import measurement_analysis as ma2
from pycqed.measurement import sweep_functions as swf
from pycqed.measurement import detector_functions as det
MC_instr = None
VNA_instr = None
def acquire_single_linear_frequency_span(file_name, start_freq=None,
stop_freq=None, center_freq=None,
span=None, nr_avg=1, sweep_mode='auto',
nbr_points=101, power=-20,
bandwidth=100, measure='S21',
options_dict=None):
"""
Acquires a single trace from the VNA.
Inputs:
file_name (str), name of the output file.
start_freq (float), starting frequency of the trace.
stop_freq (float), stoping frequency of the trace.
center_freq (float), central frequency of the trace.
span (float), span of the trace.
nbr_points (int), Number of points within the trace.
power (float), power in dBm.
bandwidth (float), bandwidth in Hz.
measure (str), scattering parameter to measure (ie. 'S21').
Output:
NONE
Beware that start/stop and center/span are just two ways of configuring the
same thing.
"""
# set VNA sweep function
if start_freq != None and stop_freq != None:
MC_instr.set_sweep_function(swf.ZNB_VNA_sweep(VNA_instr,
start_freq=start_freq,
stop_freq=stop_freq,
npts=nbr_points,
force_reset=True))
elif center_freq != None and span != None:
MC_instr.set_sweep_function(swf.ZNB_VNA_sweep(VNA_instr,
center_freq=center_freq,
span=span,
npts=nbr_points,
force_reset=True))
# set VNA detector function
MC_instr.set_detector_function(det.ZNB_VNA_detector(VNA_instr))
# VNA settings
# VNA_instr.average_state('off')
VNA_instr.bandwidth(bandwidth)
# hack to measure S parameters different from S21
str_to_write = "calc:par:meas 'trc1', '%s'" % measure
print(str_to_write)
VNA_instr.visa_handle.write(str_to_write)
VNA_instr.avg(nr_avg)
VNA_instr.number_sweeps_all(nr_avg)
VNA_instr.average_mode(sweep_mode)
VNA_instr.power(power)
VNA_instr.timeout(10**4)
t_start = ma.a_tools.current_timestamp()
MC_instr.run(name=file_name)
t_stop = ma.a_tools.current_timestamp()
t_meas = ma.a_tools.get_timestamps_in_range(t_start, t_stop, label=file_name)
assert len(t_meas) == 1, "Multiple timestamps found for this measurement"
t_meas = t_meas[0]
# ma.Homodyne_Analysis(auto=True, label=file_name, fitting_model='hanger')
# ma.VNA_analysis(auto=True, label=file_name)
ma2.VNA_analysis(auto=True, t_start=None, options_dict=options_dict)
def acquire_current_trace(file_name):
"""
Acquires the trace currently displayed on VNA.
Inputs:
file_name (str), name of the output file.
Output:
NONE
"""
# get values from VNA
start_freq = VNA_instr.start_frequency()
stop_freq = VNA_instr.stop_frequency()
nbr_points = VNA_instr.npts()
power = VNA_instr.power()
bandwidth = VNA_instr.bandwidth()
current_sweep_time = VNA_instr.sweep_time()
print(current_sweep_time)
acquire_single_linear_frequency_span(file_name, start_freq=start_freq,
stop_freq=stop_freq,
nbr_points=nbr_points,
power=power, bandwidth=bandwidth)
def acquire_linear_frequency_span_vs_power(file_name, start_freq=None,
stop_freq=None, center_freq=None,
start_power=None, stop_power=None,
step_power=2,
span=None, nbr_points=101,
bandwidth=100, measure='S21'):
"""
Acquires a single trace from the VNA.
Inputs:
file_name (str), name of the output file.
start_freq (float), starting frequency of the trace.
stop_freq (float), stoping frequency of the trace.
center_freq (float), central frequency of the trace.
span (float), span of the trace.
nbr_points (int), Number of points within the trace.
start_power, stop_power, step_power (float), power range in dBm.
bandwidth (float), bandwidth in Hz.
measure (str), scattering parameter to measure (ie. 'S21').
Output:
NONE
Beware that start/stop and center/span are just two ways of configuring the
same thing.
"""
# set VNA sweep function
if start_freq != None and stop_freq != None:
swf_fct_1D = swf.ZNB_VNA_sweep(VNA_instr,
start_freq=start_freq,
stop_freq=stop_freq,
npts=nbr_points,
force_reset=True)
MC_instr.set_sweep_function(swf_fct_1D)
elif center_freq != None and span != None:
swf_fct_1D = swf.ZNB_VNA_sweep(VNA_instr,
center_freq=center_freq,
span=span,
npts=nbr_points,
force_reset=True)
MC_instr.set_sweep_function(swf_fct_1D)
if start_power != None and stop_power != None:
# it prepares the sweep_points, such that it does not complain.
swf_fct_1D.prepare()
MC_instr.set_sweep_points(swf_fct_1D.sweep_points)
MC_instr.set_sweep_function_2D(VNA_instr.power)
MC_instr.set_sweep_points_2D(np.arange(start_power,
stop_power+step_power/2.,
step_power))
else:
raise ValueError('Need to define power range.')
# set VNA detector function
MC_instr.set_detector_function(det.ZNB_VNA_detector(VNA_instr))
# VNA settings
VNA_instr.average_state('off')
VNA_instr.bandwidth(bandwidth)
# hack to measure S parameters different from S21
str_to_write = "calc:par:meas 'trc1', '%s'" % measure
print(str_to_write)
VNA_instr.visa_handle.write(str_to_write)
VNA_instr.timeout(600)
MC_instr.run(name=file_name, mode='2D')
# ma.Homodyne_Analysis(auto=True, label=file_name, fitting_model='hanger')
ma.TwoD_Analysis(auto=True, label=file_name)
def acquire_2D_linear_frequency_span_vs_param(file_name, start_freq=None,
stop_freq=None, center_freq=None,
parameter=None, sweep_vector=None,
span=None, nbr_points=101, power=-20,
bandwidth=100, measure='S21'):
"""
Acquires a single trace from the VNA.
Inputs:
file_name (str), name of the output file.
start_freq (float), starting frequency of the trace.
stop_freq (float), stoping frequency of the trace.
center_freq (float), central frequency of the trace.
span (float), span of the trace.
nbr_points (int), Number of points within the trace.
power (float), power in dBm.
bandwidth (float), bandwidth in Hz.
measure (str), scattering parameter to measure (ie. 'S21').
Output:
NONE
Beware that start/stop and center/span are just two ways of configuring the
same thing.
"""
# set VNA sweep function
if start_freq != None and stop_freq != None:
swf_fct_1D = swf.ZNB_VNA_sweep(VNA_instr,
start_freq=start_freq,
stop_freq=stop_freq,
npts=nbr_points,
force_reset=True)
MC_instr.set_sweep_function(swf_fct_1D)
elif center_freq != None and span != None:
swf_fct_1D = swf.ZNB_VNA_sweep(VNA_instr,
center_freq=center_freq,
span=span,
npts=nbr_points,
force_reset=True)
MC_instr.set_sweep_function(swf_fct_1D)
if parameter is not None and sweep_vector is not None:
# it prepares the sweep_points, such that it does not complain.
swf_fct_1D.prepare()
MC_instr.set_sweep_points(swf_fct_1D.sweep_points)
MC_instr.set_sweep_function_2D(parameter)
MC_instr.set_sweep_points_2D(sweep_vector)
else:
raise ValueError('Need to define parameter and its range.')
# set VNA detector function
MC_instr.set_detector_function(det.ZNB_VNA_detector(VNA_instr))
# VNA settings
VNA_instr.power(power)
VNA_instr.average_state('off')
VNA_instr.bandwidth(bandwidth)
# hack to measure S parameters different from S21
str_to_write = "calc:par:meas 'trc1', '%s'" % measure
print(str_to_write)
VNA_instr.visa_handle.write(str_to_write)
VNA_instr.timeout(600)
MC_instr.run(name=file_name, mode='2D')
# ma.Homodyne_Analysis(auto=True, label=file_name, fitting_model='hanger')
ma.TwoD_Analysis(auto=True, label=file_name)
def acquire_disjoint_frequency_traces(file_name, list_freq_ranges,
power=-20,
bandwidth=100, measure='S21'):
"""
list_freq_ranges is a list that contains the arays defining all the ranges of interest.
"""
for idx, range_array in enumerate(list_freq_ranges):
this_file = file_name + '_%d'%idx
acquire_single_linear_frequency_span(file_name = this_file,
start_freq=range_array[0],
stop_freq=range_array[-1],
nbr_points=len(range_array),
power=power,
bandwidth=bandwidth,
measure=measure)
packing_mmts(file_name, labels=file_name+'__', N=len(list_freq_ranges))
def packing_mmts(file_name, labels, N):
# imports data
# stacks it toghether
for idx in range(N):
this_file = file_name + '_%d'%idx
ma_obj = ma.MeasurementAnalysis(label=this_file, auto=False)
ma_obj.get_naming_and_values()
if idx==0:
data_points = ma_obj.sweep_points
data_vector = ma_obj.measured_values
else:
data_points = np.hstack((data_points,ma_obj.sweep_points))
data_vector = np.hstack((data_vector,ma_obj.measured_values))
del ma_obj
data_vector = np.array(data_vector)
data_points = np.array(data_points)
sort_mask = np.argsort(data_points)
data_points = data_points[sort_mask]
data_vector = data_vector[:,sort_mask]
# keeps track of sweeppoints call
class call_counter:
def __init__(self):
self.counter=0
swp_points_counter = call_counter()
def wrapped_data_importing(counter):
counter.counter += 1
return data_vector[:,counter.counter-1]
detector_inst = det.Function_Detector_list(
sweep_function=wrapped_data_importing,
result_keys=['Amp', 'phase', 'I', 'Q' ,'Amp_dB'],
msmt_kw={'counter': swp_points_counter})
MC_instr.set_sweep_function(swf.None_Sweep(name='VNA sweep'))
MC_instr.set_sweep_points(data_points.flatten())
MC_instr.set_detector_function(detector_inst)
MC_instr.run(name=file_name)
| DiCarloLab-Delft/PycQED_py3 | pycqed/measurement/VNA_module.py | Python | mit | 12,353 |
Template.login.events({
'submit form': function(){
event.preventDefault();
var email = event.target.email.value;
var password = event.target.password.value;
//error handling
Meteor.loginWithPassword(email, password, function(error){
if (error) {
alert(error.reason);
} else{
Router.go('/');
};
});
}
}); | quanbinn/healthygeek | client/templates/login.js | JavaScript | mit | 336 |
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// Flags: --expose_externalize_string
'use strict';
const common = require('../common');
const assert = require('assert');
const path = require('path');
const fs = require('fs');
const tmpdir = require('../common/tmpdir');
tmpdir.refresh();
const fn = path.join(tmpdir.path, 'write.txt');
const fn2 = path.join(tmpdir.path, 'write2.txt');
const fn3 = path.join(tmpdir.path, 'write3.txt');
const expected = 'ümlaut.';
const constants = fs.constants;
/* eslint-disable no-undef */
common.allowGlobals(externalizeString, isOneByteString, x);
{
const expected = 'ümlaut eins'; // Must be a unique string.
externalizeString(expected);
assert.strictEqual(true, isOneByteString(expected));
const fd = fs.openSync(fn, 'w');
fs.writeSync(fd, expected, 0, 'latin1');
fs.closeSync(fd);
assert.strictEqual(expected, fs.readFileSync(fn, 'latin1'));
}
{
const expected = 'ümlaut zwei'; // Must be a unique string.
externalizeString(expected);
assert.strictEqual(true, isOneByteString(expected));
const fd = fs.openSync(fn, 'w');
fs.writeSync(fd, expected, 0, 'utf8');
fs.closeSync(fd);
assert.strictEqual(expected, fs.readFileSync(fn, 'utf8'));
}
{
const expected = '中文 1'; // Must be a unique string.
externalizeString(expected);
assert.strictEqual(false, isOneByteString(expected));
const fd = fs.openSync(fn, 'w');
fs.writeSync(fd, expected, 0, 'ucs2');
fs.closeSync(fd);
assert.strictEqual(expected, fs.readFileSync(fn, 'ucs2'));
}
{
const expected = '中文 2'; // Must be a unique string.
externalizeString(expected);
assert.strictEqual(false, isOneByteString(expected));
const fd = fs.openSync(fn, 'w');
fs.writeSync(fd, expected, 0, 'utf8');
fs.closeSync(fd);
assert.strictEqual(expected, fs.readFileSync(fn, 'utf8'));
}
/* eslint-enable no-undef */
fs.open(fn, 'w', 0o644, common.mustCall(function(err, fd) {
assert.ifError(err);
const done = common.mustCall(function(err, written) {
assert.ifError(err);
assert.strictEqual(Buffer.byteLength(expected), written);
fs.closeSync(fd);
const found = fs.readFileSync(fn, 'utf8');
fs.unlinkSync(fn);
assert.strictEqual(expected, found);
});
const written = common.mustCall(function(err, written) {
assert.ifError(err);
assert.strictEqual(0, written);
fs.write(fd, expected, 0, 'utf8', done);
});
fs.write(fd, '', 0, 'utf8', written);
}));
const args = constants.O_CREAT | constants.O_WRONLY | constants.O_TRUNC;
fs.open(fn2, args, 0o644, common.mustCall((err, fd) => {
assert.ifError(err);
const done = common.mustCall((err, written) => {
assert.ifError(err);
assert.strictEqual(Buffer.byteLength(expected), written);
fs.closeSync(fd);
const found = fs.readFileSync(fn2, 'utf8');
fs.unlinkSync(fn2);
assert.strictEqual(expected, found);
});
const written = common.mustCall(function(err, written) {
assert.ifError(err);
assert.strictEqual(0, written);
fs.write(fd, expected, 0, 'utf8', done);
});
fs.write(fd, '', 0, 'utf8', written);
}));
fs.open(fn3, 'w', 0o644, common.mustCall(function(err, fd) {
assert.ifError(err);
const done = common.mustCall(function(err, written) {
assert.ifError(err);
assert.strictEqual(Buffer.byteLength(expected), written);
fs.closeSync(fd);
});
fs.write(fd, expected, done);
}));
[false, 'test', {}, [], null, undefined].forEach((i) => {
common.expectsError(
() => fs.write(i, common.mustNotCall()),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError
}
);
common.expectsError(
() => fs.writeSync(i),
{
code: 'ERR_INVALID_ARG_TYPE',
type: TypeError
}
);
});
| MTASZTAKI/ApertusVR | plugins/languageAPI/jsAPI/3rdParty/nodejs/10.1.0/source/test/parallel/test-fs-write.js | JavaScript | mit | 4,815 |
using System;
using Microsoft.Extensions.DependencyInjection;
using ZptSharp.Dom;
using ZptSharp.Hosting;
namespace ZptSharp
{
/// <summary>
/// Extension methods for <see cref="IBuildsHostingEnvironment"/> instances.
/// </summary>
public static class XmlHostingBuilderExtensions
{
/// <summary>
/// Adds service registrations to the <paramref name="builder"/> in order
/// to enable reading & writing of XML documents.
/// </summary>
/// <param name="builder">The self-hosting builder.</param>
/// <returns>The self-hosting builder instance, after setting it up.</returns>
public static IBuildsHostingEnvironment AddXmlZptDocuments(this IBuildsHostingEnvironment builder)
{
if (builder == null)
throw new ArgumentNullException(nameof(builder));
builder.ServiceCollection.AddTransient<XmlDocumentProvider>();
builder.ServiceCollection.AddTransient<IGetsXhtmlDtds, Dom.Resources.EmbeddedResourceXhtmlDtdProvider>();
builder.ServiceCollection.AddTransient<IGetsXmlReaderSettings, XmlReaderSettingsFactory>();
builder.ServiceRegistry.DocumentProviderTypes.Add(typeof(XmlDocumentProvider));
return builder;
}
}
}
| csf-dev/ZPT-Sharp | DocumentProviders/ZptSharp.Xml/XmlHostingBuilderExtensions.cs | C# | mit | 1,301 |
<?php
namespace Brasa\RecursoHumanoBundle\Repository;
use Doctrine\ORM\EntityRepository;
/**
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class RhuCapacitacionTipoRepository extends EntityRepository {
} | wariox3/brasa | src/Brasa/RecursoHumanoBundle/Repository/RhuCapacitacionTipoRepository.php | PHP | mit | 270 |
var through = require('through2');
var cheerio = require('cheerio');
var gulp = require('gulp');
var url = require('url');
var path = require('path');
var fs = require('fs');
var typeMap = {
css: {
tag: 'link',
template: function(contents, el) {
var attribute = el.attr('media');
attribute = attribute ? ' media="' + attribute + '" ' : '';
return '<style' + attribute + '>\n' + String(contents) + '\n</style>';
},
filter: function(el) {
return el.attr('rel') === 'stylesheet' && isLocal(el.attr('href'));
},
getSrc: function(el) {
return el.attr('href');
}
},
js: {
tag: 'script',
template: function(contents) {
return '<script type="text/javascript">\n' + String(contents) + '\n</script>';
},
filter: function(el) {
return isLocal(el.attr('src'));
},
getSrc: function(el) {
return el.attr('src');
}
},
img: {
tag: 'img',
template: function(contents, el) {
el.attr('src', 'data:image/unknown;base64,' + contents.toString('base64'));
return cheerio.html(el);
},
filter: function(el) {
var src = el.attr('src');
return !/\.svg$/.test(src);
},
getSrc: function(el) {
return el.attr('src');
}
},
svg: {
tag: 'img',
template: function(contents) {
return String(contents);
},
filter: function(el) {
var src = el.attr('src');
return /\.svg$/.test(src) && isLocal(src);
},
getSrc: function(el) {
return el.attr('src');
}
}
};
function noop() {
return through.obj(function(file, enc, cb) {
this.push(file);
cb();
});
}
function after(n, cb) {
var i = 0;
return function() {
i++;
if(i === n) cb.apply(this, arguments);
};
}
function isLocal(href) {
return href && href.slice(0, 2) !== '//' && ! url.parse(href).hostname;
}
function replace(el, tmpl) {
return through.obj(function(file, enc, cb) {
el.replaceWith(tmpl(file.contents, el));
this.push(file);
cb();
});
}
function inject($, process, base, cb, opts, relative, ignoredFiles) {
var items = [];
$(opts.tag).each(function(idx, el) {
el = $(el);
if(opts.filter(el)) {
items.push(el);
}
});
if(items.length) {
var done = after(items.length, cb);
items.forEach(function(el) {
var src = opts.getSrc(el) || '';
var file = path.join(src[0] === '/' ? base : relative, src);
if (fs.existsSync(file) && ignoredFiles.indexOf(src) === -1) {
gulp.src(file)
.pipe(process || noop())
.pipe(replace(el, opts.template))
.pipe(through.obj(function(file, enc, cb) {
cb();
}, done));
} else {
done();
}
});
} else {
cb();
}
}
module.exports = function(opts) {
opts = opts || {};
opts.base = opts.base || '';
opts.ignore = opts.ignore || [];
opts.disabledTypes = opts.disabledTypes || [];
return through.obj(function(file, enc, cb) {
var self = this;
var $ = cheerio.load(String(file.contents), {decodeEntities: false});
var typeKeys = Object.getOwnPropertyNames(typeMap);
var done = after(typeKeys.length, function() {
file.contents = new Buffer($.html());
self.push(file);
cb();
});
typeKeys.forEach(function(type) {
if (opts.disabledTypes.indexOf(type) === -1) {
inject($, opts[type], opts.base, done, typeMap[type], path.dirname(file.path), opts.ignore);
} else {
done();
}
});
});
};
| jonnyscholes/gulp-inline | index.js | JavaScript | mit | 3,543 |
package strain
type Ints []int
type Lists [][]int
type Strings []string
func (i Ints) Keep(filter func(int) bool) Ints {
if i == nil {
return nil
}
filtered := []int{}
for _, v := range i {
if filter(v) {
filtered = append(filtered, v)
}
}
i = filtered
return i
}
func (i Ints) Discard(filter func(int) bool) Ints {
if i == nil {
return nil
}
return i.Keep(func(i int) bool {
return !filter(i)
})
}
func (l Lists) Keep(filter func([]int) bool) Lists {
if l == nil {
return nil
}
filtered := [][]int{}
for _, v := range l {
if filter(v) {
filtered = append(filtered, v)
}
}
l = filtered
return l
}
func (s Strings) Keep(filter func(string) bool) Strings {
if s == nil {
return nil
}
filtered := []string{}
for _, v := range s {
if filter(v) {
filtered = append(filtered, v)
}
}
s = filtered
return s
}
| rootulp/exercism | go/strain/strain.go | GO | mit | 862 |
package main
import (
"fmt"
"time"
"github.com/kevinburke/rct/genetic"
)
func main() {
files := genetic.GetOldFiles(1 * time.Hour)
for _, file := range files {
fmt.Println(file)
}
}
| kevinburke/rct | genetic/get_old_experiments/main.go | GO | mit | 193 |
using System;
namespace SampleWebAPIApp.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Describes a type model.
/// </summary>
public abstract class ModelDescription
{
public string Documentation { get; set; }
public Type ModelType { get; set; }
public string Name { get; set; }
}
} | adzhazhev/ASP.NET-Web-Forms | 01. Introduction-to-ASP.NET/01. Sample-ASP.NET-Apps/SampleWebAPIApp/Areas/HelpPage/ModelDescriptions/ModelDescription.cs | C# | mit | 338 |
/*******************************************************************************
*
* MIT License
*
* Copyright (c) 2017 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*******************************************************************************/
#include <miopen/rnn.hpp>
#include <miopen/rnn_util.hpp>
#include <miopen/activ.hpp>
#include <miopen/env.hpp>
#include <miopen/gemm_v2.hpp>
#include <miopen/logger.hpp>
#include <vector>
#include <numeric>
#include <algorithm>
namespace miopen {
// Assuming sequence length is set to > 0 otherwise throw exception.
void RNNDescriptor::RNNForwardInference(Handle& handle,
const int seqLen,
c_array_view<const miopenTensorDescriptor_t> xDesc,
ConstData_t x,
const TensorDescriptor& hxDesc,
ConstData_t hx,
const TensorDescriptor& cxDesc,
ConstData_t cx,
const TensorDescriptor& wDesc,
ConstData_t w,
c_array_view<const miopenTensorDescriptor_t> yDesc,
Data_t y,
const TensorDescriptor& hyDesc,
Data_t hy,
const TensorDescriptor& cyDesc,
Data_t cy,
Data_t workSpace,
size_t workSpaceSize) const
{
if(x == nullptr || w == nullptr || y == nullptr)
{
MIOPEN_THROW(miopenStatusBadParm);
}
if(hxDesc.GetSize() != cxDesc.GetSize() || hxDesc.GetSize() != hyDesc.GetSize() ||
hxDesc.GetSize() != cyDesc.GetSize())
{
MIOPEN_THROW(miopenStatusBadParm);
}
if(workSpaceSize < GetWorkspaceSize(handle, seqLen, xDesc))
{
MIOPEN_THROW("Workspace is required");
}
std::string network_config;
std::vector<int> in_n;
int in_h = xDesc[0].GetLengths()[1]; // input vector size
int hy_d = hyDesc.GetLengths()[0]; // biNumLayers
int hy_n = hyDesc.GetLengths()[1]; // max batch size
int hy_h = hyDesc.GetLengths()[2]; // hidden size
int out_h = yDesc[0].GetLengths()[1]; // output vector size
if(in_h <= 0 || hy_h <= 0 || hy_n <= 0 || hy_d <= 0 || out_h <= 0 || seqLen <= 0)
{
MIOPEN_THROW(miopenStatusBadParm);
}
int batch_n = 0;
for(int i = 0; i < seqLen; i++)
{
int batchval, inputvec, batchvalout, outputvec;
std::tie(batchval, inputvec) = miopen::tien<2>(xDesc[i].GetLengths());
std::tie(batchvalout, outputvec) = miopen::tien<2>(yDesc[i].GetLengths());
if(batchval != batchvalout)
{
MIOPEN_THROW(miopenStatusBadParm,
"Input batch length: " + std::to_string(batchval) +
", Output batch length: " + std::to_string(batchvalout));
}
if(i == 0)
{
if(batchval <= 0)
{
MIOPEN_THROW(miopenStatusBadParm, "Input batch is ZERO!");
}
}
else
{
if(batchval > in_n.back() || batchval < 0)
{
MIOPEN_THROW(miopenStatusBadParm,
"Incorrect input batch size at time " + std::to_string(i) +
"! Batch size must not ascend!");
}
}
in_n.push_back(batchval);
batch_n += batchval;
}
int bi = dirMode != 0u ? 2 : 1;
if(out_h != (bi * hy_h))
{
MIOPEN_THROW(miopenStatusBadParm, "Output size doesn't match hidden state size!");
}
float ctime = 0.;
int in_stride = in_h;
int hy_stride = hy_h * bi * static_cast<int>(workspaceScale);
int out_stride = out_h;
int wei_stride = hy_h * bi * static_cast<int>(nHiddenTensorsPerLayer);
int uni_stride = hy_h;
int bi_stride = hy_h * bi;
if(inputMode == miopenRNNskip)
{
if(in_h != hy_h)
{
MIOPEN_THROW(miopenStatusBadParm,
"The input tensor size must equal to the hidden "
"state size of the network in SKIP_INPUT mode!");
}
in_h = 0;
}
size_t wei_shift_bias = (in_h + hy_h + (bi * hy_h + hy_h) * (nLayers - 1)) * wei_stride;
size_t offset;
float alpha0, alpha1, beta_t;
float alpha = 1, beta = 0;
std::vector<int> sp_size(3, 1), sp_stride(3, 1), w_size(3, 1), w_stride(3, 1), x_size(3, 1),
x_stride(3, 1), y_size(3, 1), y_stride(3, 1), hx_size(3, 1), hx_stride(3, 1);
miopen::TensorDescriptor sp_desc, w_desc, x_desc, y_desc, hx_desc;
sp_size[2] = workSpaceSize / GetTypeSize(wDesc.GetType());
sp_stride[0] = sp_size[2];
sp_stride[1] = sp_size[2];
sp_desc = miopen::TensorDescriptor(wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
SetTensor(handle, sp_desc, workSpace, &beta);
// Update time
profileRNNkernels(handle, 0, ctime);
sp_stride[0] = batch_n * hy_stride;
sp_stride[1] = hy_stride;
sp_size[2] = 1;
w_stride[0] = wei_stride;
w_stride[1] = wei_stride;
x_stride[0] = batch_n * in_stride;
x_stride[1] = in_stride;
y_stride[0] = batch_n * out_stride;
y_stride[1] = out_stride;
if(hy != nullptr || (rnnMode == miopenLSTM && cy != nullptr))
{
hx_size[2] = hy_d * hy_n * hy_h;
hx_stride[0] = hx_size[2];
hx_stride[1] = hx_size[2];
hx_desc = miopen::TensorDescriptor(wDesc.GetType(), hx_size.data(), hx_stride.data(), 3);
if(hy != nullptr)
{
SetTensor(handle, hx_desc, hy, &beta);
// Update time
profileRNNkernels(handle, 1, ctime);
}
if(rnnMode == miopenLSTM && cy != nullptr)
{
SetTensor(handle, hx_desc, cy, &beta);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
hx_stride[0] = in_n.at(0) * uni_stride;
hx_stride[1] = uni_stride;
#if MIOPEN_USE_GEMM
int wei_shift, prelayer_shift;
int wei_len = 0;
int hid_off = 0;
switch(rnnMode)
{
case miopenRNNRELU:
case miopenRNNTANH:
// printf("run rnn gpu inference \n");
wei_len = hy_h;
hid_off = 0;
break;
case miopenLSTM:
// printf("run lstm gpu inference \n");
wei_len = hy_h * 4;
hid_off = bi * hy_h * 5;
break;
case miopenGRU:
// printf("run gru gpu inference \n");
wei_len = hy_h * 3;
hid_off = bi * hy_h * 3;
break;
}
ActivationDescriptor tanhDesc, sigDesc, activDesc;
sigDesc = {miopenActivationLOGISTIC, 1, 0, 1};
tanhDesc = {miopenActivationTANH, 1, 1, 1};
if(rnnMode == miopenRNNRELU)
{
activDesc = {miopenActivationRELU, 1, 0, 1};
}
else if(rnnMode == miopenRNNTANH)
{
activDesc = {miopenActivationTANH, 1, 1, 1};
}
for(int li = 0; li < nLayers; li++)
{
int hid_shift = li * batch_n * hy_stride;
int hx_shift = li * hy_n * bi_stride;
int wei_shift_bias_temp = static_cast<int>(wei_shift_bias) + li * 2 * wei_stride;
// from input
if(li == 0)
{
if(inputMode == miopenRNNskip)
{
x_size[1] = batch_n;
x_size[2] = hy_h;
sp_size[1] = batch_n;
sp_size[2] = hy_h;
x_desc =
miopen::TensorDescriptor(wDesc.GetType(), x_size.data(), x_stride.data(), 3);
sp_desc =
miopen::TensorDescriptor(wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
for(int gi = 0; gi < nHiddenTensorsPerLayer * bi; gi++)
{
CopyTensor(handle, x_desc, x, sp_desc, workSpace, 0, gi * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
else
{
miopen::GemmDescriptor gemm_desc = GemmDescriptor{false,
false,
true,
batch_n,
wei_len * bi,
in_h,
in_stride,
in_stride,
hy_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
1, // beta
xDesc[0].GetType()};
miopenStatus_t gemm_status = CallGemm(handle,
gemm_desc,
x,
0,
w,
0,
workSpace,
hid_shift,
nullptr,
GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
else
{
wei_shift = (in_h + hy_h) * wei_stride + (li - 1) * (bi * hy_h + hy_h) * wei_stride;
prelayer_shift = (li - 1) * batch_n * hy_stride + hid_off;
miopen::GemmDescriptor gemm_desc = GemmDescriptor{false,
false,
true,
batch_n,
wei_len * bi,
hy_h * bi,
hy_stride,
bi_stride,
hy_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
1, // beta
xDesc[0].GetType()};
miopenStatus_t gemm_status = CallGemm(handle,
gemm_desc,
workSpace,
prelayer_shift,
w,
wei_shift,
workSpace,
hid_shift,
nullptr,
GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
profileRNNkernels(handle, 1, ctime);
}
if(biasMode != 0u)
{
alpha0 = 1;
alpha1 = 1;
beta_t = 0;
w_size[1] = 1;
w_size[2] = wei_stride;
sp_size[1] = batch_n;
sp_size[2] = wei_stride;
w_desc = miopen::TensorDescriptor(wDesc.GetType(), w_size.data(), w_stride.data(), 3);
sp_desc =
miopen::TensorDescriptor(wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
sp_desc,
workSpace,
&alpha1,
w_desc,
w,
&beta_t,
sp_desc,
workSpace,
hid_shift,
wei_shift_bias_temp,
hid_shift);
// Update time
profileRNNkernels(handle, 1, ctime);
}
if(rnnMode == miopenGRU)
{
sp_size[1] = batch_n;
sp_size[2] = hy_h;
sp_desc =
miopen::TensorDescriptor(wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
alpha0 = 0;
alpha1 = 0;
beta_t = 0;
for(int bs = 0; bs < bi; bs++)
{
CopyTensor(handle,
sp_desc,
workSpace,
sp_desc,
workSpace,
hid_shift + bs * wei_len + 2 * hy_h,
hid_shift + hid_off + bs * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
workSpace,
&beta_t,
sp_desc,
workSpace,
hid_shift + bs * wei_len + 2 * hy_h,
hid_shift + bs * wei_len + 2 * hy_h,
hid_shift + bs * wei_len + 2 * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
if(biasMode != 0u)
{
wei_shift_bias_temp += wei_stride;
alpha0 = 1;
alpha1 = 1;
beta_t = 0;
if(hx != nullptr)
{
sp_size[1] = batch_n;
sp_size[2] = wei_stride;
sp_desc =
miopen::TensorDescriptor(wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
sp_desc,
workSpace,
&alpha1,
w_desc,
w,
&beta_t,
sp_desc,
workSpace,
hid_shift,
wei_shift_bias_temp,
hid_shift);
// Update time
profileRNNkernels(handle, 1, ctime);
}
else
{
sp_size[1] = batch_n - in_n.at(0);
sp_size[2] = wei_len;
sp_desc =
miopen::TensorDescriptor(wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
w_size[1] = 1;
w_size[2] = wei_len;
w_desc =
miopen::TensorDescriptor(wDesc.GetType(), w_size.data(), w_stride.data(), 3);
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
sp_desc,
workSpace,
&alpha1,
w_desc,
w,
&beta_t,
sp_desc,
workSpace,
hid_shift + in_n.at(0) * hy_stride,
wei_shift_bias_temp,
hid_shift + in_n.at(0) * hy_stride);
// Update time
profileRNNkernels(handle, 1, ctime);
if(dirMode != 0u)
{
if(in_n.at(0) == in_n.at(seqLen - 1))
{
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
sp_desc,
workSpace,
&alpha1,
w_desc,
w,
&beta_t,
sp_desc,
workSpace,
hid_shift + wei_len,
wei_shift_bias_temp + wei_len,
hid_shift + wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
}
else
{
int cur_batch = 0;
for(int ti = 0; ti < seqLen; ti++)
{
if(ti != (seqLen - 1))
{
offset = hid_shift + cur_batch * hy_stride;
sp_size[1] = in_n.at(ti + 1);
sp_size[2] = wei_len;
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
sp_desc,
workSpace,
&alpha1,
w_desc,
w,
&beta_t,
sp_desc,
workSpace,
offset + wei_len,
wei_shift_bias_temp + wei_len,
offset + wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
}
cur_batch += in_n.at(ti);
}
}
}
}
}
// from hidden state
int bacc = 0;
int baccbi = batch_n;
for(int ti = 0; ti < seqLen; ti++)
{
baccbi -= in_n.at(seqLen - 1 - ti);
wei_shift = in_h * wei_stride + li * (bi * hy_h + hy_h) * wei_stride;
int pretime_shift = 0;
int use_time = 0;
for(int ri = 0; ri < bi; ri++)
{
int cur_time = ri == 0 ? ti : seqLen - 1 - ti;
int cur_batch = ri == 0 ? bacc : baccbi;
offset = hid_shift + cur_batch * hy_stride;
if(ti > 0)
{
pretime_shift =
ri == 0 ? hid_shift + (bacc - in_n.at(ti - 1)) * hy_stride
: hid_shift + (baccbi + in_n.at(seqLen - 1 - ti)) * hy_stride;
use_time = ri == 0 ? ti : seqLen - ti;
}
if(in_n.at(cur_time) > 0)
{
if(ti == 0)
{
if(hx != nullptr)
{
miopen::GemmDescriptor gemm_desc = GemmDescriptor{false,
false,
true,
in_n.at(cur_time),
wei_len,
hy_h,
uni_stride,
uni_stride,
hy_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
1, // beta
xDesc[0].GetType()};
miopenStatus_t gemm_status =
CallGemm(handle,
gemm_desc,
hx,
hx_shift + ri * hy_n * hy_h,
w,
wei_shift + ri * wei_len * uni_stride,
workSpace,
static_cast<int>(offset) + ri * wei_len,
nullptr,
GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
else
{
if(ri == 1 && hx != nullptr && in_n.at(cur_time) > in_n.at(use_time))
{
miopen::GemmDescriptor gemm_desc =
GemmDescriptor{false,
false,
true,
(in_n.at(cur_time) - in_n.at(use_time)),
wei_len,
hy_h,
uni_stride,
uni_stride,
hy_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
1, // beta
xDesc[0].GetType()};
miopenStatus_t gemm_status =
CallGemm(handle,
gemm_desc,
hx,
hx_shift + ri * hy_n * hy_h + in_n.at(use_time) * hy_h,
w,
wei_shift + ri * wei_len * uni_stride,
workSpace,
static_cast<int>(offset) + ri * wei_len +
in_n.at(use_time) * hy_stride,
nullptr,
GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
profileRNNkernels(handle, 1, ctime);
}
if(in_n.at(use_time) > 0)
{
miopen::GemmDescriptor gemm_desc = GemmDescriptor{false,
false,
true,
in_n.at(use_time),
wei_len,
hy_h,
hy_stride,
uni_stride,
hy_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
1, // beta
xDesc[0].GetType()};
miopenStatus_t gemm_status =
CallGemm(handle,
gemm_desc,
workSpace,
pretime_shift + hid_off + ri * hy_h,
w,
wei_shift + ri * wei_len * uni_stride,
workSpace,
static_cast<int>(offset) + ri * wei_len,
nullptr,
GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
// update hidden status
sp_size[1] = in_n.at(cur_time);
if(rnnMode == miopenRNNRELU || rnnMode == miopenRNNTANH)
{
sp_size[2] = hy_h;
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
activDesc.Forward(handle,
&alpha,
sp_desc,
workSpace,
&beta,
sp_desc,
workSpace,
offset + ri * wei_len,
offset + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
}
else if(rnnMode == miopenLSTM)
{
if(algoMode == miopenRNNdefault)
{
LSTMForwardHiddenStateUpdate(handle,
wDesc.GetType(),
true,
ti == 0,
ri,
in_n.at(0),
in_n.at(cur_time),
in_n.at(use_time),
hy_h,
hy_stride,
wei_len,
wei_stride,
cx,
hx_shift + ri * hy_n * hy_h,
workSpace,
offset + ri * wei_len,
offset + hy_h + ri * wei_len,
offset + 2 * hy_h + ri * wei_len,
offset + 3 * hy_h + ri * wei_len,
offset + bi * wei_len + ri * hy_h,
pretime_shift + bi * wei_len + ri * hy_h,
0,
offset + hid_off + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
continue;
}
// active gate i, f, o
sp_size[2] = hy_h * 3;
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
sigDesc.Forward(handle,
&alpha,
sp_desc,
workSpace,
&beta,
sp_desc,
workSpace,
offset + ri * wei_len,
offset + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
// active gate c
sp_size[2] = hy_h;
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
tanhDesc.Forward(handle,
&alpha,
sp_desc,
workSpace,
&beta,
sp_desc,
workSpace,
offset + 3 * hy_h + ri * wei_len,
offset + 3 * hy_h + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
// update cell state
alpha0 = 1;
alpha1 = 1;
beta_t = 1;
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
workSpace,
&beta_t,
sp_desc,
workSpace,
offset + ri * wei_len,
offset + 3 * hy_h + ri * wei_len,
offset + bi * wei_len + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
if(ti == 0)
{
if(cx != nullptr)
{
hx_size[1] = in_n.at(cur_time);
hx_size[2] = hy_h;
hx_desc = miopen::TensorDescriptor(
wDesc.GetType(), hx_size.data(), hx_stride.data(), 3);
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
hx_desc,
cx,
&beta_t,
sp_desc,
workSpace,
offset + hy_h + ri * wei_len,
hx_shift + ri * hy_n * hy_h,
offset + bi * wei_len + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
else
{
if(ri == 1 && cx != nullptr && in_n.at(cur_time) > in_n.at(use_time))
{
hx_size[1] = in_n.at(cur_time) - in_n.at(use_time);
hx_size[2] = hy_h;
hx_desc = miopen::TensorDescriptor(
wDesc.GetType(), hx_size.data(), hx_stride.data(), 3);
sp_size[1] = in_n.at(cur_time) - in_n.at(use_time);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
hx_desc,
cx,
&beta_t,
sp_desc,
workSpace,
offset + hy_h + ri * wei_len +
in_n.at(use_time) * hy_stride,
hx_shift + ri * hy_n * hy_h + in_n.at(use_time) * hy_h,
offset + bi * wei_len + ri * hy_h +
in_n.at(use_time) * hy_stride);
// Update time
profileRNNkernels(handle, 1, ctime);
sp_size[1] = in_n.at(cur_time);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
}
if(in_n.at(use_time) > 0)
{
if(in_n.at(use_time) != in_n.at(cur_time))
{
sp_size[1] = in_n.at(use_time);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
}
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
workSpace,
&beta_t,
sp_desc,
workSpace,
offset + hy_h + ri * wei_len,
pretime_shift + bi * wei_len + ri * hy_h,
offset + bi * wei_len + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
if(in_n.at(use_time) != in_n.at(cur_time))
{
sp_size[1] = in_n.at(cur_time);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
}
}
}
// active cell state
tanhDesc.Forward(handle,
&alpha,
sp_desc,
workSpace,
&beta,
sp_desc,
workSpace,
offset + bi * wei_len + ri * hy_h,
offset + hid_off + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
// update hidden state
beta_t = 0;
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
workSpace,
&beta_t,
sp_desc,
workSpace,
offset + 2 * hy_h + ri * wei_len,
offset + hid_off + ri * hy_h,
offset + hid_off + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
}
else if(rnnMode == miopenGRU)
{
// active z, r gate
sp_size[2] = 2 * hy_h;
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
sigDesc.Forward(handle,
&alpha,
sp_desc,
workSpace,
&beta,
sp_desc,
workSpace,
offset + ri * wei_len,
offset + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
// calculate c gate
sp_size[2] = hy_h;
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
alpha0 = 1;
alpha1 = 1;
beta_t = 0;
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
workSpace,
&beta_t,
sp_desc,
workSpace,
offset + hy_h + ri * wei_len,
offset + 2 * hy_h + ri * wei_len,
offset + 2 * hy_h + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
workSpace,
&beta_t,
sp_desc,
workSpace,
offset + 2 * hy_h + ri * wei_len,
offset + hid_off + ri * hy_h,
offset + 2 * hy_h + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
// active c gate
tanhDesc.Forward(handle,
&alpha,
sp_desc,
workSpace,
&beta,
sp_desc,
workSpace,
offset + 2 * hy_h + ri * wei_len,
offset + 2 * hy_h + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
// calculate hidden state
alpha0 = -1;
alpha1 = 1;
beta_t = 0;
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
workSpace,
&beta_t,
sp_desc,
workSpace,
offset + ri * wei_len,
offset + 2 * hy_h + ri * wei_len,
offset + hid_off + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
alpha0 = 1;
alpha1 = 1;
beta_t = 0;
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
workSpace,
&beta_t,
sp_desc,
workSpace,
offset + 2 * hy_h + ri * wei_len,
offset + hid_off + ri * hy_h,
offset + hid_off + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
alpha0 = 1;
alpha1 = 1;
beta_t = 1;
if(ti == 0)
{
if(hx != nullptr)
{
hx_size[1] = in_n.at(cur_time);
hx_size[2] = hy_h;
hx_desc = miopen::TensorDescriptor(
wDesc.GetType(), hx_size.data(), hx_stride.data(), 3);
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
hx_desc,
hx,
&beta_t,
sp_desc,
workSpace,
offset + ri * wei_len,
hx_shift + ri * hy_n * hy_h,
offset + hid_off + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
else
{
if(ri == 1 && hx != nullptr && in_n.at(cur_time) > in_n.at(use_time))
{
hx_size[1] = in_n.at(cur_time) - in_n.at(use_time);
hx_size[2] = hy_h;
hx_desc = miopen::TensorDescriptor(
wDesc.GetType(), hx_size.data(), hx_stride.data(), 3);
sp_size[1] = in_n.at(cur_time) - in_n.at(use_time);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
hx_desc,
hx,
&beta_t,
sp_desc,
workSpace,
offset + ri * wei_len + in_n.at(use_time) * hy_stride,
hx_shift + ri * hy_n * hy_h + in_n.at(use_time) * hy_h,
offset + hid_off + ri * hy_h +
in_n.at(use_time) * hy_stride);
// Update time
profileRNNkernels(handle, 1, ctime);
sp_size[1] = in_n.at(cur_time);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
}
if(in_n.at(use_time) > 0)
{
if(in_n.at(use_time) != in_n.at(cur_time))
{
sp_size[1] = in_n.at(use_time);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
}
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
workSpace,
&beta_t,
sp_desc,
workSpace,
offset + ri * wei_len,
pretime_shift + hid_off + ri * hy_h,
offset + hid_off + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
}
}
}
bacc += in_n.at(ti);
}
// update hy, cy
if(hy != nullptr || (rnnMode == miopenLSTM && cy != nullptr))
{
hx_size[2] = hy_h;
sp_size[2] = hy_h;
bacc = batch_n;
baccbi = 0;
for(int ti = seqLen - 1; ti >= 0; ti--)
{
bacc -= in_n.at(ti);
for(int ri = 0; ri < bi; ri++)
{
int cur_time = ri == 0 ? ti : seqLen - 1 - ti;
int cur_batch = ri == 0 ? bacc : baccbi;
int use_batch = 0;
if(ti < seqLen - 1)
{
int use_time = ri == 0 ? ti + 1 : seqLen - 2 - ti;
use_batch = in_n.at(use_time);
}
if(in_n.at(cur_time) > use_batch)
{
offset = hid_shift + cur_batch * hy_stride;
sp_size[1] = in_n.at(cur_time) - use_batch;
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
hx_size[1] = sp_size[1];
hx_desc = miopen::TensorDescriptor(
wDesc.GetType(), hx_size.data(), hx_stride.data(), 3);
if(hy != nullptr)
{
CopyTensor(handle,
sp_desc,
workSpace,
hx_desc,
hy,
static_cast<int>(offset) + hid_off + ri * hy_h +
use_batch * hy_stride,
hx_shift + ri * hy_n * hy_h + use_batch * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
}
if(rnnMode == miopenLSTM && cy != nullptr)
{
CopyTensor(handle,
sp_desc,
workSpace,
hx_desc,
cy,
static_cast<int>(offset) + bi * wei_len + ri * hy_h +
use_batch * hy_stride,
hx_shift + ri * hy_n * hy_h + use_batch * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
}
baccbi += in_n.at(seqLen - 1 - ti);
}
}
}
// output
prelayer_shift = (static_cast<int>(nLayers) - 1) * batch_n * hy_stride + hid_off;
sp_size[1] = batch_n;
sp_size[2] = hy_h * bi;
y_size[1] = batch_n;
y_size[2] = out_h;
y_desc = miopen::TensorDescriptor(wDesc.GetType(), y_size.data(), y_stride.data(), 3);
sp_desc = miopen::TensorDescriptor(wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
CopyTensor(handle, sp_desc, workSpace, y_desc, y, prelayer_shift, 0);
// Update time
profileRNNkernels(handle, 2, ctime);
#else
(void)hx;
(void)cx;
(void)offset;
(void)alpha0;
(void)alpha1;
(void)beta_t;
(void)alpha;
(void)bi_stride;
(void)wei_shift_bias;
MIOPEN_THROW("GEMM is not supported");
#endif
}
void RNNDescriptor::RNNForwardTraining(Handle& handle,
const int seqLen,
c_array_view<const miopenTensorDescriptor_t> xDesc,
ConstData_t x,
const TensorDescriptor& hxDesc,
ConstData_t hx,
const TensorDescriptor& cxDesc,
ConstData_t cx,
const TensorDescriptor& wDesc,
ConstData_t w,
c_array_view<const miopenTensorDescriptor_t> yDesc,
Data_t y,
const TensorDescriptor& hyDesc,
Data_t hy,
const TensorDescriptor& cyDesc,
Data_t cy,
Data_t workSpace,
size_t workSpaceSize,
Data_t reserveSpace,
size_t reserveSpaceSize) const
{
(void)workSpace;
if(x == nullptr || w == nullptr || y == nullptr)
{
MIOPEN_THROW(miopenStatusBadParm);
}
if(hxDesc.GetSize() != cxDesc.GetSize() || hxDesc.GetSize() != hyDesc.GetSize() ||
hxDesc.GetSize() != cyDesc.GetSize())
{
MIOPEN_THROW(miopenStatusBadParm);
}
if(workSpaceSize < GetWorkspaceSize(handle, seqLen, xDesc))
{
MIOPEN_THROW("Workspace is required");
}
if(reserveSpaceSize < GetReserveSize(handle, seqLen, xDesc))
{
MIOPEN_THROW("Reservespace is required");
}
std::string network_config;
std::vector<int> in_n;
int in_h = xDesc[0].GetLengths()[1]; // input vector size
int hy_d = hyDesc.GetLengths()[0]; // biNumLayers
int hy_n = hyDesc.GetLengths()[1]; // max batch size
int hy_h = hyDesc.GetLengths()[2]; // hidden size
int out_h = yDesc[0].GetLengths()[1]; // output vector size
if(in_h <= 0 || hy_h <= 0 || hy_n <= 0 || hy_d <= 0 || out_h <= 0 || seqLen <= 0)
{
MIOPEN_THROW(miopenStatusBadParm);
}
int batch_n = 0;
for(int i = 0; i < seqLen; i++)
{
int batchval, inputvec, batchvalout, outputvec;
std::tie(batchval, inputvec) = miopen::tien<2>(xDesc[i].GetLengths());
std::tie(batchvalout, outputvec) = miopen::tien<2>(yDesc[i].GetLengths());
if(batchval != batchvalout)
{
MIOPEN_THROW(miopenStatusBadParm,
"Input batch length: " + std::to_string(batchval) +
", Output batch length: " + std::to_string(batchvalout));
}
if(i == 0)
{
if(batchval <= 0)
{
MIOPEN_THROW(miopenStatusBadParm, "Input batch is ZERO!");
}
}
else
{
if(batchval > in_n.back() || batchval < 0)
{
MIOPEN_THROW(miopenStatusBadParm,
"Incorrect input batch size at time " + std::to_string(i) +
"! Batch size must not ascend!");
}
}
in_n.push_back(batchval);
batch_n += batchval;
}
int bi = dirMode != 0u ? 2 : 1;
if(out_h != (bi * hy_h))
{
MIOPEN_THROW(miopenStatusBadParm, "Output size doesn't match hidden state size!");
}
float ctime = 0.;
int in_stride = in_h;
int hy_stride = hy_h * bi * static_cast<int>(workspaceScale);
int out_stride = out_h;
int wei_stride = hy_h * bi * static_cast<int>(nHiddenTensorsPerLayer);
int uni_stride = hy_h;
int bi_stride = hy_h * bi;
if(inputMode == miopenRNNskip)
{
if(in_h != hy_h)
{
MIOPEN_THROW(miopenStatusBadParm,
"The input tensor size must equal to the hidden "
"state size of the network in SKIP_INPUT mode!");
}
in_h = 0;
}
size_t wei_shift_bias = (in_h + hy_h + (bi * hy_h + hy_h) * (nLayers - 1)) * wei_stride;
size_t offset;
float alpha0, alpha1, beta_t;
float alpha = 1, beta = 0;
std::vector<int> sp_size(3, 1), sp_stride(3, 1), w_size(3, 1), w_stride(3, 1), x_size(3, 1),
x_stride(3, 1), y_size(3, 1), y_stride(3, 1), hx_size(3, 1), hx_stride(3, 1);
miopen::TensorDescriptor sp_desc, w_desc, x_desc, y_desc, hx_desc;
sp_size[2] = reserveSpaceSize / GetTypeSize(wDesc.GetType());
sp_stride[0] = sp_size[2];
sp_stride[1] = sp_size[2];
sp_desc = miopen::TensorDescriptor(wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
SetTensor(handle, sp_desc, reserveSpace, &beta);
// Update time
profileRNNkernels(handle, 0, ctime);
sp_stride[0] = batch_n * hy_stride;
sp_stride[1] = hy_stride;
sp_size[2] = 1;
w_stride[0] = wei_stride;
w_stride[1] = wei_stride;
x_stride[0] = batch_n * in_stride;
x_stride[1] = in_stride;
y_stride[0] = batch_n * out_stride;
y_stride[1] = out_stride;
if(hy != nullptr || (rnnMode == miopenLSTM && cy != nullptr))
{
hx_size[2] = hy_d * hy_n * hy_h;
hx_stride[0] = hx_size[2];
hx_stride[1] = hx_size[2];
hx_desc = miopen::TensorDescriptor(wDesc.GetType(), hx_size.data(), hx_stride.data(), 3);
if(hy != nullptr)
{
SetTensor(handle, hx_desc, hy, &beta);
// Update time
profileRNNkernels(handle, 1, ctime);
}
if(rnnMode == miopenLSTM && cy != nullptr)
{
SetTensor(handle, hx_desc, cy, &beta);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
hx_stride[0] = in_n.at(0) * uni_stride;
hx_stride[1] = uni_stride;
#if MIOPEN_USE_GEMM
int wei_shift, prelayer_shift;
int wei_len = 0;
int hid_off = 0;
switch(rnnMode)
{
case miopenRNNRELU:
case miopenRNNTANH:
// printf("run rnn gpu fwd \n");
wei_len = hy_h;
hid_off = static_cast<int>(nLayers) * batch_n * hy_stride;
break;
case miopenLSTM:
// printf("run lstm gpu fwd \n");
wei_len = hy_h * 4;
hid_off = bi * hy_h * 5;
break;
case miopenGRU:
// printf("run gru gpu fwd \n");
wei_len = hy_h * 3;
hid_off = bi * hy_h * 3;
break;
}
ActivationDescriptor tanhDesc, sigDesc, activDesc;
sigDesc = {miopenActivationLOGISTIC, 1, 0, 1};
tanhDesc = {miopenActivationTANH, 1, 1, 1};
if(rnnMode == miopenRNNRELU)
{
activDesc = {miopenActivationRELU, 1, 0, 1};
}
else if(rnnMode == miopenRNNTANH)
{
activDesc = {miopenActivationTANH, 1, 1, 1};
}
for(int li = 0; li < nLayers; li++)
{
int hid_shift = li * batch_n * hy_stride;
int hx_shift = li * hy_n * bi_stride;
int wei_shift_bias_temp = static_cast<int>(wei_shift_bias) + li * 2 * wei_stride;
// from input
if(li == 0)
{
if(inputMode == miopenRNNskip)
{
x_size[1] = batch_n;
x_size[2] = hy_h;
sp_size[1] = batch_n;
sp_size[2] = hy_h;
x_desc =
miopen::TensorDescriptor(wDesc.GetType(), x_size.data(), x_stride.data(), 3);
sp_desc =
miopen::TensorDescriptor(wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
for(int gi = 0; gi < nHiddenTensorsPerLayer * bi; gi++)
{
CopyTensor(handle, x_desc, x, sp_desc, reserveSpace, 0, gi * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
else
{
miopen::GemmDescriptor gemm_desc = GemmDescriptor{false,
false,
true,
batch_n,
wei_len * bi,
in_h,
in_stride,
in_stride,
hy_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
1, // beta
xDesc[0].GetType()};
miopenStatus_t gemm_status = CallGemm(handle,
gemm_desc,
x,
0,
w,
0,
reserveSpace,
hid_shift,
nullptr,
GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
else
{
wei_shift = (in_h + hy_h) * wei_stride + (li - 1) * (bi * hy_h + hy_h) * wei_stride;
prelayer_shift = (li - 1) * batch_n * hy_stride + hid_off;
bool use_dropout = !float_equal(miopen::deref(dropoutDesc).dropout, 0);
if(use_dropout)
{
std::vector<int> drop_size(2), drop_in_str(2, 1), drop_out_str(2, 1);
drop_size[0] = batch_n;
drop_size[1] = hy_h * bi;
drop_in_str[0] = hy_stride;
drop_out_str[0] = hy_h * bi;
auto drop_in_desc = miopen::TensorDescriptor(
wDesc.GetType(), drop_size.data(), drop_in_str.data(), 2);
auto drop_out_desc = miopen::TensorDescriptor(
wDesc.GetType(), drop_size.data(), drop_out_str.data(), 2);
size_t drop_rsv_size = drop_out_desc.GetElementSize();
size_t drop_rsv_start =
algoMode == miopenRNNdefault && rnnMode == miopenLSTM
? nLayers * batch_n * hy_stride + nLayers * batch_n * hy_h * bi
: 2 * nLayers * batch_n * hy_stride;
size_t drop_in_offset = prelayer_shift;
size_t drop_out_offset = drop_rsv_start + (li - 1) * batch_n * hy_h * bi;
size_t drop_rsv_offset = (drop_rsv_start + (nLayers - 1) * batch_n * hy_h * bi) *
(wDesc.GetType() == miopenFloat ? 4 : 2) +
(li - 1) * drop_rsv_size;
miopen::deref(dropoutDesc)
.DropoutForward(handle,
drop_in_desc,
drop_in_desc,
reserveSpace,
drop_out_desc,
reserveSpace,
reserveSpace,
drop_rsv_size,
drop_in_offset,
drop_out_offset,
drop_rsv_offset);
// Update time
profileRNNkernels(handle, 1, ctime);
prelayer_shift = drop_out_offset;
}
miopen::GemmDescriptor gemm_desc = GemmDescriptor{false,
false,
true,
batch_n,
wei_len * bi,
hy_h * bi,
use_dropout ? hy_h * bi : hy_stride,
bi_stride,
hy_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
1, // beta
xDesc[0].GetType()};
miopenStatus_t gemm_status = CallGemm(handle,
gemm_desc,
reserveSpace,
prelayer_shift,
w,
wei_shift,
reserveSpace,
hid_shift,
nullptr,
GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
profileRNNkernels(handle, 1, ctime);
}
if(biasMode != 0u)
{
alpha0 = 1;
alpha1 = 1;
beta_t = 0;
w_size[1] = 1;
w_size[2] = wei_stride;
sp_size[1] = batch_n;
sp_size[2] = wei_stride;
w_desc = miopen::TensorDescriptor(wDesc.GetType(), w_size.data(), w_stride.data(), 3);
sp_desc =
miopen::TensorDescriptor(wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
sp_desc,
reserveSpace,
&alpha1,
w_desc,
w,
&beta_t,
sp_desc,
reserveSpace,
hid_shift,
wei_shift_bias_temp,
hid_shift);
// Update time
profileRNNkernels(handle, 1, ctime);
}
if(rnnMode == miopenGRU)
{
sp_size[1] = batch_n;
sp_size[2] = hy_h;
sp_desc =
miopen::TensorDescriptor(wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
alpha0 = 0;
alpha1 = 0;
beta_t = 0;
for(int bs = 0; bs < bi; bs++)
{
CopyTensor(handle,
sp_desc,
reserveSpace,
sp_desc,
reserveSpace,
hid_shift + bs * wei_len + 2 * hy_h,
hid_shift + hid_off + bs * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
sp_desc,
reserveSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
sp_desc,
reserveSpace,
hid_shift + bs * wei_len + 2 * hy_h,
hid_shift + bs * wei_len + 2 * hy_h,
hid_shift + bs * wei_len + 2 * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
if(biasMode != 0u)
{
wei_shift_bias_temp += wei_stride;
alpha0 = 1;
alpha1 = 1;
beta_t = 0;
if(hx != nullptr)
{
sp_size[1] = batch_n;
sp_size[2] = wei_stride;
sp_desc =
miopen::TensorDescriptor(wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
sp_desc,
reserveSpace,
&alpha1,
w_desc,
w,
&beta_t,
sp_desc,
reserveSpace,
hid_shift,
wei_shift_bias_temp,
hid_shift);
// Update time
profileRNNkernels(handle, 1, ctime);
}
else
{
sp_size[1] = batch_n - in_n.at(0);
sp_size[2] = wei_len;
sp_desc =
miopen::TensorDescriptor(wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
w_size[1] = 1;
w_size[2] = wei_len;
w_desc =
miopen::TensorDescriptor(wDesc.GetType(), w_size.data(), w_stride.data(), 3);
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
sp_desc,
reserveSpace,
&alpha1,
w_desc,
w,
&beta_t,
sp_desc,
reserveSpace,
hid_shift + in_n.at(0) * hy_stride,
wei_shift_bias_temp,
hid_shift + in_n.at(0) * hy_stride);
// Update time
profileRNNkernels(handle, 1, ctime);
if(dirMode != 0u)
{
if(in_n.at(0) == in_n.at(seqLen - 1))
{
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
sp_desc,
reserveSpace,
&alpha1,
w_desc,
w,
&beta_t,
sp_desc,
reserveSpace,
hid_shift + wei_len,
wei_shift_bias_temp + wei_len,
hid_shift + wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
}
else
{
int cur_batch = 0;
for(int ti = 0; ti < seqLen; ti++)
{
if(ti != (seqLen - 1))
{
offset = hid_shift + cur_batch * hy_stride;
sp_size[1] = in_n.at(ti + 1);
sp_size[2] = wei_len;
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
sp_desc,
reserveSpace,
&alpha1,
w_desc,
w,
&beta_t,
sp_desc,
reserveSpace,
static_cast<int>(offset) + wei_len,
wei_shift_bias_temp + wei_len,
static_cast<int>(offset) + wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
}
cur_batch += in_n.at(ti);
}
}
}
}
}
// from hidden state
int bacc = 0;
int baccbi = batch_n;
for(int ti = 0; ti < seqLen; ti++)
{
baccbi -= in_n.at(seqLen - 1 - ti);
wei_shift = in_h * wei_stride + li * (bi * hy_h + hy_h) * wei_stride;
int pretime_shift = 0;
int use_time = 0;
for(int ri = 0; ri < bi; ri++)
{
int cur_time = ri == 0 ? ti : seqLen - 1 - ti;
int cur_batch = ri == 0 ? bacc : baccbi;
offset = hid_shift + cur_batch * hy_stride;
if(ti > 0)
{
pretime_shift =
ri == 0 ? hid_shift + (bacc - in_n.at(ti - 1)) * hy_stride
: hid_shift + (baccbi + in_n.at(seqLen - 1 - ti)) * hy_stride;
use_time = ri == 0 ? ti : seqLen - ti;
}
if(in_n.at(cur_time) > 0)
{
if(ti == 0)
{
if(hx != nullptr)
{
miopen::GemmDescriptor gemm_desc = GemmDescriptor{false,
false,
true,
in_n.at(cur_time),
wei_len,
hy_h,
uni_stride,
uni_stride,
hy_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
1, // beta
xDesc[0].GetType()};
miopenStatus_t gemm_status =
CallGemm(handle,
gemm_desc,
hx,
hx_shift + ri * hy_n * hy_h,
w,
wei_shift + ri * wei_len * uni_stride,
reserveSpace,
static_cast<int>(offset) + ri * wei_len,
nullptr,
GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
else
{
if(ri == 1 && hx != nullptr && in_n.at(cur_time) > in_n.at(use_time))
{
miopen::GemmDescriptor gemm_desc =
GemmDescriptor{false,
false,
true,
(in_n.at(cur_time) - in_n.at(use_time)),
wei_len,
hy_h,
uni_stride,
uni_stride,
hy_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
1, // beta
xDesc[0].GetType()};
miopenStatus_t gemm_status =
CallGemm(handle,
gemm_desc,
hx,
hx_shift + ri * hy_n * hy_h + in_n.at(use_time) * hy_h,
w,
wei_shift + ri * wei_len * uni_stride,
reserveSpace,
static_cast<int>(offset) + ri * wei_len +
in_n.at(use_time) * hy_stride,
nullptr,
GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
profileRNNkernels(handle, 1, ctime);
}
if(in_n.at(use_time) > 0)
{
miopen::GemmDescriptor gemm_desc = GemmDescriptor{false,
false,
true,
in_n.at(use_time),
wei_len,
hy_h,
hy_stride,
uni_stride,
hy_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
1, // beta
xDesc[0].GetType()};
miopenStatus_t gemm_status =
CallGemm(handle,
gemm_desc,
reserveSpace,
pretime_shift + hid_off + ri * hy_h,
w,
wei_shift + ri * wei_len * uni_stride,
reserveSpace,
static_cast<int>(offset) + ri * wei_len,
nullptr,
GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
// update hidden status
sp_size[1] = in_n.at(cur_time);
if(rnnMode == miopenRNNRELU || rnnMode == miopenRNNTANH)
{
sp_size[2] = hy_h;
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
activDesc.Forward(handle,
&alpha,
sp_desc,
reserveSpace,
&beta,
sp_desc,
reserveSpace,
offset + ri * wei_len,
offset + ri * wei_len + nLayers * batch_n * hy_stride);
// Update time
profileRNNkernels(handle, 1, ctime);
}
else if(rnnMode == miopenLSTM)
{
if(algoMode == miopenRNNdefault)
{
LSTMForwardHiddenStateUpdate(handle,
wDesc.GetType(),
false,
ti == 0,
ri,
in_n.at(0),
in_n.at(cur_time),
in_n.at(use_time),
hy_h,
hy_stride,
wei_len,
wei_stride,
cx,
hx_shift + ri * hy_n * hy_h,
reserveSpace,
offset + ri * wei_len,
offset + hy_h + ri * wei_len,
offset + 2 * hy_h + ri * wei_len,
offset + 3 * hy_h + ri * wei_len,
offset + bi * wei_len + ri * hy_h,
pretime_shift + bi * wei_len + ri * hy_h,
(li * batch_n + cur_batch) * bi * hy_h +
ri * hy_h +
nLayers * batch_n * hy_stride,
offset + hid_off + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
continue;
}
// active gate i, f, o
sp_size[2] = hy_h * 3;
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
sigDesc.Forward(handle,
&alpha,
sp_desc,
reserveSpace,
&beta,
sp_desc,
reserveSpace,
offset + ri * wei_len,
offset + ri * wei_len + nLayers * batch_n * hy_stride);
// Update time
profileRNNkernels(handle, 1, ctime);
// active gate c
sp_size[2] = hy_h;
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
tanhDesc.Forward(handle,
&alpha,
sp_desc,
reserveSpace,
&beta,
sp_desc,
reserveSpace,
offset + 3 * hy_h + ri * wei_len,
offset + 3 * hy_h + ri * wei_len +
nLayers * batch_n * hy_stride);
// Update time
profileRNNkernels(handle, 1, ctime);
// update cell state
alpha0 = 1;
alpha1 = 1;
beta_t = 1;
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
reserveSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
sp_desc,
reserveSpace,
offset + ri * wei_len + nLayers * batch_n * hy_stride,
offset + 3 * hy_h + ri * wei_len + nLayers * batch_n * hy_stride,
offset + bi * wei_len + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
if(ti == 0)
{
if(cx != nullptr)
{
hx_size[1] = in_n.at(cur_time);
hx_size[2] = hy_h;
hx_desc = miopen::TensorDescriptor(
wDesc.GetType(), hx_size.data(), hx_stride.data(), 3);
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
reserveSpace,
&alpha1,
hx_desc,
cx,
&beta_t,
sp_desc,
reserveSpace,
offset + hy_h + ri * wei_len +
nLayers * batch_n * hy_stride,
hx_shift + ri * hy_n * hy_h,
offset + bi * wei_len + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
else
{
if(ri == 1 && cx != nullptr && in_n.at(cur_time) > in_n.at(use_time))
{
hx_size[1] = in_n.at(cur_time) - in_n.at(use_time);
hx_size[2] = hy_h;
hx_desc = miopen::TensorDescriptor(
wDesc.GetType(), hx_size.data(), hx_stride.data(), 3);
sp_size[1] = in_n.at(cur_time) - in_n.at(use_time);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
reserveSpace,
&alpha1,
hx_desc,
cx,
&beta_t,
sp_desc,
reserveSpace,
offset + hy_h + ri * wei_len +
in_n.at(use_time) * hy_stride +
nLayers * batch_n * hy_stride,
hx_shift + ri * hy_n * hy_h + in_n.at(use_time) * hy_h,
offset + bi * wei_len + ri * hy_h +
in_n.at(use_time) * hy_stride);
// Update time
profileRNNkernels(handle, 1, ctime);
sp_size[1] = in_n.at(cur_time);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
}
if(in_n.at(use_time) > 0)
{
if(in_n.at(use_time) != in_n.at(cur_time))
{
sp_size[1] = in_n.at(use_time);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
}
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
reserveSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
sp_desc,
reserveSpace,
offset + hy_h + ri * wei_len +
nLayers * batch_n * hy_stride,
pretime_shift + bi * wei_len + ri * hy_h,
offset + bi * wei_len + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
if(in_n.at(use_time) != in_n.at(cur_time))
{
sp_size[1] = in_n.at(cur_time);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
}
}
}
// active cell state
tanhDesc.Forward(handle,
&alpha,
sp_desc,
reserveSpace,
&beta,
sp_desc,
reserveSpace,
offset + bi * wei_len + ri * hy_h,
offset + bi * wei_len + ri * hy_h +
nLayers * batch_n * hy_stride);
// Update time
profileRNNkernels(handle, 1, ctime);
// update hidden state
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
reserveSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
sp_desc,
reserveSpace,
offset + 2 * hy_h + ri * wei_len + nLayers * batch_n * hy_stride,
offset + bi * wei_len + ri * hy_h + nLayers * batch_n * hy_stride,
offset + hid_off + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
}
else if(rnnMode == miopenGRU)
{
// active z, r gate
sp_size[2] = 2 * hy_h;
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
sigDesc.Forward(handle,
&alpha,
sp_desc,
reserveSpace,
&beta,
sp_desc,
reserveSpace,
offset + ri * wei_len,
offset + ri * wei_len + nLayers * batch_n * hy_stride);
// Update time
profileRNNkernels(handle, 1, ctime);
// calculate c gate
sp_size[2] = hy_h;
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
CopyTensor(handle,
sp_desc,
reserveSpace,
sp_desc,
reserveSpace,
static_cast<int>(offset) + 2 * hy_h + ri * wei_len,
static_cast<int>(offset) + hid_off + ri * hy_h +
static_cast<int>(nLayers) * batch_n * hy_stride);
// Update time
profileRNNkernels(handle, 1, ctime);
alpha0 = 1;
alpha1 = 1;
beta_t = 0;
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
reserveSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
sp_desc,
reserveSpace,
offset + hy_h + ri * wei_len + nLayers * batch_n * hy_stride,
offset + 2 * hy_h + ri * wei_len,
offset + 2 * hy_h + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
sp_desc,
reserveSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
sp_desc,
reserveSpace,
offset + 2 * hy_h + ri * wei_len,
offset + hid_off + ri * hy_h,
offset + 2 * hy_h + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
// active c gate
tanhDesc.Forward(handle,
&alpha,
sp_desc,
reserveSpace,
&beta,
sp_desc,
reserveSpace,
offset + 2 * hy_h + ri * wei_len,
offset + 2 * hy_h + ri * wei_len +
nLayers * batch_n * hy_stride);
// Update time
profileRNNkernels(handle, 1, ctime);
// calculate hidden state
alpha0 = -1;
alpha1 = 1;
beta_t = 0;
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
reserveSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
sp_desc,
reserveSpace,
offset + ri * wei_len + nLayers * batch_n * hy_stride,
offset + 2 * hy_h + ri * wei_len + nLayers * batch_n * hy_stride,
offset + hid_off + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
alpha0 = 1;
alpha1 = 1;
beta_t = 0;
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
sp_desc,
reserveSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
sp_desc,
reserveSpace,
offset + 2 * hy_h + ri * wei_len + nLayers * batch_n * hy_stride,
offset + hid_off + ri * hy_h,
offset + hid_off + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
alpha0 = 1;
alpha1 = 1;
beta_t = 1;
if(ti == 0)
{
if(hx != nullptr)
{
hx_size[1] = in_n.at(cur_time);
hx_size[2] = hy_h;
hx_desc = miopen::TensorDescriptor(
wDesc.GetType(), hx_size.data(), hx_stride.data(), 3);
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
reserveSpace,
&alpha1,
hx_desc,
hx,
&beta_t,
sp_desc,
reserveSpace,
offset + ri * wei_len + nLayers * batch_n * hy_stride,
hx_shift + ri * hy_n * hy_h,
offset + hid_off + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
else
{
if(ri == 1 && hx != nullptr && in_n.at(cur_time) > in_n.at(use_time))
{
hx_size[1] = in_n.at(cur_time) - in_n.at(use_time);
hx_size[2] = hy_h;
hx_desc = miopen::TensorDescriptor(
wDesc.GetType(), hx_size.data(), hx_stride.data(), 3);
sp_size[1] = in_n.at(cur_time) - in_n.at(use_time);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
reserveSpace,
&alpha1,
hx_desc,
hx,
&beta_t,
sp_desc,
reserveSpace,
offset + ri * wei_len + in_n.at(use_time) * hy_stride +
nLayers * batch_n * hy_stride,
hx_shift + ri * hy_n * hy_h + in_n.at(use_time) * hy_h,
offset + hid_off + ri * hy_h +
in_n.at(use_time) * hy_stride);
// Update time
profileRNNkernels(handle, 1, ctime);
sp_size[1] = in_n.at(cur_time);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
}
if(in_n.at(use_time) > 0)
{
if(in_n.at(use_time) != in_n.at(cur_time))
{
sp_size[1] = in_n.at(use_time);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
}
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
reserveSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
sp_desc,
reserveSpace,
offset + ri * wei_len + nLayers * batch_n * hy_stride,
pretime_shift + hid_off + ri * hy_h,
offset + hid_off + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
}
}
}
bacc += in_n.at(ti);
}
// update hy, cy
if(hy != nullptr || (rnnMode == miopenLSTM && cy != nullptr))
{
hx_size[2] = hy_h;
sp_size[2] = hy_h;
bacc = batch_n;
baccbi = 0;
for(int ti = seqLen - 1; ti >= 0; ti--)
{
bacc -= in_n.at(ti);
for(int ri = 0; ri < bi; ri++)
{
int cur_time = ri == 0 ? ti : seqLen - 1 - ti;
int cur_batch = ri == 0 ? bacc : baccbi;
int use_batch = 0;
if(ti < seqLen - 1)
{
int use_time = ri == 0 ? ti + 1 : seqLen - 2 - ti;
use_batch = in_n.at(use_time);
}
if(in_n.at(cur_time) > use_batch)
{
offset = hid_shift + cur_batch * hy_stride;
sp_size[1] = in_n.at(cur_time) - use_batch;
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
hx_size[1] = sp_size[1];
hx_desc = miopen::TensorDescriptor(
wDesc.GetType(), hx_size.data(), hx_stride.data(), 3);
if(hy != nullptr)
{
CopyTensor(handle,
sp_desc,
reserveSpace,
hx_desc,
hy,
static_cast<int>(offset) + hid_off + ri * hy_h +
use_batch * hy_stride,
hx_shift + ri * hy_n * hy_h + use_batch * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
}
if(rnnMode == miopenLSTM && cy != nullptr)
{
CopyTensor(handle,
sp_desc,
reserveSpace,
hx_desc,
cy,
static_cast<int>(offset) + bi * wei_len + ri * hy_h +
use_batch * hy_stride,
hx_shift + ri * hy_n * hy_h + use_batch * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
}
baccbi += in_n.at(seqLen - 1 - ti);
}
}
}
// output
prelayer_shift = (static_cast<int>(nLayers) - 1) * batch_n * hy_stride + hid_off;
sp_size[1] = batch_n;
sp_size[2] = hy_h * bi;
y_size[1] = batch_n;
y_size[2] = out_h;
y_desc = miopen::TensorDescriptor(wDesc.GetType(), y_size.data(), y_stride.data(), 3);
sp_desc = miopen::TensorDescriptor(wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
CopyTensor(handle, sp_desc, reserveSpace, y_desc, y, prelayer_shift, 0);
// Update time
profileRNNkernels(handle, 2, ctime);
#else
(void)bi_stride;
(void)alpha;
(void)offset;
(void)alpha0;
(void)alpha1;
(void)beta_t;
(void)hx;
(void)cx;
(void)wei_shift_bias;
MIOPEN_THROW("GEMM is not supported");
#endif
};
void RNNDescriptor::RNNBackwardData(Handle& handle,
const int seqLen,
c_array_view<const miopenTensorDescriptor_t> yDesc,
ConstData_t y,
c_array_view<const miopenTensorDescriptor_t> dyDesc,
ConstData_t dy,
const TensorDescriptor& dhyDesc,
ConstData_t dhy,
const TensorDescriptor& dcyDesc,
ConstData_t dcy,
const TensorDescriptor& wDesc,
ConstData_t w,
const TensorDescriptor& hxDesc,
ConstData_t hx,
const TensorDescriptor& cxDesc,
ConstData_t cx,
c_array_view<const miopenTensorDescriptor_t> dxDesc,
Data_t dx,
const TensorDescriptor& dhxDesc,
Data_t dhx,
const TensorDescriptor& dcxDesc,
Data_t dcx,
Data_t workSpace,
size_t workSpaceSize,
Data_t reserveSpace,
size_t reserveSpaceSize) const
{
// Suppress warning
(void)y;
(void)yDesc;
(void)hxDesc;
(void)cxDesc;
(void)dcxDesc;
(void)dcyDesc;
(void)dhyDesc;
(void)wDesc;
if(dx == nullptr || w == nullptr || dy == nullptr)
{
MIOPEN_THROW(miopenStatusBadParm);
}
if(dhyDesc.GetSize() != dcyDesc.GetSize() || dhyDesc.GetSize() != hxDesc.GetSize() ||
dhyDesc.GetSize() != cxDesc.GetSize() || dhyDesc.GetSize() != dhxDesc.GetSize() ||
dhyDesc.GetSize() != dcxDesc.GetSize())
{
MIOPEN_THROW(miopenStatusBadParm);
}
if(workSpaceSize < GetWorkspaceSize(handle, seqLen, dxDesc))
{
MIOPEN_THROW("Workspace is required");
}
if(reserveSpaceSize < GetReserveSize(handle, seqLen, dxDesc))
{
MIOPEN_THROW("Reservespace is required");
}
std::vector<int> in_n;
int in_h = dxDesc[0].GetLengths()[1];
int hy_d = dhxDesc.GetLengths()[0];
int hy_n = dhxDesc.GetLengths()[1];
int hy_h = dhxDesc.GetLengths()[2];
int out_h = dyDesc[0].GetLengths()[1];
if(in_h <= 0 || hy_h <= 0 || hy_n <= 0 || hy_d <= 0 || out_h <= 0 || seqLen <= 0)
{
MIOPEN_THROW(miopenStatusBadParm);
}
int batch_n = 0;
for(int i = 0; i < seqLen; i++)
{
int batchval, inputvec, batchvalout, outputvec;
std::tie(batchval, inputvec) = miopen::tien<2>(dxDesc[i].GetLengths());
std::tie(batchvalout, outputvec) = miopen::tien<2>(dyDesc[i].GetLengths());
if(batchval != batchvalout)
{
MIOPEN_THROW(miopenStatusBadParm);
}
if(i == 0)
{
if(batchval <= 0)
{
MIOPEN_THROW(miopenStatusBadParm, "Input batch is ZERO!");
}
}
else
{
if(batchval > in_n.back() || batchval < 0)
{
MIOPEN_THROW(miopenStatusBadParm,
"Incorrect input batch size at time " + std::to_string(i) +
"! Batch size must not ascend!");
}
}
in_n.push_back(batchval);
batch_n += dxDesc[i].GetLengths()[0];
}
int bi = dirMode != 0u ? 2 : 1;
if(out_h != (bi * hy_h))
{
MIOPEN_THROW(miopenStatusBadParm, "Output size doesn't match hidden state size!");
}
float ctime = 0.;
int in_stride = in_h;
int hy_stride = hy_h * bi * static_cast<int>(workspaceScale);
int out_stride = out_h;
int wei_stride = hy_h * bi * static_cast<int>(nHiddenTensorsPerLayer);
int uni_stride = hy_h;
int bi_stride = hy_h * bi;
if(inputMode == miopenRNNskip)
{
if(in_h != hy_h)
{
MIOPEN_THROW(miopenStatusBadParm,
"The input tensor size must equal to the hidden "
"state size of the network in SKIP_INPUT mode!");
}
in_h = 0;
}
size_t offset;
float alpha0, alpha1, beta_t;
float alpha = 1, beta = 0;
std::vector<int> sp_size(3, 1), sp_stride(3, 1), x_size(3, 1), x_stride(3, 1), y_size(3, 1),
y_stride(3, 1), hx_size(3, 1), hx_stride(3, 1);
miopen::TensorDescriptor sp_desc, x_desc, y_desc, hx_desc;
sp_size[2] = workSpaceSize / GetTypeSize(wDesc.GetType());
sp_stride[0] = sp_size[2];
sp_stride[1] = sp_size[2];
sp_desc = miopen::TensorDescriptor(wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
SetTensor(handle, sp_desc, workSpace, &beta);
// Update time
profileRNNkernels(handle, 0, ctime);
sp_stride[0] = batch_n * hy_stride;
sp_stride[1] = hy_stride;
sp_size[2] = 1;
x_stride[0] = batch_n * in_stride;
x_stride[1] = in_stride;
y_stride[0] = batch_n * out_stride;
y_stride[1] = out_stride;
if(dhx != nullptr || (rnnMode == miopenLSTM && dcx != nullptr))
{
hx_size[2] = hy_d * hy_n * hy_h;
hx_stride[0] = hx_size[2];
hx_stride[1] = hx_size[2];
hx_desc = miopen::TensorDescriptor(wDesc.GetType(), hx_size.data(), hx_stride.data(), 3);
if(dhx != nullptr)
{
SetTensor(handle, hx_desc, dhx, &beta);
// Update time
profileRNNkernels(handle, 1, ctime);
}
if(rnnMode == miopenLSTM && dcx != nullptr)
{
SetTensor(handle, hx_desc, dcx, &beta);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
hx_stride[0] = in_n.at(0) * uni_stride;
hx_stride[1] = uni_stride;
#if MIOPEN_USE_GEMM
int prelayer_shift, pretime_shift, cur_time, cur_batch;
int wei_len = 0;
int wei_len_t = 0;
int dhd_off = 0;
int use_time = 0;
int pre_batch = 0;
int use_time2 = 0;
int pre_batch2 = 0;
switch(rnnMode)
{
case miopenRNNRELU:
case miopenRNNTANH:
// printf("run rnn gpu bwd data \n");
wei_len = hy_h;
wei_len_t = hy_h;
dhd_off = 0;
break;
case miopenLSTM:
// printf("run lstm gpu bwd data \n");
wei_len = hy_h * 4;
wei_len_t = hy_h * 4;
dhd_off = bi * hy_h * 5;
break;
case miopenGRU:
// printf("run gru gpu bwd data \n");
wei_len = hy_h * 3;
wei_len_t = hy_h * 2;
dhd_off = bi * hy_h * 3;
break;
}
ActivationDescriptor tanhDesc, sigDesc, activDesc;
sigDesc = {miopenActivationLOGISTIC, 1, 0, 1};
tanhDesc = {miopenActivationTANH, 1, 1, 1};
if(rnnMode == miopenRNNRELU)
{
activDesc = {miopenActivationRELU, 1, 0, 1};
}
else if(rnnMode == miopenRNNTANH)
{
activDesc = {miopenActivationTANH, 1, 1, 1};
}
for(int li = static_cast<int>(nLayers) - 1; li >= 0; li--)
{
int wei_shift = (in_h + hy_h) * wei_stride + li * (bi * hy_h + hy_h) * wei_stride;
int hid_shift = li * batch_n * hy_stride;
int hx_shift = li * hy_n * bi_stride;
int weitime_shift = in_h * wei_stride + li * (bi * hy_h + hy_h) * wei_stride;
// feedback from output
if(li == nLayers - 1)
{
y_size[1] = batch_n;
y_size[2] = out_h;
sp_size[1] = batch_n;
sp_size[2] = hy_h * bi;
y_desc = miopen::TensorDescriptor(wDesc.GetType(), y_size.data(), y_stride.data(), 3);
sp_desc =
miopen::TensorDescriptor(wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
CopyTensor(handle, y_desc, dy, sp_desc, workSpace, 0, hid_shift + dhd_off);
// Update time
profileRNNkernels(handle, 1, ctime); // start timing
}
else
{
prelayer_shift = (li + 1) * batch_n * hy_stride;
miopen::GemmDescriptor gemm_desc = GemmDescriptor{false,
false,
false,
batch_n,
hy_h * bi,
wei_len * bi,
hy_stride,
bi_stride,
hy_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
1, // beta
yDesc[0].GetType()};
miopenStatus_t gemm_status = CallGemm(handle,
gemm_desc,
workSpace,
prelayer_shift,
w,
wei_shift,
workSpace,
hid_shift + dhd_off,
nullptr,
GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
profileRNNkernels(handle, 1, ctime);
if(!float_equal(miopen::deref(dropoutDesc).dropout, 0))
{
std::vector<int> drop_size(2), drop_in_str(2, 1);
drop_size[0] = batch_n;
drop_size[1] = hy_h * bi;
drop_in_str[0] = hy_stride;
auto drop_in_desc = miopen::TensorDescriptor(
wDesc.GetType(), drop_size.data(), drop_in_str.data(), 2);
size_t drop_rsv_size = drop_in_desc.GetElementSize();
size_t drop_rsv_start =
algoMode == miopenRNNdefault && rnnMode == miopenLSTM
? nLayers * batch_n * hy_stride + nLayers * batch_n * hy_h * bi
: 2 * nLayers * batch_n * hy_stride;
size_t drop_rsv_offset = (drop_rsv_start + (nLayers - 1) * batch_n * hy_h * bi) *
(wDesc.GetType() == miopenFloat ? 4 : 2) +
li * drop_rsv_size;
miopen::deref(dropoutDesc)
.DropoutBackward(handle,
drop_in_desc,
drop_in_desc,
workSpace,
drop_in_desc,
workSpace,
reserveSpace,
drop_rsv_size,
hid_shift + dhd_off,
hid_shift + dhd_off,
drop_rsv_offset);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
// from hidden state
int bacc = batch_n;
int baccbi = 0;
for(int ti = seqLen - 1; ti >= 0; ti--)
{
bacc -= in_n.at(ti);
// from post state
for(int ri = 0; ri < bi; ri++)
{
cur_time = ri == 0 ? ti : seqLen - 1 - ti;
cur_batch = ri == 0 ? bacc : baccbi;
offset = hid_shift + cur_batch * hy_stride;
if(ti < seqLen - 1)
{
use_time = ri == 0 ? ti + 1 : seqLen - 1 - ti;
pre_batch = ri == 0 ? bacc + in_n.at(ti) : baccbi - in_n.at(seqLen - 2 - ti);
}
if(ti > 0)
{
use_time2 = ri == 0 ? ti : seqLen - ti;
pre_batch2 =
ri == 0 ? bacc - in_n.at(ti - 1) : baccbi + in_n.at(seqLen - 1 - ti);
}
if(in_n.at(cur_time) > 0)
{
if(ti == seqLen - 1)
{
if(dhy != nullptr)
{
alpha0 = 1;
alpha1 = 1;
beta_t = 0;
hx_size[1] = in_n.at(cur_time);
hx_size[2] = hy_h;
sp_size[1] = in_n.at(cur_time);
sp_size[2] = hy_h;
hx_desc = miopen::TensorDescriptor(
wDesc.GetType(), hx_size.data(), hx_stride.data(), 3);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
hx_desc,
dhy,
&alpha1,
sp_desc,
workSpace,
&beta_t,
sp_desc,
workSpace,
hx_shift + ri * hy_n * hy_h,
offset + dhd_off + ri * hy_h,
offset + dhd_off + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
else
{
if(ri == 0 && dhy != nullptr && in_n.at(cur_time) > in_n.at(use_time))
{
alpha0 = 1;
alpha1 = 1;
beta_t = 0;
hx_size[1] = in_n.at(cur_time) - in_n.at(use_time);
hx_size[2] = hy_h;
sp_size[1] = in_n.at(cur_time) - in_n.at(use_time);
sp_size[2] = hy_h;
hx_desc = miopen::TensorDescriptor(
wDesc.GetType(), hx_size.data(), hx_stride.data(), 3);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
hx_desc,
dhy,
&alpha1,
sp_desc,
workSpace,
&beta_t,
sp_desc,
workSpace,
hx_shift + ri * hy_n * hy_h + in_n.at(use_time) * hy_h,
offset + dhd_off + ri * hy_h + in_n.at(use_time) * hy_stride,
offset + dhd_off + ri * hy_h + in_n.at(use_time) * hy_stride);
// Update time
profileRNNkernels(handle, 1, ctime);
}
pretime_shift =
li * batch_n * hy_stride + pre_batch * hy_stride + ri * wei_len;
if(in_n.at(use_time) > 0)
{
if(rnnMode == miopenGRU)
{
sp_size[1] = in_n.at(use_time);
sp_size[2] = hy_h;
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
alpha0 = 1;
alpha1 = 1;
beta_t = 1;
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
sp_desc,
workSpace,
pretime_shift - ri * 2 * hy_h + dhd_off,
pretime_shift + nLayers * batch_n * hy_stride,
offset + dhd_off + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
CopyTensor(handle,
sp_desc,
workSpace,
sp_desc,
workSpace,
pretime_shift + 2 * hy_h,
static_cast<int>(offset) + ri * wei_len + 2 * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
CopyTensor(handle,
sp_desc,
reserveSpace,
sp_desc,
workSpace,
pretime_shift - ri * 2 * hy_h + dhd_off +
static_cast<int>(nLayers) * batch_n * hy_stride,
pretime_shift + 2 * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
}
miopen::GemmDescriptor gemm_desc = GemmDescriptor{false,
false,
false,
in_n.at(use_time),
hy_h,
wei_len,
hy_stride,
uni_stride,
hy_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
1, // beta
yDesc[0].GetType()};
miopenStatus_t gemm_status =
CallGemm(handle,
gemm_desc,
workSpace,
pretime_shift,
w,
weitime_shift + ri * wei_len * uni_stride,
workSpace,
static_cast<int>(offset) + dhd_off + ri * hy_h,
nullptr,
GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
profileRNNkernels(handle, 1, ctime);
if(rnnMode == miopenGRU)
{
CopyTensor(handle,
sp_desc,
workSpace,
sp_desc,
workSpace,
static_cast<int>(offset) + ri * wei_len + 2 * hy_h,
pretime_shift + 2 * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
}
// update hidden status
sp_size[1] = in_n.at(cur_time);
sp_size[2] = hy_h;
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
if(rnnMode == miopenRNNRELU || rnnMode == miopenRNNTANH)
{
// activation
activDesc.Backward(handle,
&alpha,
sp_desc,
reserveSpace,
sp_desc,
workSpace,
sp_desc,
reserveSpace,
&beta,
sp_desc,
workSpace,
offset + ri * wei_len + nLayers * batch_n * hy_stride,
offset + ri * wei_len,
offset + ri * wei_len,
offset + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
}
else if(rnnMode == miopenLSTM)
{
if(algoMode == miopenRNNdefault)
{
LSTMBackwardHiddenStateUpdate(
handle,
wDesc.GetType(),
ti == 0,
ti == seqLen - 1,
ri,
in_n.at(0),
in_n.at(cur_time),
in_n.at(use_time),
in_n.at(use_time2),
hy_h,
hy_stride,
wei_len,
wei_stride,
cx,
hx_shift + ri * hy_n * hy_h,
reserveSpace,
offset + ri * wei_len,
offset + hy_h + ri * wei_len,
offset + 2 * hy_h + ri * wei_len,
offset + 3 * hy_h + ri * wei_len,
(li * batch_n + cur_batch) * bi * hy_h + ri * hy_h +
nLayers * batch_n * hy_stride,
li * batch_n * hy_stride + pre_batch2 * hy_stride + bi * wei_len +
ri * hy_h,
dcy,
hx_shift + ri * hy_n * hy_h,
workSpace,
offset + ri * wei_len,
offset + hy_h + ri * wei_len,
offset + 2 * hy_h + ri * wei_len,
offset + 3 * hy_h + ri * wei_len,
offset + bi * wei_len + ri * hy_h,
li * batch_n * hy_stride + pre_batch * hy_stride + bi * wei_len +
ri * hy_h,
offset + dhd_off + ri * hy_h,
li * batch_n * hy_stride + pre_batch * hy_stride + hy_h +
ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
continue;
}
alpha0 = 1;
alpha1 = 1;
beta_t = 0;
// update cell state
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
sp_desc,
workSpace,
offset + dhd_off + ri * hy_h,
offset + 2 * hy_h + ri * wei_len + nLayers * batch_n * hy_stride,
offset + bi * wei_len + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
tanhDesc.Backward(handle,
&alpha,
sp_desc,
reserveSpace,
sp_desc,
workSpace,
sp_desc,
reserveSpace,
&beta,
sp_desc,
workSpace,
offset + bi * wei_len + ri * hy_h +
nLayers * batch_n * hy_stride,
offset + bi * wei_len + ri * hy_h,
offset + bi * wei_len + ri * hy_h,
offset + bi * wei_len + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
if(ti == seqLen - 1)
{
if(dcy != nullptr)
{
hx_size[1] = in_n.at(cur_time);
hx_size[2] = hy_h;
hx_desc = miopen::TensorDescriptor(
wDesc.GetType(), hx_size.data(), hx_stride.data(), 3);
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
hx_desc,
dcy,
&alpha1,
sp_desc,
workSpace,
&beta_t,
sp_desc,
workSpace,
hx_shift + ri * hy_n * hy_h,
offset + bi * wei_len + ri * hy_h,
offset + bi * wei_len + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
else
{
if(ri == 0 && dcy != nullptr && in_n.at(cur_time) > in_n.at(use_time))
{
hx_size[1] = in_n.at(cur_time) - in_n.at(use_time);
hx_size[2] = hy_h;
sp_size[1] = in_n.at(cur_time) - in_n.at(use_time);
sp_size[2] = hy_h;
hx_desc = miopen::TensorDescriptor(
wDesc.GetType(), hx_size.data(), hx_stride.data(), 3);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
hx_desc,
dcy,
&alpha1,
sp_desc,
workSpace,
&beta_t,
sp_desc,
workSpace,
hx_shift + ri * hy_n * hy_h + in_n.at(use_time) * hy_h,
offset + bi * wei_len + ri * hy_h +
in_n.at(use_time) * hy_stride,
offset + bi * wei_len + ri * hy_h +
in_n.at(use_time) * hy_stride);
// Update time
profileRNNkernels(handle, 1, ctime);
sp_size[1] = in_n.at(cur_time);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
}
pretime_shift = li * batch_n * hy_stride + pre_batch * hy_stride;
alpha0 = 1;
alpha1 = 1;
beta_t = 1;
if(in_n.at(cur_time) != in_n.at(use_time))
{
sp_size[1] = in_n.at(use_time);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
}
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
sp_desc,
workSpace,
pretime_shift + bi * wei_len + ri * hy_h,
pretime_shift + hy_h + ri * wei_len +
nLayers * batch_n * hy_stride,
offset + bi * wei_len + ri * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
if(in_n.at(cur_time) != in_n.at(use_time))
{
sp_size[1] = in_n.at(cur_time);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
}
}
// update forget gate
alpha0 = 1;
alpha1 = 1;
beta_t = 0;
if(ti == 0)
{
if(cx != nullptr)
{
hx_size[1] = in_n.at(cur_time);
hx_size[2] = hy_h;
hx_desc = miopen::TensorDescriptor(
wDesc.GetType(), hx_size.data(), hx_stride.data(), 3);
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
hx_desc,
cx,
&beta_t,
sp_desc,
workSpace,
offset + bi * wei_len + ri * hy_h,
hx_shift + ri * hy_n * hy_h,
offset + hy_h + ri * wei_len);
}
}
else
{
if(ri == 1 && cx != nullptr && in_n.at(cur_time) > in_n.at(use_time2))
{
hx_size[1] = in_n.at(cur_time) - in_n.at(use_time2);
hx_size[2] = hy_h;
sp_size[1] = in_n.at(cur_time) - in_n.at(use_time2);
sp_size[2] = hy_h;
hx_desc = miopen::TensorDescriptor(
wDesc.GetType(), hx_size.data(), hx_stride.data(), 3);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
hx_desc,
cx,
&beta_t,
sp_desc,
workSpace,
offset + bi * wei_len + ri * hy_h +
in_n.at(use_time2) * hy_stride,
hx_shift + ri * hy_n * hy_h + in_n.at(use_time2) * hy_h,
offset + hy_h + ri * wei_len +
in_n.at(use_time2) * hy_stride);
sp_size[1] = in_n.at(cur_time);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
}
if(in_n.at(use_time2) > 0)
{
pretime_shift = li * batch_n * hy_stride + pre_batch2 * hy_stride;
if(in_n.at(cur_time) != in_n.at(use_time2))
{
sp_size[1] = in_n.at(use_time2);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
}
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
sp_desc,
workSpace,
offset + bi * wei_len + ri * hy_h,
pretime_shift + bi * wei_len + ri * hy_h,
offset + hy_h + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
if(in_n.at(cur_time) != in_n.at(use_time2))
{
sp_size[1] = in_n.at(cur_time);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
}
}
}
// update input gate
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
sp_desc,
workSpace,
offset + bi * wei_len + ri * hy_h,
offset + 3 * hy_h + ri * wei_len + nLayers * batch_n * hy_stride,
offset + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
// update output gate
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
sp_desc,
workSpace,
offset + dhd_off + ri * hy_h,
offset + bi * wei_len + ri * hy_h + nLayers * batch_n * hy_stride,
offset + 2 * hy_h + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
// update c gate
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
sp_desc,
workSpace,
offset + bi * wei_len + ri * hy_h,
offset + ri * wei_len + nLayers * batch_n * hy_stride,
offset + 3 * hy_h + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
tanhDesc.Backward(handle,
&alpha,
sp_desc,
reserveSpace,
sp_desc,
workSpace,
sp_desc,
reserveSpace,
&beta,
sp_desc,
workSpace,
offset + 3 * hy_h + ri * wei_len +
nLayers * batch_n * hy_stride,
offset + 3 * hy_h + ri * wei_len,
offset + 3 * hy_h + ri * wei_len,
offset + 3 * hy_h + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
sp_size[2] = 3 * hy_h;
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
sigDesc.Backward(handle,
&alpha,
sp_desc,
reserveSpace,
sp_desc,
workSpace,
sp_desc,
reserveSpace,
&beta,
sp_desc,
workSpace,
offset + ri * wei_len + nLayers * batch_n * hy_stride,
offset + ri * wei_len,
offset + ri * wei_len,
offset + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
}
else if(rnnMode == miopenGRU)
{
// c gate
alpha0 = 1;
alpha1 = -1;
beta_t = 0;
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
sp_desc,
workSpace,
offset + dhd_off + ri * hy_h,
offset + ri * wei_len + nLayers * batch_n * hy_stride,
offset + 2 * hy_h + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
alpha0 = 1;
alpha1 = 1;
beta_t = 0;
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
workSpace,
&beta_t,
sp_desc,
workSpace,
offset + dhd_off + ri * hy_h,
offset + 2 * hy_h + ri * wei_len,
offset + 2 * hy_h + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
tanhDesc.Backward(handle,
&alpha,
sp_desc,
reserveSpace,
sp_desc,
workSpace,
sp_desc,
reserveSpace,
&beta,
sp_desc,
workSpace,
offset + 2 * hy_h + ri * wei_len +
nLayers * batch_n * hy_stride,
offset + 2 * hy_h + ri * wei_len,
offset + 2 * hy_h + ri * wei_len,
offset + 2 * hy_h + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
// r gate
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
sp_desc,
workSpace,
offset + 2 * hy_h + ri * wei_len,
offset + dhd_off + ri * hy_h + nLayers * batch_n * hy_stride,
offset + hy_h + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
sp_desc,
reserveSpace,
offset + 2 * hy_h + ri * wei_len,
offset + hy_h + ri * wei_len + nLayers * batch_n * hy_stride,
offset + dhd_off + ri * hy_h + nLayers * batch_n * hy_stride);
// Update time
profileRNNkernels(handle, 1, ctime);
// z gate
if(ti == 0)
{
if(hx != nullptr)
{
hx_size[1] = in_n.at(cur_time);
hx_size[2] = hy_h;
hx_desc = miopen::TensorDescriptor(
wDesc.GetType(), hx_size.data(), hx_stride.data(), 3);
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
hx_desc,
hx,
&alpha1,
sp_desc,
workSpace,
&beta_t,
sp_desc,
workSpace,
hx_shift + ri * hy_n * hy_h,
offset + dhd_off + ri * hy_h,
offset + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
else
{
if(ri == 1 && hx != nullptr && in_n.at(cur_time) > in_n.at(use_time2))
{
hx_size[1] = in_n.at(cur_time) - in_n.at(use_time2);
hx_size[2] = hy_h;
sp_size[1] = in_n.at(cur_time) - in_n.at(use_time2);
hx_desc = miopen::TensorDescriptor(
wDesc.GetType(), hx_size.data(), hx_stride.data(), 3);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
hx_desc,
hx,
&alpha1,
sp_desc,
workSpace,
&beta_t,
sp_desc,
workSpace,
hx_shift + ri * hy_n * hy_h + in_n.at(use_time2) * hy_h,
offset + dhd_off + ri * hy_h +
in_n.at(use_time2) * hy_stride,
offset + ri * wei_len + in_n.at(use_time2) * hy_stride);
// Update time
profileRNNkernels(handle, 1, ctime);
sp_size[1] = in_n.at(cur_time);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
}
if(in_n.at(use_time2) > 0)
{
if(in_n.at(use_time2) != in_n.at(cur_time))
{
sp_size[1] = in_n.at(use_time2);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
}
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
reserveSpace,
&alpha1,
sp_desc,
workSpace,
&beta_t,
sp_desc,
workSpace,
hid_shift + pre_batch2 * hy_stride + dhd_off + ri * hy_h,
offset + dhd_off + ri * hy_h,
offset + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
if(in_n.at(use_time2) != in_n.at(cur_time))
{
sp_size[1] = in_n.at(cur_time);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
}
}
}
alpha0 = -1;
alpha1 = 1;
beta_t = 1;
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
reserveSpace,
&alpha1,
sp_desc,
workSpace,
&beta_t,
sp_desc,
workSpace,
offset + 2 * hy_h + ri * wei_len + nLayers * batch_n * hy_stride,
offset + dhd_off + ri * hy_h,
offset + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
sp_size[2] = 2 * hy_h;
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
sigDesc.Backward(handle,
&alpha,
sp_desc,
reserveSpace,
sp_desc,
workSpace,
sp_desc,
reserveSpace,
&beta,
sp_desc,
workSpace,
offset + ri * wei_len + nLayers * batch_n * hy_stride,
offset + ri * wei_len,
offset + ri * wei_len,
offset + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
}
baccbi += in_n.at(seqLen - 1 - ti);
}
// dcx, dhx
if(dhx != nullptr || (rnnMode == miopenLSTM && dcx != nullptr))
{
hx_size[2] = hy_h;
sp_size[2] = hy_h;
bacc = 0;
baccbi = batch_n;
for(int ti = 0; ti < seqLen; ti++)
{
baccbi -= in_n.at(seqLen - 1 - ti);
for(int ri = 0; ri < bi; ri++)
{
cur_time = ri == 0 ? ti : seqLen - 1 - ti;
cur_batch = ri == 0 ? bacc : baccbi;
use_time = 0;
int use_batch = 0;
if(ti > 0)
{
use_time = ri == 0 ? ti - 1 : seqLen - ti;
use_batch = in_n.at(use_time);
}
if(in_n.at(cur_time) > use_batch)
{
pretime_shift = li * batch_n * hy_stride + cur_batch * hy_stride;
if(rnnMode == miopenLSTM || rnnMode == miopenGRU)
{
sp_size[1] = in_n.at(cur_time) - use_batch;
hx_size[1] = in_n.at(cur_time) - use_batch;
hx_desc = miopen::TensorDescriptor(
wDesc.GetType(), hx_size.data(), hx_stride.data(), 3);
sp_desc = miopen::TensorDescriptor(
wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
}
if(dhx != nullptr)
{
if(rnnMode == miopenGRU)
{
alpha0 = 1;
alpha1 = 1;
beta_t = 0;
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
sp_desc,
reserveSpace,
pretime_shift + 2 * hy_h + ri * wei_len +
use_batch * hy_stride,
pretime_shift + hy_h + ri * wei_len +
use_batch * hy_stride + nLayers * batch_n * hy_stride,
pretime_shift + dhd_off + ri * hy_h +
use_batch * hy_stride + nLayers * batch_n * hy_stride);
// Update time
profileRNNkernels(handle, 1, ctime);
miopen::GemmDescriptor gemm_desc =
GemmDescriptor{false,
false,
false,
(in_n.at(cur_time) - use_batch),
hy_h,
hy_h,
hy_stride,
uni_stride,
uni_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
0, // beta
yDesc[0].GetType()};
miopenStatus_t gemm_status = CallGemm(
handle,
gemm_desc,
reserveSpace,
pretime_shift + dhd_off + ri * hy_h + use_batch * hy_stride +
static_cast<int>(nLayers) * batch_n * hy_stride,
w,
weitime_shift + 2 * hy_h * uni_stride +
ri * wei_len * uni_stride,
dhx,
hx_shift + ri * hy_n * hy_h + use_batch * hy_h,
nullptr,
GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
profileRNNkernels(handle, 1, ctime);
beta_t = 1;
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
hx_desc,
dhx,
pretime_shift + dhd_off + ri * hy_h +
use_batch * hy_stride,
pretime_shift + ri * wei_len + use_batch * hy_stride +
nLayers * batch_n * hy_stride,
hx_shift + ri * hy_n * hy_h + use_batch * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
}
miopen::GemmDescriptor gemm_desc =
GemmDescriptor{false,
false,
false,
(in_n.at(cur_time) - use_batch),
hy_h,
wei_len_t,
hy_stride,
uni_stride,
uni_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
1, // beta
yDesc[0].GetType()};
miopenStatus_t gemm_status =
CallGemm(handle,
gemm_desc,
workSpace,
pretime_shift + ri * wei_len + use_batch * hy_stride,
w,
weitime_shift + ri * wei_len * uni_stride,
dhx,
hx_shift + ri * hy_n * hy_h + use_batch * hy_h,
nullptr,
GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
profileRNNkernels(handle, 1, ctime);
}
if(rnnMode == miopenLSTM && dcx != nullptr)
{
alpha0 = 1;
alpha1 = 1;
beta_t = 1;
if(algoMode == miopenRNNdefault)
{
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
hx_desc,
dcx,
pretime_shift + bi * wei_len + ri * hy_h +
use_batch * hy_stride,
pretime_shift + hy_h + ri * wei_len +
use_batch * hy_stride,
hx_shift + ri * hy_n * hy_h + use_batch * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
continue;
}
OpTensor(handle,
miopenTensorOpMul,
&alpha0,
sp_desc,
workSpace,
&alpha1,
sp_desc,
reserveSpace,
&beta_t,
hx_desc,
dcx,
pretime_shift + bi * wei_len + ri * hy_h +
use_batch * hy_stride,
pretime_shift + hy_h + ri * wei_len + use_batch * hy_stride +
nLayers * batch_n * hy_stride,
hx_shift + ri * hy_n * hy_h + use_batch * hy_h);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
}
bacc += in_n.at(ti);
}
}
}
// dinput
if(inputMode == miopenRNNskip)
{
sp_size[1] = batch_n;
sp_size[2] = hy_h;
x_size[1] = batch_n;
x_size[2] = hy_h;
x_desc = miopen::TensorDescriptor(wDesc.GetType(), x_size.data(), x_stride.data(), 3);
sp_desc = miopen::TensorDescriptor(wDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
alpha0 = 1;
alpha1 = 1;
beta_t = 0;
for(int gi = 0; gi < nHiddenTensorsPerLayer * bi; gi++)
{
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
sp_desc,
workSpace,
&alpha1,
x_desc,
dx,
&beta_t,
x_desc,
dx,
gi * hy_h,
0,
0);
// Update time
profileRNNkernels(handle, (gi == nHiddenTensorsPerLayer * bi - 1) ? 2 : 1, ctime);
}
}
else
{
miopen::GemmDescriptor gemm_desc = GemmDescriptor{false,
false,
false,
batch_n,
in_h,
wei_len * bi,
hy_stride,
in_stride,
in_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
0, // beta
yDesc[0].GetType()};
miopenStatus_t gemm_status = CallGemm(
handle, gemm_desc, workSpace, 0, w, 0, dx, 0, nullptr, GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
profileRNNkernels(handle, 2, ctime);
}
#else
(void)wei_stride;
(void)bi_stride;
(void)alpha;
(void)offset;
(void)alpha0;
(void)alpha1;
(void)beta_t;
(void)hx;
(void)cx;
(void)dhy;
(void)dcy;
(void)reserveSpace;
(void)in_h;
MIOPEN_THROW("GEMM is not supported");
#endif
};
void RNNDescriptor::RNNBackwardWeights(Handle& handle,
const int seqLen,
c_array_view<const miopenTensorDescriptor_t> xDesc,
ConstData_t x,
const TensorDescriptor& hxDesc,
ConstData_t hx,
c_array_view<const miopenTensorDescriptor_t> dyDesc,
ConstData_t dy,
const TensorDescriptor& dwDesc,
Data_t dw,
Data_t workSpace,
size_t workSpaceSize,
ConstData_t reserveSpace,
size_t reserveSpaceSize) const
{
if(x == nullptr || dw == nullptr || dy == nullptr)
{
MIOPEN_THROW(miopenStatusBadParm);
}
if(workSpaceSize < GetWorkspaceSize(handle, seqLen, xDesc))
{
MIOPEN_THROW("Workspace is required");
}
if(reserveSpaceSize < GetReserveSize(handle, seqLen, xDesc))
{
MIOPEN_THROW("Reservespace is required");
}
std::string network_config;
std::vector<int> in_n;
int in_h = xDesc[0].GetLengths()[1];
int hy_d = hxDesc.GetLengths()[0];
int hy_n = hxDesc.GetLengths()[1];
int hy_h = hxDesc.GetLengths()[2];
int out_h = dyDesc[0].GetLengths()[1];
if(in_h <= 0 || hy_h <= 0 || hy_n <= 0 || hy_d <= 0 || out_h <= 0 || seqLen <= 0)
{
MIOPEN_THROW(miopenStatusBadParm);
}
int batch_n = 0;
for(int i = 0; i < seqLen; i++)
{
int batchval, inputvec, batchvalout, outputvec;
std::tie(batchval, inputvec) = miopen::tien<2>(xDesc[i].GetLengths());
std::tie(batchvalout, outputvec) = miopen::tien<2>(dyDesc[i].GetLengths());
if(batchval != batchvalout)
{
MIOPEN_THROW(miopenStatusBadParm);
}
if(i == 0)
{
if(batchval <= 0)
{
MIOPEN_THROW(miopenStatusBadParm, "Input batch is ZERO!");
}
}
else
{
if(batchval > in_n.back() || batchval < 0)
{
MIOPEN_THROW(miopenStatusBadParm,
"Incorrect input batch size at time " + std::to_string(i) +
"! Batch size must not ascend!");
}
}
in_n.push_back(batchval);
batch_n += xDesc[i].GetLengths()[0];
}
int bi = dirMode != 0u ? 2 : 1;
if(out_h != (bi * hy_h))
{
MIOPEN_THROW(miopenStatusBadParm, "Output size doesn't match hidden state size!");
}
float ctime = 0.;
int in_stride = in_h;
int hy_stride = hy_h * bi * static_cast<int>(workspaceScale);
int wei_stride = hy_h * bi * static_cast<int>(nHiddenTensorsPerLayer);
int uni_stride = hy_h;
int bi_stride = hy_h * bi;
if(inputMode == miopenRNNskip)
{
if(in_h != hy_h)
{
MIOPEN_THROW(miopenStatusBadParm,
"The input tensor size must equal to the hidden "
"state size of the network in SKIP_INPUT mode!");
}
in_h = 0;
}
size_t wei_shift_bias = (in_h + hy_h + (bi * hy_h + hy_h) * (nLayers - 1)) * wei_stride;
float alpha0, alpha1, beta_t = 0;
std::vector<int> sp_size(3, 1), sp_stride(3, 1), w_size(3, 1), w_stride(3, 1);
miopen::TensorDescriptor sp_desc, w_desc;
sp_stride[0] = batch_n * hy_stride;
sp_stride[1] = hy_stride;
w_size[2] = dwDesc.GetElementSize();
w_stride[0] = w_size[2];
w_stride[1] = w_size[2];
w_desc = miopen::TensorDescriptor(dwDesc.GetType(), w_size.data(), w_stride.data(), 3);
SetTensor(handle, w_desc, dw, &beta_t);
// Update time
profileRNNkernels(handle, 0, ctime);
w_stride[0] = wei_stride;
w_stride[1] = wei_stride;
w_size[2] = 1;
#if MIOPEN_USE_GEMM
int wei_len = 0;
int hid_off = 0;
int use_time = 0;
int pre_batch = 0;
switch(rnnMode)
{
case miopenRNNRELU:
case miopenRNNTANH:
// printf("run rnn gpu bwd weights \n");
wei_len = hy_h;
hid_off = static_cast<int>(nLayers) * batch_n * hy_stride;
break;
case miopenLSTM:
// printf("run lstm gpu bwd weights \n");
wei_len = hy_h * 4;
hid_off = bi * hy_h * 5;
break;
case miopenGRU:
// printf("run gru gpu bwd weights \n");
wei_len = hy_h * 3;
hid_off = bi * hy_h * 3;
break;
}
for(int li = 0; li < nLayers; li++)
{
int hid_shift = li * batch_n * hy_stride;
int wei_shift = (in_h + hy_h) * wei_stride + (li - 1) * (bi * hy_h + hy_h) * wei_stride;
// between layers
if(li == 0)
{
if(inputMode == miopenRNNlinear)
{
miopen::GemmDescriptor gemm_desc = GemmDescriptor{false,
true,
false,
wei_len * bi,
in_h,
batch_n,
hy_stride,
in_stride,
in_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
1, // beta
xDesc[0].GetType()};
miopenStatus_t gemm_status = CallGemm(handle,
gemm_desc,
workSpace,
0,
x,
0,
dw,
0,
nullptr,
GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
else
{
bool use_dropout = !float_equal(miopen::deref(dropoutDesc).dropout, 0);
auto prelayer_shift = static_cast<int>(
use_dropout ? (algoMode == miopenRNNdefault && rnnMode == miopenLSTM
? nLayers * batch_n * hy_stride + nLayers * batch_n * hy_h * bi
: 2 * nLayers * batch_n * hy_stride) +
(li - 1) * batch_n * hy_h * bi
: (li - 1) * batch_n * hy_stride + hid_off);
miopen::GemmDescriptor gemm_desc = GemmDescriptor{false,
true,
false,
wei_len * bi,
hy_h * bi,
batch_n,
hy_stride,
use_dropout ? hy_h * bi : hy_stride,
bi_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
1, // beta
xDesc[0].GetType()};
miopenStatus_t gemm_status = CallGemm(handle,
gemm_desc,
workSpace,
hid_shift,
reserveSpace,
prelayer_shift,
dw,
wei_shift,
nullptr,
GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
profileRNNkernels(handle, 1, ctime);
}
if(biasMode != 0u)
{
wei_shift = static_cast<int>(wei_shift_bias) + li * 2 * wei_stride;
sp_size[1] = batch_n;
sp_size[2] = wei_stride;
w_size[1] = 1;
w_size[2] = wei_stride;
w_desc = miopen::TensorDescriptor(dwDesc.GetType(), w_size.data(), w_stride.data(), 3);
sp_desc =
miopen::TensorDescriptor(dwDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
alpha0 = 0;
alpha1 = 1;
beta_t = 1;
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
w_desc,
dw,
&alpha1,
sp_desc,
workSpace,
&beta_t,
w_desc,
dw,
wei_shift,
hid_shift,
wei_shift);
// Update time
profileRNNkernels(handle, 1, ctime);
}
// between time
// Calculate feedback for c gate in GRU
if(rnnMode == miopenGRU)
{
sp_size[1] = batch_n;
sp_size[2] = hy_h;
sp_desc =
miopen::TensorDescriptor(dwDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
for(int ri = 0; ri < bi; ri++)
{
CopyTensor(handle,
sp_desc,
reserveSpace,
sp_desc,
workSpace,
hid_shift + hid_off + ri * hy_h +
static_cast<int>(nLayers) * batch_n * hy_stride,
hid_shift + 2 * hy_h + ri * wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
if(biasMode != 0u)
{
wei_shift = static_cast<int>(wei_shift_bias) + li * 2 * wei_stride + wei_stride;
alpha0 = 1;
alpha1 = 1;
beta_t = 0;
if(hx != nullptr)
{
if(rnnMode == miopenGRU)
{
sp_size[1] = batch_n;
sp_size[2] = wei_stride;
w_size[1] = 1;
w_size[2] = wei_stride;
w_desc = miopen::TensorDescriptor(
dwDesc.GetType(), w_size.data(), w_stride.data(), 3);
sp_desc = miopen::TensorDescriptor(
dwDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
w_desc,
dw,
&alpha1,
sp_desc,
workSpace,
&beta_t,
w_desc,
dw,
wei_shift,
hid_shift,
wei_shift);
// Update time
profileRNNkernels(handle, 1, ctime);
}
else
{
CopyTensor(handle, w_desc, dw, w_desc, dw, wei_shift - wei_stride, wei_shift);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
else
{
sp_size[1] = 1;
sp_size[2] = wei_len;
w_size[1] = 1;
w_size[2] = wei_len;
w_desc =
miopen::TensorDescriptor(dwDesc.GetType(), w_size.data(), w_stride.data(), 3);
sp_desc =
miopen::TensorDescriptor(dwDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
for(int bs = 0; bs < batch_n; bs++)
{
if(!(hx == nullptr && bs < in_n.at(0)))
{
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
sp_desc,
workSpace,
&alpha1,
w_desc,
dw,
&beta_t,
w_desc,
dw,
hid_shift + bs * hy_stride,
wei_shift,
wei_shift);
// Update time
profileRNNkernels(handle, 1, ctime);
}
}
if(dirMode != 0u)
{
sp_size[1] = 1;
sp_size[2] = wei_len;
w_size[1] = 1;
w_size[2] = wei_len;
w_desc = miopen::TensorDescriptor(
dwDesc.GetType(), w_size.data(), w_stride.data(), 3);
sp_desc = miopen::TensorDescriptor(
dwDesc.GetType(), sp_size.data(), sp_stride.data(), 3);
int cur_batch = 0;
for(int ti = 0; ti < seqLen - 1; ti++)
{
for(int bs = 0; bs < in_n.at(ti + 1); bs++)
{
OpTensor(handle,
miopenTensorOpAdd,
&alpha0,
sp_desc,
workSpace,
&alpha1,
w_desc,
dw,
&beta_t,
w_desc,
dw,
hid_shift + (cur_batch + bs) * hy_stride + wei_len,
wei_shift + wei_len,
wei_shift + wei_len);
// Update time
profileRNNkernels(handle, 1, ctime);
}
cur_batch += in_n.at(ti);
}
}
}
}
int pretime_shift, hx_shift, cur_time;
bool comb_check = true;
if(seqLen > 2)
{
if(in_n.at(0) != in_n.at(seqLen - 2))
{
comb_check = false;
}
}
if(comb_check)
{
hx_shift = li * hy_n * bi_stride;
wei_shift = in_h * wei_stride + li * (bi * hy_h + hy_h) * wei_stride;
for(int ri = 0; ri < bi; ri++)
{
hid_shift =
ri == 0 ? li * batch_n * hy_stride
: (li * batch_n * hy_stride + in_n.at(0) * (seqLen - 1) * hy_stride);
cur_time = ri == 0 ? 0 : seqLen - 1;
if(in_n.at(cur_time) > 0 && hx != nullptr)
{
miopen::GemmDescriptor gemm_desc = GemmDescriptor{false,
true,
false,
wei_len,
hy_h,
in_n.at(cur_time),
hy_stride,
uni_stride,
uni_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
1, // beta
xDesc[0].GetType()};
miopenStatus_t gemm_status = CallGemm(handle,
gemm_desc,
workSpace,
hid_shift + ri * wei_len,
hx,
hx_shift + ri * hy_n * hy_h,
dw,
wei_shift + ri * wei_len * uni_stride,
nullptr,
GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
if(li == nLayers - 1 && ri == bi - 1 && seqLen == 1)
profileRNNkernels(handle, 2, ctime);
else
profileRNNkernels(handle, 1, ctime);
}
if(seqLen > 1)
{
if(ri == 1 && hx != nullptr && in_n.at(0) > in_n.at(seqLen - 1))
{
miopen::GemmDescriptor gemm_desc =
GemmDescriptor{false,
true,
false,
wei_len,
hy_h,
(in_n.at(0) - in_n.at(seqLen - 1)),
hy_stride,
uni_stride,
uni_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
1, // beta
xDesc[0].GetType()};
miopenStatus_t gemm_status =
CallGemm(handle,
gemm_desc,
workSpace,
hid_shift + ri * wei_len -
(in_n.at(0) - in_n.at(seqLen - 1)) * hy_stride,
hx,
hx_shift + ri * hy_n * hy_h + in_n.at(seqLen - 1) * hy_h,
dw,
wei_shift + ri * wei_len * uni_stride,
nullptr,
GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
profileRNNkernels(handle, 1, ctime);
}
hid_shift = ri == 0 ? (li * batch_n * hy_stride + in_n.at(0) * hy_stride)
: (li * batch_n * hy_stride);
pretime_shift =
ri == 0 ? li * batch_n * hy_stride + hid_off
: li * batch_n * hy_stride + in_n.at(0) * hy_stride + hid_off;
miopen::GemmDescriptor gemm_desc =
GemmDescriptor{false,
true,
false,
wei_len,
hy_h,
in_n.at(0) * (seqLen - 2) + in_n.at(seqLen - 1),
hy_stride,
hy_stride,
uni_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
1, // beta
xDesc[0].GetType()};
miopenStatus_t gemm_status = CallGemm(handle,
gemm_desc,
workSpace,
hid_shift + ri * wei_len,
reserveSpace,
pretime_shift + ri * hy_h,
dw,
wei_shift + ri * wei_len * uni_stride,
nullptr,
GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
if(li == nLayers - 1 && ri == bi - 1)
profileRNNkernels(handle, 2, ctime);
else
profileRNNkernels(handle, 1, ctime);
}
}
}
else
{
int bacc = 0;
int baccbi = batch_n;
for(int ti = 0; ti < seqLen; ti++)
{
baccbi -= in_n.at(seqLen - 1 - ti);
hx_shift = li * hy_n * bi_stride;
wei_shift = in_h * wei_stride + li * (bi * hy_h + hy_h) * wei_stride;
for(int ri = 0; ri < bi; ri++)
{
hid_shift = ri == 0 ? (li * batch_n * hy_stride + bacc * hy_stride)
: (li * batch_n * hy_stride + baccbi * hy_stride);
cur_time = ri == 0 ? ti : seqLen - 1 - ti;
if(ti > 0)
{
pre_batch =
ri == 0 ? bacc - in_n.at(ti - 1) : baccbi + in_n.at(seqLen - 1 - ti);
use_time = ri == 0 ? ti : seqLen - ti;
}
if(in_n.at(cur_time) > 0)
{
if(ti == 0)
{
if(hx != nullptr)
{
miopen::GemmDescriptor gemm_desc =
GemmDescriptor{false,
true,
false,
wei_len,
hy_h,
in_n.at(cur_time),
hy_stride,
uni_stride,
uni_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
1, // beta
xDesc[0].GetType()};
miopenStatus_t gemm_status =
CallGemm(handle,
gemm_desc,
workSpace,
hid_shift + ri * wei_len,
hx,
hx_shift + ri * hy_n * hy_h,
dw,
wei_shift + ri * wei_len * uni_stride,
nullptr,
GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
if(li == nLayers - 1 && ti == seqLen - 1 && ri == bi - 1)
profileRNNkernels(handle, 2, ctime);
else
profileRNNkernels(handle, 1, ctime);
}
}
else
{
if(ri == 1 && hx != nullptr && in_n.at(cur_time) > in_n.at(use_time))
{
miopen::GemmDescriptor gemm_desc =
GemmDescriptor{false,
true,
false,
wei_len,
hy_h,
(in_n.at(cur_time) - in_n.at(use_time)),
hy_stride,
uni_stride,
uni_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
1, // beta
xDesc[0].GetType()};
miopenStatus_t gemm_status = CallGemm(
handle,
gemm_desc,
workSpace,
hid_shift + ri * wei_len + in_n.at(use_time) * hy_stride,
hx,
hx_shift + ri * hy_n * hy_h + in_n.at(use_time) * hy_h,
dw,
wei_shift + ri * wei_len * uni_stride,
nullptr,
GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
profileRNNkernels(handle, 1, ctime);
}
pretime_shift =
li * batch_n * hy_stride + pre_batch * hy_stride + hid_off;
if(in_n.at(use_time) > 0)
{
miopen::GemmDescriptor gemm_desc =
GemmDescriptor{false,
true,
false,
wei_len,
hy_h,
in_n.at(use_time),
hy_stride,
hy_stride,
uni_stride,
1, // batch count
0, // Stride A
0, // Stride B
0, // Stride C
1, // alpha
1, // beta
xDesc[0].GetType()};
miopenStatus_t gemm_status =
CallGemm(handle,
gemm_desc,
workSpace,
hid_shift + ri * wei_len,
reserveSpace,
pretime_shift + ri * hy_h,
dw,
wei_shift + ri * wei_len * uni_stride,
nullptr,
GemmBackend_t::miopengemm);
if(gemm_status != miopenStatusSuccess)
{
if(gemm_status == miopenStatusNotImplemented)
{
MIOPEN_LOG_E("GEMM not implemented");
}
else
{
MIOPEN_LOG_E("GEMM failed");
}
}
// Update time
if(li == nLayers - 1 && ti == seqLen - 1 && ri == bi - 1)
profileRNNkernels(handle, 2, ctime);
else
profileRNNkernels(handle, 1, ctime);
}
}
}
}
bacc += in_n.at(ti);
}
}
}
#else
(void)in_stride;
(void)alpha0;
(void)wei_shift_bias;
(void)alpha1;
(void)bi_stride;
(void)uni_stride;
(void)hx;
(void)workSpace;
(void)reserveSpace;
MIOPEN_THROW("GEMM is not supported");
#endif
};
} // namespace miopen
| ROCmSoftwarePlatform/MIOpen | src/ocl/rnnocl.cpp | C++ | mit | 222,865 |
<?php
namespace Renovate\MainBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Renovate\MainBundle\Entity\Vacancy;
use Renovate\MainBundle\Entity\Document;
class VacanciesController extends Controller
{
public function indexAction()
{
$timestamp = time();
$token = Document::getToken($timestamp);
$parameters = array(
'timestamp' => $timestamp,
'token' => $token
);
$parameters['page'] = $this->get('renovate.pages')->getPageForUrl($this->getRequest()->getUri());
return $this->render('RenovateMainBundle:Vacancies:index.html.twig', $parameters);
}
public function showVacancyAction($vacancy_name_translit)
{
$em = $this->getDoctrine()->getManager();
$vacancy = $em->getRepository("RenovateMainBundle:Vacancy")->findOneByNameTranslit($vacancy_name_translit);
if ($vacancy == NULL) return $this->redirect($this->generateUrl('renovate_main_homepage'));
$parameters = array("vacancy" => $vacancy);
$parameters['page'] = $this->get('renovate.pages')->getPageForUrl($this->getRequest()->getUri());
return $this->render('RenovateMainBundle:Vacancies:showVacancy.html.twig', $parameters);
}
public function getVacanciesNgAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$response = new Response(json_encode(array("result" => Vacancy::getVacancies($em, $request->query->all(), true))));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
public function getVacanciesCountNgAction()
{
$em = $this->getDoctrine()->getManager();
$response = new Response(json_encode(array("result" => Vacancy::getVacanciesCount($em))));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
public function addVacancyNgAction()
{
$em = $this->getDoctrine()->getManager();
$data = json_decode(file_get_contents("php://input"));
$parameters = (object) $data;
$transliterater = $this->get('renovate.transliterater');
$vacancy = Vacancy::addVacancy($em, $transliterater, $parameters);
$response = new Response(json_encode(array("result" => $vacancy->getInArray())));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
public function removeVacancyNgAction($vacancy_id)
{
$em = $this->getDoctrine()->getManager();
$response = new Response(json_encode(array("result" => Vacancy::removeVacancyById($em, $vacancy_id))));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
public function editVacancyNgAction($vacancy_id)
{
$em = $this->getDoctrine()->getManager();
$data = json_decode(file_get_contents("php://input"));
$parameters = (object) $data;
$transliterater = $this->get('renovate.transliterater');
$vacancy = Vacancy::editVacancyById($em, $transliterater, $vacancy_id, $parameters);
$response = new Response(json_encode(array("result" => $vacancy->getInArray())));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
}
| oligarch777/renovate | src/Renovate/MainBundle/Controller/VacanciesController.php | PHP | mit | 3,444 |
class AddMemberAddressFragments < ActiveRecord::Migration
def up
add_column :members, :street_address, :string
add_column :members, :address_locality, :string
add_column :members, :address_region, :string
add_column :members, :address_country, :string
add_column :members, :postal_code, :string
add_column :members, :organization_type, :string
add_column :members, :organization_vat_id, :string
add_column :members, :organization_company_number, :string
end
def down
remove_column :members, :street_address
remove_column :members, :address_locality
remove_column :members, :address_region
remove_column :members, :address_country
remove_column :members, :postal_code
remove_column :members, :organization_type
remove_column :members, :organization_vat_id
remove_column :members, :organization_company_number
end
end
| theodi/member-directory | db/migrate/20150303135313_add_member_address_fragments.rb | Ruby | mit | 889 |
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
// https://stackoverflow.com/a/34384189
namespace PS4Macro.Classes.GlobalHooks
{
public class GlobalKeyboardHookEventArgs : HandledEventArgs
{
public GlobalKeyboardHook.KeyboardState KeyboardState { get; private set; }
public GlobalKeyboardHook.LowLevelKeyboardInputEvent KeyboardData { get; private set; }
public GlobalKeyboardHookEventArgs(
GlobalKeyboardHook.LowLevelKeyboardInputEvent keyboardData,
GlobalKeyboardHook.KeyboardState keyboardState)
{
KeyboardData = keyboardData;
KeyboardState = keyboardState;
}
}
//Based on https://gist.github.com/Stasonix
public class GlobalKeyboardHook : IDisposable
{
public event EventHandler<GlobalKeyboardHookEventArgs> KeyboardPressed;
public GlobalKeyboardHook()
{
_windowsHookHandle = IntPtr.Zero;
_user32LibraryHandle = IntPtr.Zero;
_hookProc = LowLevelKeyboardProc; // we must keep alive _hookProc, because GC is not aware about SetWindowsHookEx behaviour.
_user32LibraryHandle = LoadLibrary("User32");
if (_user32LibraryHandle == IntPtr.Zero)
{
int errorCode = Marshal.GetLastWin32Error();
throw new Win32Exception(errorCode, $"Failed to load library 'User32.dll'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
}
_windowsHookHandle = SetWindowsHookEx(WH_KEYBOARD_LL, _hookProc, _user32LibraryHandle, 0);
if (_windowsHookHandle == IntPtr.Zero)
{
int errorCode = Marshal.GetLastWin32Error();
throw new Win32Exception(errorCode, $"Failed to adjust keyboard hooks for '{Process.GetCurrentProcess().ProcessName}'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
}
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// because we can unhook only in the same thread, not in garbage collector thread
if (_windowsHookHandle != IntPtr.Zero)
{
if (!UnhookWindowsHookEx(_windowsHookHandle))
{
int errorCode = Marshal.GetLastWin32Error();
throw new Win32Exception(errorCode, $"Failed to remove keyboard hooks for '{Process.GetCurrentProcess().ProcessName}'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
}
_windowsHookHandle = IntPtr.Zero;
// ReSharper disable once DelegateSubtraction
_hookProc -= LowLevelKeyboardProc;
}
}
if (_user32LibraryHandle != IntPtr.Zero)
{
if (!FreeLibrary(_user32LibraryHandle)) // reduces reference to library by 1.
{
int errorCode = Marshal.GetLastWin32Error();
throw new Win32Exception(errorCode, $"Failed to unload library 'User32.dll'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
}
_user32LibraryHandle = IntPtr.Zero;
}
}
~GlobalKeyboardHook()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private IntPtr _windowsHookHandle;
private IntPtr _user32LibraryHandle;
private HookProc _hookProc;
delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll")]
private static extern IntPtr LoadLibrary(string lpFileName);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
private static extern bool FreeLibrary(IntPtr hModule);
/// <summary>
/// The SetWindowsHookEx function installs an application-defined hook procedure into a hook chain.
/// You would install a hook procedure to monitor the system for certain types of events. These events are
/// associated either with a specific thread or with all threads in the same desktop as the calling thread.
/// </summary>
/// <param name="idHook">hook type</param>
/// <param name="lpfn">hook procedure</param>
/// <param name="hMod">handle to application instance</param>
/// <param name="dwThreadId">thread identifier</param>
/// <returns>If the function succeeds, the return value is the handle to the hook procedure.</returns>
[DllImport("USER32", SetLastError = true)]
static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hMod, int dwThreadId);
/// <summary>
/// The UnhookWindowsHookEx function removes a hook procedure installed in a hook chain by the SetWindowsHookEx function.
/// </summary>
/// <param name="hhk">handle to hook procedure</param>
/// <returns>If the function succeeds, the return value is true.</returns>
[DllImport("USER32", SetLastError = true)]
public static extern bool UnhookWindowsHookEx(IntPtr hHook);
/// <summary>
/// The CallNextHookEx function passes the hook information to the next hook procedure in the current hook chain.
/// A hook procedure can call this function either before or after processing the hook information.
/// </summary>
/// <param name="hHook">handle to current hook</param>
/// <param name="code">hook code passed to hook procedure</param>
/// <param name="wParam">value passed to hook procedure</param>
/// <param name="lParam">value passed to hook procedure</param>
/// <returns>If the function succeeds, the return value is true.</returns>
[DllImport("USER32", SetLastError = true)]
static extern IntPtr CallNextHookEx(IntPtr hHook, int code, IntPtr wParam, IntPtr lParam);
[StructLayout(LayoutKind.Sequential)]
public struct LowLevelKeyboardInputEvent
{
/// <summary>
/// A virtual-key code. The code must be a value in the range 1 to 254.
/// </summary>
public int VirtualCode;
/// <summary>
/// A hardware scan code for the key.
/// </summary>
public int HardwareScanCode;
/// <summary>
/// The extended-key flag, event-injected Flags, context code, and transition-state flag. This member is specified as follows. An application can use the following values to test the keystroke Flags. Testing LLKHF_INJECTED (bit 4) will tell you whether the event was injected. If it was, then testing LLKHF_LOWER_IL_INJECTED (bit 1) will tell you whether or not the event was injected from a process running at lower integrity level.
/// </summary>
public int Flags;
/// <summary>
/// The time stamp stamp for this message, equivalent to what GetMessageTime would return for this message.
/// </summary>
public int TimeStamp;
/// <summary>
/// Additional information associated with the message.
/// </summary>
public IntPtr AdditionalInformation;
}
public const int WH_KEYBOARD_LL = 13;
//const int HC_ACTION = 0;
public enum KeyboardState
{
KeyDown = 0x0100,
KeyUp = 0x0101,
SysKeyDown = 0x0104,
SysKeyUp = 0x0105
}
public const int VkSnapshot = 0x2c;
//const int VkLwin = 0x5b;
//const int VkRwin = 0x5c;
//const int VkTab = 0x09;
//const int VkEscape = 0x18;
//const int VkControl = 0x11;
const int KfAltdown = 0x2000;
public const int LlkhfAltdown = (KfAltdown >> 8);
public IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam)
{
bool fEatKeyStroke = false;
var wparamTyped = wParam.ToInt32();
if (Enum.IsDefined(typeof(KeyboardState), wparamTyped))
{
object o = Marshal.PtrToStructure(lParam, typeof(LowLevelKeyboardInputEvent));
LowLevelKeyboardInputEvent p = (LowLevelKeyboardInputEvent)o;
var eventArguments = new GlobalKeyboardHookEventArgs(p, (KeyboardState)wparamTyped);
EventHandler<GlobalKeyboardHookEventArgs> handler = KeyboardPressed;
handler?.Invoke(this, eventArguments);
fEatKeyStroke = eventArguments.Handled;
}
return fEatKeyStroke ? (IntPtr)1 : CallNextHookEx(IntPtr.Zero, nCode, wParam, lParam);
}
}
} | komefai/PS4Macro | PS4Macro/Classes/GlobalHooks/GlobalKeyboardHook.cs | C# | mit | 9,190 |
module Rapa
class AlternateVersion
# @return [Hash]
attr_reader :source
# @param source [Hash]
def initialize(source)
@source = source
end
# @return [String]
def asin
source["ASIN"]
end
# @return [String]
def binding
source["Binding"]
end
# @return [String]
def title
source["Title"]
end
end
end
| r7kamura/rapa | lib/rapa/alternate_version.rb | Ruby | mit | 384 |
/**
* \file
* \brief Implementions of RL domains, Mountain Car (MC), HIV, and Bicycle.
*
* Copyright (c) 2008-2014 Robert D. Vincent.
*/
#include <vector>
#include <utility>
#include <cmath>
#include <string.h>
using namespace std;
#include "domain.h"
#include "random.h"
/** Returns the sign of a real number.
* \param x The number whose sign we wish to extract.
* \return The sign of \c x.
*/
double sign(double x) {
if (x == 0.0) return 0.0;
if (x < 0.0) return -1.0;
return 1.0;
}
/*
double dangle(double x) {
return fabs(x + 2.0*k*M_PI);
}
*/
/**
* Bicycle-balancing task used in Ernst et al. 2005.
*/
class Bicycle : public Domain {
private:
double dt;
double v;
double g;
double d_CM;
double c;
double h;
double M_c;
double M_d;
double M_p;
double M;
double r;
double l;
//double delta_psi; // used for reward calculation.
public:
/** Construct the bicycle balancing domain.
*/
Bicycle() {
numActions = 9;
numSteps = 500;
numDimensions = 7;
dt = 0.01;
v = 10.0/3.6;
g = 9.82;
d_CM = 0.3;
c = 0.66;
h = 0.94;
M_c = 15.0;
M_d = 1.7;
M_p = 60.0;
M = M_c + M_p;
r = 0.34;
l = 1.11;
}
bool isTerminal(vector<double> s) const {
return (s[0] > M_PI*12.0/180.0);
}
double getReward(vector<double> s, int a) const {
if (isTerminal(s)) return -1.0;
//return 0.1 * delta_psi;
return 0;
}
OneStepResult performAction(vector<double> s, int a) {
vector<double> sp(numDimensions, 0.0);
double ad[] = { 0.0, 0.0, 0.0, -0.02, -0.02, -0.02, 0.02, 0.02, 0.02 };
double aT[] = { 0.0, 2.0, -2.0, 0.0, 2.0, -2.0, 0.0, 2.0, -2.0 };
double d = ad[a];
double T = aT[a];
double w = rndInterval(-0.02, 0.02);
double dot_sigma = v/r;
double I_bnc = 13.0/3.0*M_c*h*h + M_p*(h + d_CM)*(h + d_CM);
double I_dc = M_d * r * r;
double I_dv = 3.0/2.0 * M_d * r * r;
double I_dl = 1.0/2.0 * M_d * r * r;
double omega = s[0];
double dot_omega = s[1];
double theta = s[2];
double dot_theta = s[3];
double x_b = s[4];
double y_b = s[5];
double psi = s[6];
double phi = omega + atan(d + w)/h;
double invrf = fabs(sin(theta))/l;
double invrb = fabs(tan(theta))/l;
double invrcm = (theta == 0.0) ? 0.0 : 1.0/sqrt((l-c)*(l-c) + (1.0/invrb)*(1.0/invrb));
sp[0] = omega + dt * dot_omega;
sp[1] = dot_omega + dt * (1.0 / I_bnc) * (M*h*g*sin(phi) - cos(phi)*(I_dc*dot_sigma*dot_theta + sign(theta)*v*v*(M_d*r*(invrb+invrf)+M*h*invrcm)));
sp[2] = theta + dt * dot_theta;
sp[3] = dot_theta + dt * (T - I_dv*dot_sigma*dot_omega)/I_dl;
sp[4] = x_b + dt * v * cos(psi);
sp[5] = y_b + dt * v * sin(psi);
sp[6] = psi + dt * sign(theta)*v*invrb;
//delta_psi = dangle(psi) - dangle(sp[6]);
if (fabs(theta) > M_PI*80.0/180.0) {
sp[2] = sign(theta)*M_PI*80.0/180.0;
sp[3] = 0.0;
}
OneStepResult p(sp, getReward(sp, a));
return p;
}
vector<double> initialState() {
vector<double> s(numDimensions, 0.0);
s[6] = M_PI;
return s;
}
};
/**
* \brief Implements the HIV model defined by Adams et al. (2004, 2005) and
* used by Ernst et al. (2006).
*
* This domain simulates the dynamics of HIV infection at the cellular level.
* It uses a six-dimensional real-valued state
* vector, in the order T1, T2, T1*, T2*, V, E, where T1 and T2 are the
* populations of uninfected type 1 and type 2 cells, and T1* and T2* are
* the populations of infected type 1 and 2 cells. V is the viral population,
* and E is the population of immune effectors.
*
* The problem is deterministic. It has three stable states, corresponding
* to an "uninfected" state, an "unhealthy" state, and a "healthy" state.
* The goal of the problem is to learn how to move the model from the
* unhealthy state to the healthy state.
*
* The action space in this implementation is limited to four discrete
* choices: No therapy, reverse transcriptase inhibitor only (RTI),
* protease inhibitor (PI) only, or both RTI and PI
* simultaneously. The RTI and PI have fixed values.
* These are the stable state vectors:
*
* - unhealthy: (163574.0, 5.0, 11945.0, 46.0, 63919.0, 24.0)
* - healthy: (967839.0, 621.0, 76.0, 6.0, 415.0, 353108.0)
* - uninfected: (1000000.0, 3198.0, 0.0, 0.0, 0.0, 10.0)
*/
class HIV : public Domain {
private:
double Q; /**< Coefficient of the viral load in the reward function. */
double R1; /**< Coefficient of the RTI in the reward function. */
double R2; /**< Coefficient of the PI in the reward function. */
double S; /**< Coefficient of the immune effectors. */
double l1; /**< type 1 cell production rate */
double d1; /**< type 1 cell death rate */
double k1; /**< population 1 infection rate */
double l2; /**< type 2 cell production rate */
double d2; /**< type 2 cell death rate */
double f; /**< treatment efficacy reduction in population 2 */
double k2; /**< population 2 infection rate */
double delta; /**< infected cell death rate */
double m1; /**< immune-induced clearance rate for population 1 */
double m2; /**< immune-induced clearance rate for population 2 */
double NT; /**< virions produced per infected cell */
double c; /**< virus natural death rate */
double p1; /**< average number of virions infecting a type 1 cell */
double p2; /**< average number of virions infecting a type 2 cell */
double lE; /**< immune effector production rate */
double bE; /**< maximum birth rate for immune effectors */
double Kb; /**< saturation constant for immune effector birth */
double dE; /**< maximum death rate for immune effectors */
double Kd; /**< saturation constant for immune effector death */
double deltaE; /**< natural death rate for immune effectors */
// Other constants
double dt; /**< Our integration timestep, in days. */
int nInt; /**< Number of integration steps per action. */
public:
/**
* Constructor for the HIV domain.
*/
HIV() {
numActions = 4;
numSteps = 200;
numDimensions = 6;
// constants for the reward function
Q = 0.1;
R1 = 20000.0;
R2 = 2000.0;
S = 1000.0;
// Constants for the ODE's
l1 = 10000.0; // type 1 cell production rate
d1 = 0.01; // type 1 cell death rate
k1 = 8.0e-7; // population 1 infection rate
l2 = 31.98; // type 2 cell production rate
d2 = 0.01; // type 2 cell death rate
f = 0.34; // treatment efficacy reduction in population 2
k2 = 1e-4; // population 2 infection rate
delta = 0.7; // infected cell death rate
m1 = 1.0e-5; // immune-induced clearance rate for population 1
m2 = 1.0e-5; // immune-induced clearance rate for population 2
NT = 100.0; // virions produced per infected cell
c = 13.0; // virus natural death rate
p1 = 1.0; // average number of virions infecting a type 1 cell
p2 = 1.0; // average number of virions infecting a type 2 cell
lE = 1.0; // immune effector production rate
bE = 0.3; // maximum birth rate for immune effectors
Kb = 100.0; // saturation constant for immune effector birth
dE = 0.25; // maximum death rate for immune effectors
Kd = 500.0; // saturation constant for immune effector death
deltaE = 0.1; // natural death rate for immune effectors
// Other constants
dt = 0.001; // Our integration timestep, in days.
nInt = (int)(5.0 / dt); // Number of integration steps per action.
}
/**
* Calculate the reward for the HIV domain. The reward is a
* continuous function of the action (treatment option), the virus
* population (\c s[4]) and the immune effector count (\c s[5]).
*/
double getReward(vector<double> s, int a) const {
// e1 is between 0.0 and 0.7 (RTI therapy on/off)
// e2 is between 0.0 and 0.3 (PI therapy on/off)
double V = s[4];
double E = s[5];
double e1 = ((a & 1) != 0) ? 0.7 : 0.0;
double e2 = ((a & 2) != 0) ? 0.3 : 0.0;
return -(Q*V + R1*e1*e1 + R2*e2*e2 - S*E);
}
/**
* Calculate the next state of the environment. The equations
* are integrated using a simple Euler method.
*/
OneStepResult performAction(vector<double> s, int a) {
/* This version is restricted to only four possible actions.
*/
double e1 = ((a & 1) != 0) ? 0.7 : 0.0;
double e2 = ((a & 2) != 0) ? 0.3 : 0.0;
vector<double> dy(numDimensions);
vector<double> y = s;
for (int i = 0; i < nInt; i++) {
dy[0] = l1 - d1 * y[0] - (1 - e1) * k1 * y[4] * y[0];
dy[1] = l2 - d2 * y[1] - (1 - f * e1) * k2 * y[4] * y[1];
dy[2] = (1 - e1) * k1 * y[4] * y[0] - delta * y[2] - m1 * y[5] * y[2];
dy[3] = (1 - f * e1) * k2 * y[4] * y[1] - delta * y[3] - m2 * y[5] * y[3];
dy[4] = (1.0 - e2) * NT * delta * (y[2] + y[3]) - c * y[4] -
((1 - e1) * p1 * k1 * y[0] + (1 - f * e1) * p2 * k2 * y[1]) * y[4];
dy[5] = lE + (bE * (y[2] + y[3]) * y[5]) / (y[2] + y[3] + Kb) -
(dE * (y[2] + y[3]) * y[5]) / (y[2] + y[3] + Kd) - deltaE * y[5];
for (int j = 0; j < numDimensions; j++)
y[j] += dy[j] * dt;
}
OneStepResult p(y, getReward(y, a));
return p;
}
/**
* The initial state in the environment is the "sick" stable state.
* There are two other stable states, a "healthy infected" state,
* and an "uninfected" state.
*/
vector<double> initialState() {
vector<double> s(numDimensions);
/* This is the "sick" initial state.
*/
s[0] = 163574.0;
s[1] = 5.0;
s[2] = 11945.0;
s[3] = 46.0;
s[4] = 63919.0;
s[5] = 24.0;
return s;
}
};
/**
* Implementation of the classic "mountain-car" reinforcement learning
* problem from Singh and Sutton 1996. It implements a two-dimensional
* continuous state consisting of the car's position and velocity.
*/
class MC : public Domain {
static const double min_x = -1.2; /**< Minimum position. */
static const double max_x = 0.5; /**< Maximum position. */
static const double min_v = -0.07; /**< Minimum velocity. */
static const double max_v = 0.07; /**< Maximum velocity. */
public:
/**
* Construct a mountain-car environment.
*/
MC() {
numDimensions = 2;
numActions = 3;
numSteps = 2000;
}
/**
* The domain is stochastic, in that it begins at a random initial
* state. It is otherwise deterministic.
*/
bool isStochastic() { return true; }
/**
* Return the reward for this state and action. For mountain car the
* usual implementation is to give a reward of -1 for every time step
* before reaching the goal.
* \param s The state vector.
* \param a The action.
* \return The reward received.
*/
double getReward(vector<double> s, int a) const {
if (isTerminal(s)) {
return 0.0;
}
else return -1.0;
}
/**
* Return the initial state for the task. Selects uniformly random values
* from the legal range of the position and velocity values.
* \return A two-dimensional state vector consisting of a random legal
* position and velocity.
*/
vector<double> initialState() {
vector<double> s(numDimensions);
s[0] = rndInterval(min_x, max_x);
s[1] = rndInterval(min_v, max_v);
return s;
}
/**
* Perform one time step in the mountain car environment.
* \param s The two-dimensional mountain car state vector.
* \param a The action to perform, where 0 means full reverse, 2 means full forward, and 1 implies no acceleration.
* \return A pair containing the next state and reward.
*/
OneStepResult performAction(vector<double> s, int a) {
double acc = 0.0;
if (a == 0) {
acc = -1.0;
}
if (a == 2) {
acc = 1.0;
}
double x0 = s[0];
double v0 = s[1];
double v1 = v0 + acc * 0.001 + cos(3.0 * x0) * -0.0025;
// Enforce bounds.
if (v1 < min_v) {
v1 = min_v;
}
else if (v1 > max_v) {
v1 = max_v;
}
double x1 = x0 + v1;
if (x1 < min_x) {
x1 = min_x;
}
else if (x1 > max_x) {
x1 = max_x;
}
vector<double> s1(numDimensions);
s1[0] = x1;
s1[1] = v1;
OneStepResult p(s1, getReward(s1, a));
return p;
}
/**
* Returns true if the car has reached the goal state.
* \param s The state to evaluate.
* \return True if the car's position is at is maximum.
*/
bool isTerminal(vector<double> s) const { return (s[0] >= max_x); }
};
/**
* Create a domain by name. Avoids having to export domain classes outside
* this module.
* \param name The name of the domain to create. It is not case-sensitive.
* The default is HIV
* \param propfile The name of an optional property file, which will provide
* configuration information for the domain.
* \return The domain object.
*/
Domain *CreateDomain(const char *name, const char *propfile) {
if (!strcasecmp(name, "MC")) {
return new MC();
}
else if (!strcasecmp(name, "Bicycle")) {
return new Bicycle();
}
else if (!strcasecmp(name, "rf")) {
extern Domain *getRF(const char *);
return getRF(propfile);
}
else if (!strcasecmp(name, "tass")) {
extern Domain *getTass(const char *);
return getTass(propfile);
}
else {
return new HIV();
}
}
| rdvincent/fqi | domain.cpp | C++ | mit | 13,528 |
'use strict';
angular.module('app.directives')
.directive('questionBlock',function() {
return {
restrict: 'E',
scope: {
question:'='
},
templateUrl:'/directives/questions/question-block.html'
};
});
| pwithers/agrippa | public/js/directives/question-block.js | JavaScript | mit | 244 |
from asyncio import coroutine
import pytest
from aiohttp import HttpBadRequest, HttpMethodNotAllowed
from fluentmock import create_mock
from aiohttp_rest import RestEndpoint
class CustomEndpoint(RestEndpoint):
def get(self):
pass
def patch(self):
pass
@pytest.fixture
def endpoint():
return RestEndpoint()
@pytest.fixture
def custom_endpoint():
return CustomEndpoint()
def test_exiting_methods_are_registered_during_initialisation(custom_endpoint: CustomEndpoint):
assert len(custom_endpoint.methods) == 2
assert ('GET', custom_endpoint.get) in custom_endpoint.methods.items()
assert ('PATCH', custom_endpoint.patch) in custom_endpoint.methods.items()
def test_register_method(endpoint: RestEndpoint):
def sample_method():
pass
endpoint.register_method('verb', sample_method)
assert ('VERB', sample_method) in endpoint.methods.items()
@pytest.mark.asyncio
async def test_dispatch_uses_correct_handler_for_verb(endpoint: RestEndpoint):
endpoint.register_method('VERB1', coroutine(lambda: 5))
endpoint.register_method('VERB2', coroutine(lambda: 17))
assert await endpoint.dispatch(create_mock(method='VERB1', match_info={})) == 5
assert await endpoint.dispatch(create_mock(method='VERB2', match_info={})) == 17
@pytest.mark.asyncio
async def test_dispatch_passes_request_when_required(endpoint: RestEndpoint):
endpoint.register_method('REQUEST', coroutine(lambda request: request))
request = create_mock(method='REQUEST', match_info={})
assert await endpoint.dispatch(request) == request
@pytest.mark.asyncio
async def test_dispatch_passes_match_info_when_required(endpoint: RestEndpoint):
endpoint.register_method('MATCH_INFO', coroutine(lambda prop1, prop2: (prop2, prop1)))
request = create_mock(method='MATCH_INFO', match_info={'prop1': 1, 'prop2': 2})
assert await endpoint.dispatch(request) == (2, 1)
@pytest.mark.asyncio
async def test_dispatch_raises_bad_request_when_match_info_does_not_exist(endpoint: RestEndpoint):
endpoint.register_method('BAD_MATCH_INFO', coroutine(lambda no_match: no_match))
request = create_mock(method='BAD_MATCH_INFO', match_info={})
with pytest.raises(HttpBadRequest):
await endpoint.dispatch(request)
@pytest.mark.asyncio
async def test_dispatch_raises_method_not_allowed_when_verb_not_matched(endpoint: RestEndpoint):
request = create_mock(method='NO_METHOD')
with pytest.raises(HttpMethodNotAllowed):
await endpoint.dispatch(request)
| atbentley/aiohttp-rest | tests/test_endpoint.py | Python | mit | 2,542 |
package main
import (
"log"
"os"
"golang.org/x/net/context"
"google.golang.org/grpc"
// "google.golang.org/grpc/credentials/oauth"
"google.golang.org/grpc/metadata"
m "github.com/konjoot/grpc/proto/messages"
s "github.com/konjoot/grpc/proto/sessions"
)
const sessionAddr = "localhost:50051"
const messageAddr = "localhost:50052"
var (
defaultLogin = []byte("login")
defaultPass = []byte("pass")
)
func main() {
// Set up a connection to the server.
sessionConn, err := grpc.Dial(sessionAddr, grpc.WithInsecure())
if err != nil {
log.Fatalf("did not connect to session server: %v", err)
}
defer sessionConn.Close()
session := s.NewSessionClient(sessionConn)
login := defaultLogin
pass := defaultPass
if len(os.Args) > 1 {
login = []byte(os.Args[1])
}
if len(os.Args) > 2 {
pass = []byte(os.Args[2])
}
sess, err := session.Create(context.Background(), &s.SessionRequest{Login: login, Pass: pass})
if err != nil {
log.Fatalf("could not create session: %v", err)
}
messageConn, err := grpc.Dial(messageAddr, grpc.WithInsecure())
if err != nil {
log.Fatalf("did not connect to message server: %v", err)
}
defer messageConn.Close()
message := m.NewMessageClient(messageConn)
// header usage example
header := metadata.Pairs("Authorization", string(sess.Token))
ctx := metadata.NewContext(context.Background(), header)
msg, err := message.Create(ctx, &m.MessageRequest{User: []byte("user1"), Text: []byte("hello")})
if err != nil {
log.Fatalf("could not create message: %v", err)
}
log.Print(msg)
}
| konjoot/grpc | cmd/messages/client/main.go | GO | mit | 1,558 |
'use strict';
var _ = require('lodash');
var utils = require('../utils');
var d3 = require('d3');
var sunCalc = require('suncalc');
var geocoder = require('geocoder');
var Path = require('svg-path-generator');
var margin = {
top: 20,
right: 0,
bottom: 20,
left: 0
};
var dayOfYear = function(d) {
var j1 = new Date(d);
j1.setMonth(0, 0);
return Math.round((d - j1) / 8.64e7) - 1;
};
/*
* View controller
*/
function Viz($el) {
if (!(this instanceof Viz)) {
return new Viz($el);
}
this.$el = $el;
var $tooltip = $('#tooltip');
// do some cool vizualization here
var width = $el.width() - margin.left - margin.right;
var height = (Math.min(width * 0.6, $(document).height() - $el.offset().top - 180)) - margin.top - margin.bottom;
var today = new Date();
var start = new Date(today.getFullYear(), 0, 1, 12, 0, 0, 0, 0);
var end = new Date(today.getFullYear(), 11, 31, 12, 0, 0, 0, 0);
var dateX = d3.time.scale().domain([start, end]).range([0, width]);
this.x = d3.scale.linear()
.domain([0, 365])
.range([0, width]);
this.y = d3.scale.linear()
.domain([0, 24])
.range([0, height]);
var inverseX = d3.scale.linear()
.range([0, 365])
.domain([0, width]);
var xAxis = d3.svg.axis()
.scale(dateX);
var svg = d3.select($el[0])
.append('svg')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
.append('g')
.classed('container', true)
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
var self = this;
var hideTimeout;
svg.on('mousemove', function() {
if(!self.times.length) {
return;
}
var coordinates = d3.mouse(this);
var x = coordinates[0];
var i = inverseX(x);
i = Math.floor(i);
self.svg.selectAll('g.day').classed('hover', function(d, idx) {
return idx === i;
});
var format = d3.time.format('%B %e');
$tooltip.find('.date').text(format(self.dates[i]));
var sunset = new Date(self.times[i].sunset);
var sunrise = new Date(self.times[i].sunrise);
format = d3.time.format('%I:%M %p');
console.log(format(sunrise));
console.log(format(sunset));
$tooltip.find('.sunrise').text(format(sunrise));
$tooltip.find('.sunset').text(format(sunset));
var offset = self.$el.offset();
var top = offset.top;
top += self.y(sunrise.getHours() + sunrise.getMinutes() / 60);
var left = self.x(i) + offset.left;
left -= $tooltip.width() / 2;
top -= $tooltip.height() - 15;
$tooltip.css('top', top).css('left', left).show();
clearTimeout(hideTimeout);
}).on('mouseout', function(){
hideTimeout = setTimeout(function() {
$tooltip.fadeOut();
self.svg.selectAll('g.day').classed('hover', false);
}, 750);
});
d3.select($tooltip[0]).on('mouseenter', function() {
clearTimeout(hideTimeout);
});
this.svg = svg;
svg.append('rect')
.attr('x', 0)
.attr('y', 0)
.attr('width', width)
.attr('height', height);
svg.append('g')
.attr('class', 'x axis')
.attr('transform', 'translate(0,' + height + ')')
.call(xAxis);
var max = 0;
for (var d = start, i=0; d < end; d.setDate(d.getDate() + 1), i++) {
this._drawDay(i);
if(i > max) {
max = i;
}
}
var avgGroup = this.svg.append('g').classed('average', true);
avgGroup
.append('path')
.attr('d', function() {
return new Path()
.moveTo(self.x(0), self.y(12))
.horizontalLineTo(self.x(max))
.end();
})
.classed('sunrise', true);
avgGroup
.append('path')
.attr('d', function() {
return new Path()
.moveTo(self.x(0), self.y(12))
.horizontalLineTo(self.x(max))
.end();
})
.classed('sunset', true);
avgGroup
.append('text')
.attr('x', self.x(50))
.attr('y', self.y(12))
.style('opacity', 0)
.classed('sunrise', true);
avgGroup
.append('text')
.attr('x', self.x(250))
.attr('y', self.y(12))
.style('opacity', 0)
.classed('sunset', true);
this.svg
.append('path')
.attr('d', function() {
return new Path()
.moveTo(self.x(0), self.y(today.getHours() + today.getMinutes() / 60))
.horizontalLineTo(self.x(max))
.end();
})
.classed('now', true);
}
Viz.prototype.updatePlace = function(placeName) {
var self = this;
if(placeName.trim() === '') {
return;
}
var times = [];
var dates = [];
geocoder.geocode(placeName, function(err, res) {
if(err) {
return console.log(err);
}
if(!res.results.length) {
return $('.place-name-container').text('Could not find ' + placeName + '!');
}
$('.place-name-container').text(res.results[0].formatted_address);
var location = res.results[0].geometry.location;
var today = new Date();
var start = new Date(today.getFullYear(), 0, 1, 12, 0, 0, 0, 0);
var end = new Date(today.getFullYear()+1, 0, 1, 12, 0, 0, 0, 0);
for (var d = start, i=0; d < end; d.setDate(d.getDate() + 1), i++) {
var time = sunCalc.getTimes(d, location.lat, location.lng);
var isToday = false;
if(d.getDate() === today.getDate() && d.getMonth() === today.getMonth()) {
console.log('Today!');
console.log(d);
isToday = true;
}
self._updateToday(time);
self._updateLine(i, time, isToday);
times.push(time);
dates.push(new Date(d));
}
self._updateAverages(times);
});
this.times = times;
this.dates = dates;
};
Viz.prototype._updateToday = function(times) {
};
Viz.prototype._updateAverages = function(times) {
var avgSunrise = 0, avgSunset = 0;
_.each(times, function(time, i) {
var sunrise = new Date(time.sunrise);
var sunset = new Date(time.sunset);
if(sunset.getDate() !== sunrise.getDate()) {
if(dayOfYear(sunrise) !== i) {
avgSunrise -= 24;
} else {
avgSunset += 24;
}
}
avgSunset += sunset.getHours() + sunset.getMinutes() / 60;
avgSunrise += sunrise.getHours() + sunrise.getMinutes() / 60;
});
avgSunset /= times.length;
avgSunrise /= times.length;
avgSunrise = (avgSunrise + 24) % 24;
avgSunset = (avgSunset + 24) % 24;
var avg = this.svg.select('g.average');
var self = this;
avg.select('path.sunrise')
.transition()
.delay(150)
.duration(1500)
.attr('d', function() {
return new Path()
.moveTo(self.x(0), self.y(avgSunrise))
.horizontalLineTo(self.x(times.length))
.end();
});
avg.select('path.sunset')
.transition()
.delay(150)
.duration(1500)
.attr('d', function() {
return new Path()
.moveTo(self.x(0), self.y(avgSunset))
.horizontalLineTo(self.x(times.length))
.end();
});
var format = d3.time.format('%I:%M %p');
var getTimeZone = function() {
return /\((.*)\)/.exec(new Date().toString())[1];
};
var formatHour = function(n) {
var d = new Date();
var hour = Math.floor(n);
var minutes = n - Math.floor(n);
minutes = Math.round(minutes * 60);
d.setHours(hour);
d.setMinutes(minutes);
return format(d) + ' (' + getTimeZone() + ')';
};
avg.select('text.sunrise')
.transition()
.delay(150)
.duration(1500)
.style('opacity', 1)
.attr('y', function() {
if(avgSunrise < 4) {
return self.y(avgSunrise) + 20;
}
return self.y(avgSunrise) - 7;
})
.text(function() {
return 'Average Sunrise: ' + formatHour(avgSunrise);
});
avg.select('text.sunset')
.transition()
.delay(150)
.duration(1500)
.style('opacity', 1).attr('y', function() {
if(avgSunset < 4) {
return self.y(avgSunset) + 20;
}
return self.y(avgSunset) - 7;
})
.text(function() {
return 'Average Sunset: ' + formatHour(avgSunset);
});
};
Viz.prototype._updateLine = function(i, times, today) {
var sunrise = new Date(times.sunrise);
var sunset = new Date(times.sunset);
today = today || false;
var self = this;
var group = this.svg.selectAll('g.day').filter(function(d, idx) {
return i === idx;
});
var start = self.y(sunrise.getHours() + sunrise.getMinutes() / 60);
var end = self.y(sunset.getHours() + sunset.getMinutes() / 60);
if(start < end) {
group
.select('path.day')
.transition()
.duration(1500)
.attr('d', function() {
return new Path()
.moveTo(self.x(i), start)
.verticalLineTo(end)
.end();
});
group
.select('path.day-wrap')
.transition()
.duration(1500)
.attr('d', function() {
return new Path()
.moveTo(self.x(i), self.y(24))
.verticalLineTo(self.y(24))
.end();
})
.style('stroke-width', 0);
} else {
group
.select('path.day')
.transition()
.duration(1500)
.attr('d', function() {
return new Path()
.moveTo(self.x(i), 0)
.verticalLineTo(end)
.end();
});
group
.select('path.day-wrap')
.transition()
.duration(1500)
.attr('d', function() {
return new Path()
.moveTo(self.x(i), start)
.verticalLineTo(self.y(24))
.end();
})
.style('stroke-width', (today) ? 2 : 0.5);
}
}
Viz.prototype._drawDay = function(i) {
var today = dayOfYear(new Date()) === i;
var self = this;
var group = this.svg.append('g').classed('day', true);
group
.append('path')
.attr('d', function() {
return new Path()
.moveTo(self.x(i + 0.5), self.y(11.9))
.verticalLineTo(self.y(12.1))
.end();
})
// .style('stroke-width', self.x(i+1) - self.x(i) - .5)
.style('stroke-width', function() {
if(today) {
return 2;
}
return 0.5;
})
.classed('day', true)
.classed('today', today);
group
.append('path')
.attr('d', function() {
return new Path()
.moveTo(self.x(i + 0.5), self.y(24))
.verticalLineTo(self.y(24))
.end();
})
.classed('day-wrap', true)
.classed('today', today);
};
Viz.prototype.destroy = function() {
// destroy d3 object
};
module.exports = Viz;
| mathisonian/sunrise | src/js/viz/viz.js | JavaScript | mit | 11,928 |
// All symbols in the `Runic` script as per Unicode v10.0.0:
[
'\u16A0',
'\u16A1',
'\u16A2',
'\u16A3',
'\u16A4',
'\u16A5',
'\u16A6',
'\u16A7',
'\u16A8',
'\u16A9',
'\u16AA',
'\u16AB',
'\u16AC',
'\u16AD',
'\u16AE',
'\u16AF',
'\u16B0',
'\u16B1',
'\u16B2',
'\u16B3',
'\u16B4',
'\u16B5',
'\u16B6',
'\u16B7',
'\u16B8',
'\u16B9',
'\u16BA',
'\u16BB',
'\u16BC',
'\u16BD',
'\u16BE',
'\u16BF',
'\u16C0',
'\u16C1',
'\u16C2',
'\u16C3',
'\u16C4',
'\u16C5',
'\u16C6',
'\u16C7',
'\u16C8',
'\u16C9',
'\u16CA',
'\u16CB',
'\u16CC',
'\u16CD',
'\u16CE',
'\u16CF',
'\u16D0',
'\u16D1',
'\u16D2',
'\u16D3',
'\u16D4',
'\u16D5',
'\u16D6',
'\u16D7',
'\u16D8',
'\u16D9',
'\u16DA',
'\u16DB',
'\u16DC',
'\u16DD',
'\u16DE',
'\u16DF',
'\u16E0',
'\u16E1',
'\u16E2',
'\u16E3',
'\u16E4',
'\u16E5',
'\u16E6',
'\u16E7',
'\u16E8',
'\u16E9',
'\u16EA',
'\u16EE',
'\u16EF',
'\u16F0',
'\u16F1',
'\u16F2',
'\u16F3',
'\u16F4',
'\u16F5',
'\u16F6',
'\u16F7',
'\u16F8'
]; | mathiasbynens/unicode-data | 10.0.0/scripts/Runic-symbols.js | JavaScript | mit | 1,010 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) Lewis Baker
// Licenced under MIT license. See LICENSE.txt for details.
///////////////////////////////////////////////////////////////////////////////
#ifndef CPPCORO_TESTS_COUNTED_HPP_INCLUDED
#define CPPCORO_TESTS_COUNTED_HPP_INCLUDED
struct counted
{
static int default_construction_count;
static int copy_construction_count;
static int move_construction_count;
static int destruction_count;
int id;
static void reset_counts()
{
default_construction_count = 0;
copy_construction_count = 0;
move_construction_count = 0;
destruction_count = 0;
}
static int construction_count()
{
return default_construction_count + copy_construction_count + move_construction_count;
}
static int active_count()
{
return construction_count() - destruction_count;
}
counted() : id(default_construction_count++) {}
counted(const counted& other) : id(other.id) { ++copy_construction_count; }
counted(counted&& other) : id(other.id) { ++move_construction_count; other.id = -1; }
~counted() { ++destruction_count; }
};
#endif
| lewissbaker/cppcoro | test/counted.hpp | C++ | mit | 1,141 |
#! /usr/bin/python
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 27 18:31:59 2017
@author: katsuya.ishiyama
"""
from numpy import random
# Definition of module level constants
SUCCESS_CODE = 1
FAILURE_CODE = 0
class Strategy():
def __init__(self, n):
_success_probability = _generate_success_probability(n)
_strategy = {i: p for i, p in enumerate(_success_probability, 1)}
self._n = n
self.strategy = _strategy
self.stock_of_strategy = list(_strategy.keys())
self.tried_strategy = []
self.current_strategy = None
self.previous_strategy = None
self.count_same_strategy = 0
self._result_of_trial = None
def choose_strategy(self):
if not self.stock_of_strategy:
raise ValueError('There is no strategy in stock.')
_chosen_id = random.choice(self.stock_of_strategy, 1)[0]
self.previous_strategy = self.current_strategy
self.current_strategy = _chosen_id
self.count_same_strategy = 0
self.stock_of_strategy.remove(_chosen_id)
_chosen_strategy = {
'chosen_strategy': _chosen_id,
'success_probability': self._get_success_probability()
}
return _chosen_strategy
def _get_success_probability(self):
return self.strategy[self.current_strategy]
def try_strategy(self):
if not self.current_strategy:
raise ValueError('No strategy is chosen.')
self.tried_strategy.append(self.current_strategy)
self._result_of_trial = _get_trial_result(
p=self._get_success_probability()
)
if self.current_strategy == self.previous_strategy:
self.count_same_strategy += 1
return self._result_of_trial
def _get_trial_result(p):
_trial_result = random.choice([FAILURE_CODE, SUCCESS_CODE], size=1, p=[1 - p, p])
return _trial_result[0]
def _generate_success_probability(size):
return random.sample(size)
| Katsuya-Ishiyama/simulation | strategy/strategy.py | Python | mit | 2,013 |
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Eloquent\SoftDeletes;
class CreateImagesTable extends Migration
{
//use SoftDeletes;
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('images', function (Blueprint $table) {
$table->increments('id');
$table->string('type', 50);
$table->string('filename', 500);
$table->integer('signup_id');
$table->timestamps();
//$table->softDeletes();
$table->foreign('signup_id')->references('id')->on('signups');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('images');
}
}
| timitek/GetRealTLanding | database/migrations/2017_10_24_142738_create_images_table.php | PHP | mit | 908 |
package de.v13dev.designpatterns.util;
import java.util.List;
/**
* Created by stebo on 22.03.17.
*/
public class TestHelper {
public static boolean isSortedAscending(List<Integer> list) {
if(list.size() < 2) return true;
for(int i = 1; i < list.size(); i++) {
if(list.get(i - 1) > list.get(i)) {
return false;
}
}
return true;
}
public static boolean isSortedDescending(List<Integer> list) {
if(list.size() < 2) return true;
for(int i = 1; i < list.size(); i++) {
if(list.get(i - 1) < list.get(i)) {
return false;
}
}
return true;
}
}
| ste-bo/designpatterns | src/test/java/de/v13dev/designpatterns/util/TestHelper.java | Java | mit | 705 |
import { FormGroup } from '@angular/forms';
export class PasswordMatchValidator {
static validate(passwordFormGroup: FormGroup) {
const password = passwordFormGroup.controls.password.value;
const repeatPassword =
passwordFormGroup.controls.password_confirmation.value;
if (repeatPassword.length <= 0) {
return null;
}
if (repeatPassword !== password) {
return {
doesMatchPassword: true
};
}
return null;
}
}
| aviabird/angularspree | src/app/shared/custom-validator/password-match-validator.ts | TypeScript | mit | 475 |
<?php
namespace DTR\CrawlerBundle\Services\Crawler;
use DTR\CrawlerBundle\Services\Algorithms\PatternIdentifierInterface;
use DTR\CrawlerBundle\Services\Inspectors\ComponentInspector;
use Symfony\Component\DomCrawler\Crawler;
class MenuCrawler implements CrawlerInterface
{
/**
* @var ComponentInspector
*/
private $component_inspector;
/**
* @var PatternIdentifierInterface
*/
private $pattern;
/**
* @param ComponentInspector $component_inspector
*/
public function __construct(ComponentInspector $component_inspector)
{
$this->component_inspector = $component_inspector;
}
/**
* @param PatternIdentifierInterface $pattern
* @return CrawlerInterface
*/
public function setPattern(PatternIdentifierInterface $pattern)
{
$this->pattern = $pattern;
return $this;
}
/**
* @param $url
* @return array
*/
public function getMenu($url)
{
$contents = $this->chewUrl($url);
$crawler = new Crawler($contents);
$product_html = $this->pattern->getProductHtmlCollection($crawler);
$products = array();
foreach($product_html as $product_dom)
{
$collection = $this->getProductValues($product_dom);
foreach($collection as $product)
$products[] = $product;
}
$logo = $this->getLogo($crawler->filter('body'));
if(empty($logo))
$logo = $products[0]['image'];
return [
'logo' => $logo,
'products' => $products
];
}
/**
* @param Crawler $body
* @return string
*/
public function getLogo(Crawler $body)
{
$all_elements = $body->filter('*')->slice(1);
foreach($all_elements as $element)
{
if($element->hasAttributes())
{
$attr_str = '';
foreach($element->attributes as $attr)
$attr_str .= $attr->nodeName. ' '. $attr->nodeValue. ' ';
if(preg_match_all('/logo/i', $attr_str) > 0)
{
$element = new Crawler($element);
$element = $element->filter('img');
if($element->getNode(0) != null)
return $this->component_inspector->getSource($element);
}
}
}
return '';
/*$all_elements = $all_elements->reduce(function(Crawler $element) {
$classes = $element->extract([ 'class' ]);
if(empty($classes[0]))
return false;
if(preg_match_all('/logo/i', $classes[0]) == 0)
return false;
$image = $element->filter('img');
if($image->getNode(0) == null)
return false;
return true;
});
$logo = '';
if($all_elements->getNode(0) != null)
$logo = $this->component_inspector->getSource($all_elements->first());
return $logo;*/
}
/**
* @param Crawler $product_dom
* @return array
*/
public function getProductValues(Crawler $product_dom)
{
$image = $this->component_inspector->getImage($product_dom);
$title = $this->component_inspector->getTitle($product_dom);
$description = $this->component_inspector->getDescription($product_dom);
list($blocks, $prices) = $this->component_inspector->getPriceInfo($product_dom);
$price_count = count($prices);
$values = array();
if($price_count == 1)
{
$values[] = [
'image' => $image,
'title' => $title,
'description' => $description,
'price' => $this->component_inspector->getPriceFormat($prices[0])
];
}
else
{
for($p = 0; $p != $price_count; ++$p)
{
$diff = $this->component_inspector->getPriceDifferences($blocks[$p], $prices, $prices[$p]);
$price = $this->component_inspector->getPriceFormat($prices[$p]);
$values[] = [
'image' => $image,
'title' => $diff. ' '. $title,
'description' => $description,
'price' => $price
];
}
}
return $values;
}
/**
* @param string $url
* @return string
*/
public function chewUrl($url)
{
$url_parts = parse_url($url);
$base_url = $url_parts['scheme']. '://'. $url_parts['host'];
$this->component_inspector->setBaseUrl($base_url);
return $this->getUrlContents($url);
}
/**
* @param $url string
* @return string
*/
public function getUrlContents($url)
{
$curl_handle=curl_init();
curl_setopt($curl_handle, CURLOPT_URL, $url);
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
$contents = curl_exec($curl_handle);
curl_close($curl_handle);
return ($contents === FALSE) ? $this->getUrlContents($url) : $contents;
}
} | nfqakademija/dydis-turi-reiksme | src/DTR/CrawlerBundle/Services/Crawler/MenuCrawler.php | PHP | mit | 5,270 |
module Effective
module Providers
module Free
extend ActiveSupport::Concern
def free
raise('free provider is not available') unless EffectiveOrders.free?
@order ||= Order.find(params[:id])
EffectiveResources.authorize!(self, :update, @order)
unless @order.free?
flash[:danger] = 'Unable to process free order with a non-zero total'
redirect_to effective_orders.order_path(@order)
return
end
order_purchased(
payment: 'free order. no payment required.',
provider: 'free',
card: 'none',
purchased_url: free_params[:purchased_url]
)
end
def free_params
params.require(:free).permit(:purchased_url, :declined_url)
end
end
end
end
| code-and-effect/effective_orders | app/controllers/effective/providers/free.rb | Ruby | mit | 809 |
package fr.aumgn.bukkitutils.geom;
import fr.aumgn.bukkitutils.geom.direction.VectorDirection;
import fr.aumgn.bukkitutils.geom.vector.VectorIterator;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import java.util.Iterator;
/**
* Immutable Vector class.
* Inspired from WorldEdit.
*/
public class Vector implements Iterable<Vector> {
private final double x, y, z;
public Vector() {
this.x = 0;
this.y = 0;
this.z = 0;
}
public Vector(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public Vector(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
public Vector(Location loc) {
this(loc.getX(), loc.getY(), loc.getZ());
}
public Vector(Entity entity) {
this(entity.getLocation());
}
public Vector(Block block) {
this(block.getX(), block.getY(), block.getZ());
}
public double getX() {
return x;
}
public Vector setX(double x) {
return new Vector(x, y, z);
}
public int getBlockX() {
return (int) Math.round(x);
}
public double getY() {
return y;
}
public Vector setY(double y) {
return new Vector(x, y, z);
}
public int getBlockY() {
return (int) Math.round(y);
}
public double getZ() {
return z;
}
public Vector setZ(double z) {
return new Vector(x, y, z);
}
public int getBlockZ() {
return (int) Math.round(z);
}
public Vector add(double i) {
return new Vector(this.x + i, this.y + i, this.z + i);
}
public Vector add(double ox, double oy, double oz) {
return new Vector(x + ox, y + oy, z + oz);
}
public Vector add(Vector other) {
return new Vector(x + other.x, y + other.y, z + other.z);
}
public Vector addX(double ox) {
return new Vector(x + ox, y, z);
}
public Vector addY(double oy) {
return new Vector(x, y + oy, z);
}
public Vector addZ(double oz) {
return new Vector(x, y, z + oz);
}
public Vector subtract(double i) {
return new Vector(x - i, y - i, z - i);
}
public Vector subtract(double ox, double oy, double oz) {
return new Vector(x - ox, y - oy, z - oz);
}
public Vector subtract(Vector other) {
return new Vector(x - other.x, y - other.y, z - other.z);
}
public Vector subtractX(double ox) {
return new Vector(x - ox, y, z);
}
public Vector subtractY(double oy) {
return new Vector(x, y - oy, z);
}
public Vector subtractZ(double oz) {
return new Vector(x, y, z - oz);
}
public Vector multiply(double i) {
return new Vector(x * i, y * i, z * i);
}
public Vector multiply(double ox, double oy, double oz) {
return new Vector(x * ox, y * oy, z * oz);
}
public Vector multiply(Vector other) {
return new Vector(x * other.x, y * other.y, z * other.z);
}
public Vector divide(double i) {
return new Vector(x / i, y / i, z / i);
}
public Vector divide(double ox, double oy, double oz) {
return new Vector(x / ox, y / oy, z / oz);
}
public Vector divide(Vector other) {
return new Vector(x / other.x, y / other.y, z / other.z);
}
public Vector getMiddle(Vector other) {
return new Vector(
(x + other.x) / 2,
(y + other.y) / 2,
(z + other.z) / 2);
}
public boolean isInside(Vector min, Vector max) {
return x >= min.x && x <= max.x
&& y >= min.y && y <= max.y
&& z >= min.z && z <= max.z;
}
public boolean isZero() {
return x == 0.0 && y == 0.0 && z == 0;
}
public Vector positive() {
return new Vector(Math.abs(x), Math.abs(y), Math.abs(z));
}
public double lengthSq() {
return x * x + y * y + z * z;
}
public double length() {
return Math.sqrt(lengthSq());
}
public double distanceSq(Vector other) {
return subtract(other).lengthSq();
}
public double distance(Vector other) {
return subtract(other).length();
}
public Vector normalize() {
return divide(length());
}
public Vector2D to2D() {
return new Vector2D(x, z);
}
public Block toBlock(World world) {
return world.getBlockAt(getBlockX(), getBlockY(), getBlockZ());
}
public Direction toDirection() {
if (isZero()) {
return Direction.NONE;
}
return new VectorDirection(this);
}
public Direction towards(Vector to) {
return to.subtract(this).toDirection();
}
public org.bukkit.util.Vector toBukkit() {
return new org.bukkit.util.Vector(x, y, z);
}
public Location toLocation(World world) {
return toLocation(world, 0.0f, 0.0f);
}
public Location toLocation(World world, Vector2D direction) {
return toLocation(world, direction.toDirection());
}
public Location toLocation(World world, Direction dir) {
return toLocation(world, dir.getYaw(), dir.getPitch());
}
public Location toLocation(World world, float yaw, float pitch) {
return new Location(world, x, getBlockY() + 0.1, z, yaw, pitch);
}
@Override
public Iterator<Vector> iterator() {
return new VectorIterator(new Vector(), this);
}
public Iterable<Vector> rectangle(final Vector max) {
return new Iterable<Vector>() {
@Override
public Iterator<Vector> iterator() {
return new VectorIterator(Vector.this, max);
}
};
}
@Override
public String toString() {
return "(" + x + ", " + y + ", " + z + ")";
}
@Override
public int hashCode() {
return new HashCodeBuilder(23, 11)
.append(x)
.append(y)
.append(z)
.toHashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Vector)) {
return false;
}
Vector o = (Vector) obj;
return x == o.x && y == o.y && z == o.z;
}
public boolean equalsBlock(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Vector)) {
return false;
}
Vector other = (Vector) obj;
return getBlockX() == other.getBlockX()
&& getBlockY() == other.getBlockY()
&& getBlockZ() == other.getBlockZ();
}
}
| aumgn/BukkitUtils | src/main/java/fr/aumgn/bukkitutils/geom/Vector.java | Java | mit | 6,906 |
/**
* Central storage with in-memory cache
*/
const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');
const app = process.type === 'renderer'
? require('electron').remote.app
: require('electron').app;
const _defaultDir = path.join(app.getPath('userData'), 'data');
const _storage = {};
function getPath(options) {
if(options.prefix) {
return path.join(_defaultDir, options.prefix, options.fileName);
}
return path.join(_defaultDir, options.fileName);
}
function ensureDirectoryExists(dir) {
if (!fs.existsSync(dir)){
mkdirp.sync(dir);
}
}
function ensurePrefixExists(prefix) {
ensureDirectoryExists(path.join(_defaultDir, prefix));
}
ensureDirectoryExists(_defaultDir);
const Storage = {};
Storage.set = function(options, callback) {
if(options.prefix) {
ensurePrefixExists(options.prefix);
}
const file = getPath(options);
_storage[file] = options.value;
fs.writeFile(file, options.value, callback);
};
Storage.get = function(options, callback) {
const file = getPath(options);
if(file in _storage) {
callback(null, _storage[file]);
return;
}
fs.readFile(file, callback);
};
Storage.append = function(options, callback) {
if(options.prefix) {
ensurePrefixExists(options.prefix);
}
const file = getPath(options);
if(!(file in _storage)) {
_storage[file] = [];
}
_storage[file].push(options.value);
fs.appendFile(file, options.value, callback);
};
Storage.delete = function(options, callback) {
const file = getPath(options);
delete _storage[file];
fs.unlink(file, callback);
};
module.exports = Storage;
| scholtzm/punk | src/utils/storage.js | JavaScript | mit | 1,642 |
<?php
class HtmlTest extends \Codeception\TestCase\Test
{
/**
* @var \CodeGuy
*/
protected $codeGuy;
public function testSend()
{
$instance = new \Hahns\Response\Html();
$response = $instance->send('<h1>hello world</h1>');
$this->assertEquals('<h1>hello world</h1>', $response);
$response = $instance->send('');
$this->assertEquals('', $response);
try {
$instance->send([]);
$this->fail();
} catch (InvalidArgumentException $e) { }
try {
$instance->send('', 'as');
$this->fail();
} catch (InvalidArgumentException $e) { }
}
} | pklink/Hahns | tests/unit/Response/HtmlTest.php | PHP | mit | 680 |
require 'spec_helper'
describe AdminsController do
describe 'attempting to access the admin dashboard when not logged in' do
before :each do
get :index, {:id => 2}
end
it 'should redirect to the login page' do
response.should be_redirect
response.should redirect_to('/login')
end
end
end
| Berkeley-BCEF/IntakeApp | spec/controllers/admin_controller_spec.rb | Ruby | mit | 343 |
<?php
header("Access-Control-Allow-Origin:*");
?>
<html>
<head>
<title>TESTS AJAX</title>
<style type="text/css">
.bouton,.obj_prec{
margin-left:4px;
color:blue;
font-size:14px;
font-weight:bold;
cursor:pointer;
}
.bouton:hover{
color:#ccc;
}
#log{
border:1px solid red;
background-color:pink;
}
</style>
<script src="http://code.jquery.com/jquery.js"></script>
<script>
function recreer_liste(){
$( "p#result" ).hide( 200, function() {
$( "p#result" ).html('');
afficher();
});
}
function afficher(){
$.ajax({
type:"GET",
url:"http://sfrest.local/app_dev.php/notes.json",
contentType:"text/plain",
dataType:"json",
cache:false,
data:{limit:$("#nb_mess").val()},
success:function(data,status,jqXHR){
showData2(data);
},
error: function (jqXHR,status) {
messager(status,'Affichage Erreur');
}
});
}
function showData2(data){ // de benjamin
messager(data,'Affichage OK');
$("p#result").append($("<ul>"));
$.each(data.notes,function(i,item){
$("p#result ul").append($('<li>'+item.message+' ('+i+')<span num="'+i+'" class="bouton item">Supprimer</span></li>'));
});
$("p#result").show(400);
$(".item").click(function() {
//alert($(this).attr('num'));
remover($(this).attr('num'));
});
}
function remover(n){
$.ajax({
type:"GET",
url:'http://sfrest.local/app_dev.php/notes/'+n+'/remove',
contentType:"text/plain",
dataType:"json",
data:{id:n},
success:function(result){
messager(result,'Suppr OK');
},
error: function (jqXHR,status) {
messager(status + JSON.stringify(jqXHR),'Suppr Erreur');
}
});
recreer_liste();
//setTimeout(recreer_liste,2000);
}
function ajouter(m){
$.ajax({
type: "POST",
url: "http://sfrest.local/app_dev.php/notes.json",
data: {'note[message]':m},
dataType: "json",
success:function(result,status,jqXHR){
messager(result,'Ajout OK');
messager(jqXHR,'Ajout OK');
},
error: function (jqXHR,status) {
messager(status + JSON.stringify(jqXHR),'Ajout Erreur');
}
});
recreer_liste();
}
function messager(mess,quoi){
if(typeof(mess)=='object'){
mess = JSON.stringify(mess);
c = '<div class="obj_prec">Objet</div>';
c += '<div style="display:none">'+mess+'</div>';
$("#log").html(c + $("#log").html());
}else{
$("#log").html(mess+'<br>'+$("#log").html());
}
d = new Date();
dts = d.getHours()+':'+d.getMinutes()+':'+d.getSeconds();
$("#log").html('['+dts+'] '+$("#log").html());
if(quoi!=undefined){
$("#log").html(quoi+' : '+$("#log").html());
}
$(".obj_prec").click(function() {
$(this).next().toggle();
});
}
$(document).ready(function(){
$("#envoie").click(function() {
ajouter($("#message").val());
});
$("#rafraichir").click(function() {
recreer_liste();
});
afficher();
});
</script>
</head>
<body>
<div id="menus">
Afficher : <input type="text" id="nb_mess" value="10" style="width:30px;"> <span id="rafraichir" class="bouton">Rafraichir</span>
<br><br><input type="text" id="message"> <span id="envoie" class="bouton">Ajouter</span>
</div>
<div id="conteneur" style="min-height:400px;">
<p id="result"></p>
</div>
<div id="log">
</div>
</body>
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
| jc-miralles/WebSymfony | web/tests_ajax.php | PHP | mit | 4,802 |
<?php
namespace Nemundo\Package\FontAwesome\Icon;
use Nemundo\Package\FontAwesome\AbstractFontAwesomeIcon;
class TrashIcon extends AbstractFontAwesomeIcon
{
public function getContent()
{
$this->icon = 'trash';
return parent::getContent();
}
} | nemundo/framework | src/Package/FontAwesome/Icon/TrashIcon.php | PHP | mit | 278 |
import { Component, Input } from '@angular/core';
import { Character } from '../../../data/models/character';
import { LinkLocation } from '../../directive/insertLinks/insertLinks.directive';
@Component({
selector: 'lc-character',
templateUrl: 'character.component.html',
styleUrls: [ 'character.component.scss' ],
})
export class CharacterComponent {
@Input() public excludeLinks: LinkLocation[];
@Input() public character: Character;
}
| manuelhuber/LostColonies | src/app/components/character/character.component.ts | TypeScript | mit | 450 |
// Copyright (c) 2011-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "coincontroldialog.h"
#include "ui_coincontroldialog.h"
#include "addresstablemodel.h"
#include "bitcoinunits.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include "platformstyle.h"
#include "txmempool.h"
#include "walletmodel.h"
#include "wallet/coincontrol.h"
#include "init.h"
#include "policy/fees.h"
#include "policy/policy.h"
#include "validation.h" // For mempool
#include "wallet/fees.h"
#include "wallet/wallet.h"
#include <QApplication>
#include <QCheckBox>
#include <QCursor>
#include <QDialogButtonBox>
#include <QFlags>
#include <QIcon>
#include <QSettings>
#include <QString>
#include <QTreeWidget>
#include <QTreeWidgetItem>
QList<CAmount> CoinControlDialog::payAmounts;
CCoinControl* CoinControlDialog::coinControl = new CCoinControl();
bool CoinControlDialog::fSubtractFeeFromAmount = false;
bool CCoinControlWidgetItem::operator<(const QTreeWidgetItem &other) const {
int column = treeWidget()->sortColumn();
if (column == CoinControlDialog::COLUMN_AMOUNT || column == CoinControlDialog::COLUMN_DATE || column == CoinControlDialog::COLUMN_CONFIRMATIONS)
return data(column, Qt::UserRole).toLongLong() < other.data(column, Qt::UserRole).toLongLong();
return QTreeWidgetItem::operator<(other);
}
CoinControlDialog::CoinControlDialog(const PlatformStyle *_platformStyle, QWidget *parent) :
QDialog(parent),
ui(new Ui::CoinControlDialog),
model(0),
platformStyle(_platformStyle)
{
ui->setupUi(this);
// context menu actions
QAction *copyAddressAction = new QAction(tr("Copy address"), this);
QAction *copyLabelAction = new QAction(tr("Copy label"), this);
QAction *copyAmountAction = new QAction(tr("Copy amount"), this);
copyTransactionHashAction = new QAction(tr("Copy transaction ID"), this); // we need to enable/disable this
lockAction = new QAction(tr("Lock unspent"), this); // we need to enable/disable this
unlockAction = new QAction(tr("Unlock unspent"), this); // we need to enable/disable this
// context menu
contextMenu = new QMenu(this);
contextMenu->addAction(copyAddressAction);
contextMenu->addAction(copyLabelAction);
contextMenu->addAction(copyAmountAction);
contextMenu->addAction(copyTransactionHashAction);
contextMenu->addSeparator();
contextMenu->addAction(lockAction);
contextMenu->addAction(unlockAction);
// context menu signals
connect(ui->treeWidget, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showMenu(QPoint)));
connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(copyAddress()));
connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(copyLabel()));
connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount()));
connect(copyTransactionHashAction, SIGNAL(triggered()), this, SLOT(copyTransactionHash()));
connect(lockAction, SIGNAL(triggered()), this, SLOT(lockCoin()));
connect(unlockAction, SIGNAL(triggered()), this, SLOT(unlockCoin()));
// clipboard actions
QAction *clipboardQuantityAction = new QAction(tr("Copy quantity"), this);
QAction *clipboardAmountAction = new QAction(tr("Copy amount"), this);
QAction *clipboardFeeAction = new QAction(tr("Copy fee"), this);
QAction *clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this);
QAction *clipboardBytesAction = new QAction(tr("Copy bytes"), this);
QAction *clipboardLowOutputAction = new QAction(tr("Copy dust"), this);
QAction *clipboardChangeAction = new QAction(tr("Copy change"), this);
connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(clipboardQuantity()));
connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(clipboardAmount()));
connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(clipboardFee()));
connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(clipboardAfterFee()));
connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(clipboardBytes()));
connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(clipboardLowOutput()));
connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(clipboardChange()));
ui->labelCoinControlQuantity->addAction(clipboardQuantityAction);
ui->labelCoinControlAmount->addAction(clipboardAmountAction);
ui->labelCoinControlFee->addAction(clipboardFeeAction);
ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction);
ui->labelCoinControlBytes->addAction(clipboardBytesAction);
ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction);
ui->labelCoinControlChange->addAction(clipboardChangeAction);
// toggle tree/list mode
connect(ui->radioTreeMode, SIGNAL(toggled(bool)), this, SLOT(radioTreeMode(bool)));
connect(ui->radioListMode, SIGNAL(toggled(bool)), this, SLOT(radioListMode(bool)));
// click on checkbox
connect(ui->treeWidget, SIGNAL(itemChanged(QTreeWidgetItem*, int)), this, SLOT(viewItemChanged(QTreeWidgetItem*, int)));
// click on header
#if QT_VERSION < 0x050000
ui->treeWidget->header()->setClickable(true);
#else
ui->treeWidget->header()->setSectionsClickable(true);
#endif
connect(ui->treeWidget->header(), SIGNAL(sectionClicked(int)), this, SLOT(headerSectionClicked(int)));
// ok button
connect(ui->buttonBox, SIGNAL(clicked( QAbstractButton*)), this, SLOT(buttonBoxClicked(QAbstractButton*)));
// (un)select all
connect(ui->pushButtonSelectAll, SIGNAL(clicked()), this, SLOT(buttonSelectAllClicked()));
// change coin control first column label due Qt4 bug.
// see https://github.com/bitcoin/bitcoin/issues/5716
ui->treeWidget->headerItem()->setText(COLUMN_CHECKBOX, QString());
ui->treeWidget->setColumnWidth(COLUMN_CHECKBOX, 84);
ui->treeWidget->setColumnWidth(COLUMN_AMOUNT, 110);
ui->treeWidget->setColumnWidth(COLUMN_LABEL, 190);
ui->treeWidget->setColumnWidth(COLUMN_ADDRESS, 320);
ui->treeWidget->setColumnWidth(COLUMN_DATE, 130);
ui->treeWidget->setColumnWidth(COLUMN_CONFIRMATIONS, 110);
ui->treeWidget->setColumnHidden(COLUMN_TXHASH, true); // store transaction hash in this column, but don't show it
ui->treeWidget->setColumnHidden(COLUMN_VOUT_INDEX, true); // store vout index in this column, but don't show it
// default view is sorted by amount desc
sortView(COLUMN_AMOUNT, Qt::DescendingOrder);
// restore list mode and sortorder as a convenience feature
QSettings settings;
if (settings.contains("nCoinControlMode") && !settings.value("nCoinControlMode").toBool())
ui->radioTreeMode->click();
if (settings.contains("nCoinControlSortColumn") && settings.contains("nCoinControlSortOrder"))
sortView(settings.value("nCoinControlSortColumn").toInt(), ((Qt::SortOrder)settings.value("nCoinControlSortOrder").toInt()));
}
CoinControlDialog::~CoinControlDialog()
{
QSettings settings;
settings.setValue("nCoinControlMode", ui->radioListMode->isChecked());
settings.setValue("nCoinControlSortColumn", sortColumn);
settings.setValue("nCoinControlSortOrder", (int)sortOrder);
delete ui;
}
void CoinControlDialog::setModel(WalletModel *_model)
{
this->model = _model;
if(_model && _model->getOptionsModel() && _model->getAddressTableModel())
{
updateView();
updateLabelLocked();
CoinControlDialog::updateLabels(_model, this);
}
}
// ok button
void CoinControlDialog::buttonBoxClicked(QAbstractButton* button)
{
if (ui->buttonBox->buttonRole(button) == QDialogButtonBox::AcceptRole)
done(QDialog::Accepted); // closes the dialog
}
// (un)select all
void CoinControlDialog::buttonSelectAllClicked()
{
Qt::CheckState state = Qt::Checked;
for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++)
{
if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) != Qt::Unchecked)
{
state = Qt::Unchecked;
break;
}
}
ui->treeWidget->setEnabled(false);
for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++)
if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) != state)
ui->treeWidget->topLevelItem(i)->setCheckState(COLUMN_CHECKBOX, state);
ui->treeWidget->setEnabled(true);
if (state == Qt::Unchecked)
coinControl->UnSelectAll(); // just to be sure
CoinControlDialog::updateLabels(model, this);
}
// context menu
void CoinControlDialog::showMenu(const QPoint &point)
{
QTreeWidgetItem *item = ui->treeWidget->itemAt(point);
if(item)
{
contextMenuItem = item;
// disable some items (like Copy Transaction ID, lock, unlock) for tree roots in context menu
if (item->text(COLUMN_TXHASH).length() == 64) // transaction hash is 64 characters (this means its a child node, so its not a parent node in tree mode)
{
copyTransactionHashAction->setEnabled(true);
if (model->isLockedCoin(uint256S(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt()))
{
lockAction->setEnabled(false);
unlockAction->setEnabled(true);
}
else
{
lockAction->setEnabled(true);
unlockAction->setEnabled(false);
}
}
else // this means click on parent node in tree mode -> disable all
{
copyTransactionHashAction->setEnabled(false);
lockAction->setEnabled(false);
unlockAction->setEnabled(false);
}
// show context menu
contextMenu->exec(QCursor::pos());
}
}
// context menu action: copy amount
void CoinControlDialog::copyAmount()
{
GUIUtil::setClipboard(BitcoinUnits::removeSpaces(contextMenuItem->text(COLUMN_AMOUNT)));
}
// context menu action: copy label
void CoinControlDialog::copyLabel()
{
if (ui->radioTreeMode->isChecked() && contextMenuItem->text(COLUMN_LABEL).length() == 0 && contextMenuItem->parent())
GUIUtil::setClipboard(contextMenuItem->parent()->text(COLUMN_LABEL));
else
GUIUtil::setClipboard(contextMenuItem->text(COLUMN_LABEL));
}
// context menu action: copy address
void CoinControlDialog::copyAddress()
{
if (ui->radioTreeMode->isChecked() && contextMenuItem->text(COLUMN_ADDRESS).length() == 0 && contextMenuItem->parent())
GUIUtil::setClipboard(contextMenuItem->parent()->text(COLUMN_ADDRESS));
else
GUIUtil::setClipboard(contextMenuItem->text(COLUMN_ADDRESS));
}
// context menu action: copy transaction id
void CoinControlDialog::copyTransactionHash()
{
GUIUtil::setClipboard(contextMenuItem->text(COLUMN_TXHASH));
}
// context menu action: lock coin
void CoinControlDialog::lockCoin()
{
if (contextMenuItem->checkState(COLUMN_CHECKBOX) == Qt::Checked)
contextMenuItem->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked);
COutPoint outpt(uint256S(contextMenuItem->text(COLUMN_TXHASH).toStdString()), contextMenuItem->text(COLUMN_VOUT_INDEX).toUInt());
model->lockCoin(outpt);
contextMenuItem->setDisabled(true);
contextMenuItem->setIcon(COLUMN_CHECKBOX, platformStyle->SingleColorIcon(":/icons/lock_closed"));
updateLabelLocked();
}
// context menu action: unlock coin
void CoinControlDialog::unlockCoin()
{
COutPoint outpt(uint256S(contextMenuItem->text(COLUMN_TXHASH).toStdString()), contextMenuItem->text(COLUMN_VOUT_INDEX).toUInt());
model->unlockCoin(outpt);
contextMenuItem->setDisabled(false);
contextMenuItem->setIcon(COLUMN_CHECKBOX, QIcon());
updateLabelLocked();
}
// copy label "Quantity" to clipboard
void CoinControlDialog::clipboardQuantity()
{
GUIUtil::setClipboard(ui->labelCoinControlQuantity->text());
}
// copy label "Amount" to clipboard
void CoinControlDialog::clipboardAmount()
{
GUIUtil::setClipboard(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" ")));
}
// copy label "Fee" to clipboard
void CoinControlDialog::clipboardFee()
{
GUIUtil::setClipboard(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(" ")).replace(ASYMP_UTF8, ""));
}
// copy label "After fee" to clipboard
void CoinControlDialog::clipboardAfterFee()
{
GUIUtil::setClipboard(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" ")).replace(ASYMP_UTF8, ""));
}
// copy label "Bytes" to clipboard
void CoinControlDialog::clipboardBytes()
{
GUIUtil::setClipboard(ui->labelCoinControlBytes->text().replace(ASYMP_UTF8, ""));
}
// copy label "Dust" to clipboard
void CoinControlDialog::clipboardLowOutput()
{
GUIUtil::setClipboard(ui->labelCoinControlLowOutput->text());
}
// copy label "Change" to clipboard
void CoinControlDialog::clipboardChange()
{
GUIUtil::setClipboard(ui->labelCoinControlChange->text().left(ui->labelCoinControlChange->text().indexOf(" ")).replace(ASYMP_UTF8, ""));
}
// treeview: sort
void CoinControlDialog::sortView(int column, Qt::SortOrder order)
{
sortColumn = column;
sortOrder = order;
ui->treeWidget->sortItems(column, order);
ui->treeWidget->header()->setSortIndicator(sortColumn, sortOrder);
}
// treeview: clicked on header
void CoinControlDialog::headerSectionClicked(int logicalIndex)
{
if (logicalIndex == COLUMN_CHECKBOX) // click on most left column -> do nothing
{
ui->treeWidget->header()->setSortIndicator(sortColumn, sortOrder);
}
else
{
if (sortColumn == logicalIndex)
sortOrder = ((sortOrder == Qt::AscendingOrder) ? Qt::DescendingOrder : Qt::AscendingOrder);
else
{
sortColumn = logicalIndex;
sortOrder = ((sortColumn == COLUMN_LABEL || sortColumn == COLUMN_ADDRESS) ? Qt::AscendingOrder : Qt::DescendingOrder); // if label or address then default => asc, else default => desc
}
sortView(sortColumn, sortOrder);
}
}
// toggle tree mode
void CoinControlDialog::radioTreeMode(bool checked)
{
if (checked && model)
updateView();
}
// toggle list mode
void CoinControlDialog::radioListMode(bool checked)
{
if (checked && model)
updateView();
}
// checkbox clicked by user
void CoinControlDialog::viewItemChanged(QTreeWidgetItem* item, int column)
{
if (column == COLUMN_CHECKBOX && item->text(COLUMN_TXHASH).length() == 64) // transaction hash is 64 characters (this means its a child node, so its not a parent node in tree mode)
{
COutPoint outpt(uint256S(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt());
if (item->checkState(COLUMN_CHECKBOX) == Qt::Unchecked)
coinControl->UnSelect(outpt);
else if (item->isDisabled()) // locked (this happens if "check all" through parent node)
item->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked);
else
coinControl->Select(outpt);
// selection changed -> update labels
if (ui->treeWidget->isEnabled()) // do not update on every click for (un)select all
CoinControlDialog::updateLabels(model, this);
}
// TODO: Remove this temporary qt5 fix after Qt5.3 and Qt5.4 are no longer used.
// Fixed in Qt5.5 and above: https://bugreports.qt.io/browse/QTBUG-43473
#if QT_VERSION >= 0x050000
else if (column == COLUMN_CHECKBOX && item->childCount() > 0)
{
if (item->checkState(COLUMN_CHECKBOX) == Qt::PartiallyChecked && item->child(0)->checkState(COLUMN_CHECKBOX) == Qt::PartiallyChecked)
item->setCheckState(COLUMN_CHECKBOX, Qt::Checked);
}
#endif
}
// shows count of locked unspent outputs
void CoinControlDialog::updateLabelLocked()
{
std::vector<COutPoint> vOutpts;
model->listLockedCoins(vOutpts);
if (vOutpts.size() > 0)
{
ui->labelLocked->setText(tr("(%1 locked)").arg(vOutpts.size()));
ui->labelLocked->setVisible(true);
}
else ui->labelLocked->setVisible(false);
}
void CoinControlDialog::updateLabels(WalletModel *model, QDialog* dialog)
{
if (!model)
return;
// nPayAmount
CAmount nPayAmount = 0;
bool fDust = false;
CMutableTransaction txDummy;
for (const CAmount &amount : CoinControlDialog::payAmounts)
{
nPayAmount += amount;
if (amount > 0)
{
CTxOut txout(amount, (CScript)std::vector<unsigned char>(24, 0));
txDummy.vout.push_back(txout);
fDust |= IsDust(txout, ::dustRelayFee);
}
}
CAmount nAmount = 0;
CAmount nPayFee = 0;
CAmount nAfterFee = 0;
CAmount nChange = 0;
unsigned int nBytes = 0;
unsigned int nBytesInputs = 0;
unsigned int nQuantity = 0;
bool fWitness = false;
std::vector<COutPoint> vCoinControl;
std::vector<COutput> vOutputs;
coinControl->ListSelected(vCoinControl);
model->getOutputs(vCoinControl, vOutputs);
for (const COutput& out : vOutputs) {
// unselect already spent, very unlikely scenario, this could happen
// when selected are spent elsewhere, like rpc or another computer
uint256 txhash = out.tx->GetHash();
COutPoint outpt(txhash, out.i);
if (model->isSpent(outpt))
{
coinControl->UnSelect(outpt);
continue;
}
// Quantity
nQuantity++;
// Amount
nAmount += out.tx->tx->vout[out.i].nValue;
// Bytes
CTxDestination address;
int witnessversion = 0;
std::vector<unsigned char> witnessprogram;
if (out.tx->tx->vout[out.i].scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram))
{
nBytesInputs += (32 + 4 + 1 + (107 / WITNESS_SCALE_FACTOR) + 4);
fWitness = true;
}
else if(ExtractDestination(out.tx->tx->vout[out.i].scriptPubKey, address))
{
CPubKey pubkey;
CKeyID *keyid = boost::get<CKeyID>(&address);
if (keyid && model->getPubKey(*keyid, pubkey))
{
nBytesInputs += (pubkey.IsCompressed() ? 148 : 180);
}
else
nBytesInputs += 148; // in all error cases, simply assume 148 here
}
else nBytesInputs += 148;
}
// calculation
if (nQuantity > 0)
{
// Bytes
nBytes = nBytesInputs + ((CoinControlDialog::payAmounts.size() > 0 ? CoinControlDialog::payAmounts.size() + 1 : 2) * 34) + 10; // always assume +1 output for change here
if (fWitness)
{
// there is some fudging in these numbers related to the actual virtual transaction size calculation that will keep this estimate from being exact.
// usually, the result will be an overestimate within a couple of satoshis so that the confirmation dialog ends up displaying a slightly smaller fee.
// also, the witness stack size value is a variable sized integer. usually, the number of stack items will be well under the single byte var int limit.
nBytes += 2; // account for the serialized marker and flag bytes
nBytes += nQuantity; // account for the witness byte that holds the number of stack items for each input.
}
// in the subtract fee from amount case, we can tell if zero change already and subtract the bytes, so that fee calculation afterwards is accurate
if (CoinControlDialog::fSubtractFeeFromAmount)
if (nAmount - nPayAmount == 0)
nBytes -= 34;
// Fee
nPayFee = GetMinimumFee(nBytes, *coinControl, ::mempool, ::feeEstimator, nullptr /* FeeCalculation */);
if (nPayAmount > 0)
{
nChange = nAmount - nPayAmount;
if (!CoinControlDialog::fSubtractFeeFromAmount)
nChange -= nPayFee;
// Never create dust outputs; if we would, just add the dust to the fee.
if (nChange > 0 && nChange < MIN_CHANGE)
{
CTxOut txout(nChange, (CScript)std::vector<unsigned char>(24, 0));
if (IsDust(txout, ::dustRelayFee))
{
nPayFee += nChange;
nChange = 0;
if (CoinControlDialog::fSubtractFeeFromAmount)
nBytes -= 34; // we didn't detect lack of change above
}
}
if (nChange == 0 && !CoinControlDialog::fSubtractFeeFromAmount)
nBytes -= 34;
}
// after fee
nAfterFee = std::max<CAmount>(nAmount - nPayFee, 0);
}
// actually update labels
int nDisplayUnit = BitcoinUnits::BTC;
if (model && model->getOptionsModel())
nDisplayUnit = model->getOptionsModel()->getDisplayUnit();
QLabel *l1 = dialog->findChild<QLabel *>("labelCoinControlQuantity");
QLabel *l2 = dialog->findChild<QLabel *>("labelCoinControlAmount");
QLabel *l3 = dialog->findChild<QLabel *>("labelCoinControlFee");
QLabel *l4 = dialog->findChild<QLabel *>("labelCoinControlAfterFee");
QLabel *l5 = dialog->findChild<QLabel *>("labelCoinControlBytes");
QLabel *l7 = dialog->findChild<QLabel *>("labelCoinControlLowOutput");
QLabel *l8 = dialog->findChild<QLabel *>("labelCoinControlChange");
// enable/disable "dust" and "change"
dialog->findChild<QLabel *>("labelCoinControlLowOutputText")->setEnabled(nPayAmount > 0);
dialog->findChild<QLabel *>("labelCoinControlLowOutput") ->setEnabled(nPayAmount > 0);
dialog->findChild<QLabel *>("labelCoinControlChangeText") ->setEnabled(nPayAmount > 0);
dialog->findChild<QLabel *>("labelCoinControlChange") ->setEnabled(nPayAmount > 0);
// stats
l1->setText(QString::number(nQuantity)); // Quantity
l2->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nAmount)); // Amount
l3->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nPayFee)); // Fee
l4->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nAfterFee)); // After Fee
l5->setText(((nBytes > 0) ? ASYMP_UTF8 : "") + QString::number(nBytes)); // Bytes
l7->setText(fDust ? tr("yes") : tr("no")); // Dust
l8->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nChange)); // Change
if (nPayFee > 0)
{
l3->setText(ASYMP_UTF8 + l3->text());
l4->setText(ASYMP_UTF8 + l4->text());
if (nChange > 0 && !CoinControlDialog::fSubtractFeeFromAmount)
l8->setText(ASYMP_UTF8 + l8->text());
}
// turn label red when dust
l7->setStyleSheet((fDust) ? "color:red;" : "");
// tool tips
QString toolTipDust = tr("This label turns red if any recipient receives an amount smaller than the current dust threshold.");
// how many satoshis the estimated fee can vary per byte we guess wrong
assert(nBytes != 0);
double dFeeVary = (double)nPayFee / nBytes;
QString toolTip4 = tr("Can vary +/- %1 satoshi(s) per input.").arg(dFeeVary);
l3->setToolTip(toolTip4);
l4->setToolTip(toolTip4);
l7->setToolTip(toolTipDust);
l8->setToolTip(toolTip4);
dialog->findChild<QLabel *>("labelCoinControlFeeText") ->setToolTip(l3->toolTip());
dialog->findChild<QLabel *>("labelCoinControlAfterFeeText") ->setToolTip(l4->toolTip());
dialog->findChild<QLabel *>("labelCoinControlBytesText") ->setToolTip(l5->toolTip());
dialog->findChild<QLabel *>("labelCoinControlLowOutputText")->setToolTip(l7->toolTip());
dialog->findChild<QLabel *>("labelCoinControlChangeText") ->setToolTip(l8->toolTip());
// Insufficient funds
QLabel *label = dialog->findChild<QLabel *>("labelCoinControlInsuffFunds");
if (label)
label->setVisible(nChange < 0);
}
void CoinControlDialog::updateView()
{
if (!model || !model->getOptionsModel() || !model->getAddressTableModel())
return;
bool treeMode = ui->radioTreeMode->isChecked();
ui->treeWidget->clear();
ui->treeWidget->setEnabled(false); // performance, otherwise updateLabels would be called for every checked checkbox
ui->treeWidget->setAlternatingRowColors(!treeMode);
QFlags<Qt::ItemFlag> flgCheckbox = Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable;
QFlags<Qt::ItemFlag> flgTristate = Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemIsTristate;
int nDisplayUnit = model->getOptionsModel()->getDisplayUnit();
std::map<QString, std::vector<COutput> > mapCoins;
model->listCoins(mapCoins);
for (const std::pair<QString, std::vector<COutput>>& coins : mapCoins) {
CCoinControlWidgetItem *itemWalletAddress = new CCoinControlWidgetItem();
itemWalletAddress->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked);
QString sWalletAddress = coins.first;
QString sWalletLabel = model->getAddressTableModel()->labelForAddress(sWalletAddress);
if (sWalletLabel.isEmpty())
sWalletLabel = tr("(no label)");
if (treeMode)
{
// wallet address
ui->treeWidget->addTopLevelItem(itemWalletAddress);
itemWalletAddress->setFlags(flgTristate);
itemWalletAddress->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked);
// label
itemWalletAddress->setText(COLUMN_LABEL, sWalletLabel);
// address
itemWalletAddress->setText(COLUMN_ADDRESS, sWalletAddress);
}
CAmount nSum = 0;
int nChildren = 0;
for (const COutput& out : coins.second) {
nSum += out.tx->tx->vout[out.i].nValue;
nChildren++;
CCoinControlWidgetItem *itemOutput;
if (treeMode) itemOutput = new CCoinControlWidgetItem(itemWalletAddress);
else itemOutput = new CCoinControlWidgetItem(ui->treeWidget);
itemOutput->setFlags(flgCheckbox);
itemOutput->setCheckState(COLUMN_CHECKBOX,Qt::Unchecked);
// address
CTxDestination outputAddress;
QString sAddress = "";
if(ExtractDestination(out.tx->tx->vout[out.i].scriptPubKey, outputAddress))
{
sAddress = QString::fromStdString(EncodeDestination(outputAddress));
// if listMode or change => show bitcoin address. In tree mode, address is not shown again for direct wallet address outputs
if (!treeMode || (!(sAddress == sWalletAddress)))
itemOutput->setText(COLUMN_ADDRESS, sAddress);
}
// label
if (!(sAddress == sWalletAddress)) // change
{
// tooltip from where the change comes from
itemOutput->setToolTip(COLUMN_LABEL, tr("change from %1 (%2)").arg(sWalletLabel).arg(sWalletAddress));
itemOutput->setText(COLUMN_LABEL, tr("(change)"));
}
else if (!treeMode)
{
QString sLabel = model->getAddressTableModel()->labelForAddress(sAddress);
if (sLabel.isEmpty())
sLabel = tr("(no label)");
itemOutput->setText(COLUMN_LABEL, sLabel);
}
// amount
itemOutput->setText(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, out.tx->tx->vout[out.i].nValue));
itemOutput->setData(COLUMN_AMOUNT, Qt::UserRole, QVariant((qlonglong)out.tx->tx->vout[out.i].nValue)); // padding so that sorting works correctly
// date
itemOutput->setText(COLUMN_DATE, GUIUtil::dateTimeStr(out.tx->GetTxTime()));
itemOutput->setData(COLUMN_DATE, Qt::UserRole, QVariant((qlonglong)out.tx->GetTxTime()));
// confirmations
itemOutput->setText(COLUMN_CONFIRMATIONS, QString::number(out.nDepth));
itemOutput->setData(COLUMN_CONFIRMATIONS, Qt::UserRole, QVariant((qlonglong)out.nDepth));
// transaction hash
uint256 txhash = out.tx->GetHash();
itemOutput->setText(COLUMN_TXHASH, QString::fromStdString(txhash.GetHex()));
// vout index
itemOutput->setText(COLUMN_VOUT_INDEX, QString::number(out.i));
// disable locked coins
if (model->isLockedCoin(txhash, out.i))
{
COutPoint outpt(txhash, out.i);
coinControl->UnSelect(outpt); // just to be sure
itemOutput->setDisabled(true);
itemOutput->setIcon(COLUMN_CHECKBOX, platformStyle->SingleColorIcon(":/icons/lock_closed"));
}
// set checkbox
if (coinControl->IsSelected(COutPoint(txhash, out.i)))
itemOutput->setCheckState(COLUMN_CHECKBOX, Qt::Checked);
}
// amount
if (treeMode)
{
itemWalletAddress->setText(COLUMN_CHECKBOX, "(" + QString::number(nChildren) + ")");
itemWalletAddress->setText(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, nSum));
itemWalletAddress->setData(COLUMN_AMOUNT, Qt::UserRole, QVariant((qlonglong)nSum));
}
}
// expand all partially selected
if (treeMode)
{
for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++)
if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) == Qt::PartiallyChecked)
ui->treeWidget->topLevelItem(i)->setExpanded(true);
}
// sort view
sortView(sortColumn, sortOrder);
ui->treeWidget->setEnabled(true);
}
| trippysalmon/bitcoin | src/qt/coincontroldialog.cpp | C++ | mit | 29,915 |
<?php
/*
Safe sample
input : use fopen to read /tmp/tainted.txt and put the first line in $tainted
Flushes content of $sanitized if the filter number_float_filter is not applied
construction : use of sprintf via a %d with simple quote
*/
/*Copyright 2015 Bertrand STIVALET
Permission is hereby granted, without written agreement or royalty fee, to
use, copy, modify, and distribute this software and its documentation for
any purpose, provided that the above copyright notice and the following
three paragraphs appear in all copies of this software.
IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT
LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO
OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.*/
$handle = @fopen("/tmp/tainted.txt", "r");
if ($handle) {
if(($tainted = fgets($handle, 4096)) == false) {
$tainted = "";
}
fclose($handle);
} else {
$tainted = "";
}
if (filter_var($sanitized, FILTER_VALIDATE_FLOAT))
$tainted = $sanitized ;
else
$tainted = "" ;
$query = sprintf("$temp = '%d';", $tainted);
$res = eval($query);
?> | stivalet/PHP-Vulnerability-test-suite | Injection/CWE_95/safe/CWE_95__fopen__func_FILTER-VALIDATION-number_float_filter__variable-sprintf_%d_simple_quote.php | PHP | mit | 1,502 |
<?php
/*
* This file is part of App/Validation.
*
* (c) Alexandre Gomes Gaigalas <alexandre@gaigalas.net>
*
* For the full copyright and license information, please view the "LICENSE.md"
* file that was distributed with this source code.
*/
namespace App\Validation\Exceptions;
class PostalCodeException extends ValidationException
{
public static $defaultTemplates = [
self::MODE_DEFAULT => [
self::STANDARD => '{{name}} must be a valid postal code on {{countryCode}}',
],
self::MODE_NEGATIVE => [
self::STANDARD => '{{name}} must not be a valid postal code on {{countryCode}}',
],
];
}
| Javier-Solis/admin-project | app/Validation/Exceptions/PostalCodeException.php | PHP | mit | 662 |
<?php
/******************************/
/* Submission Form Management */
/******************************/
require_once("../includes/admin_init.php");
require_once("../includes/adminAccount.class.php");
require_once("../includes/subForm.class.php");
require_once("../includes/conference.class.php");
/* Intitalize and output header */
initHeader("Submission Form Management");
/* Lets create an instance of the AdminAccount class, which handles administrator's account */
$adminAccount = new AdminAccount();
/* Let's create an instance of the SubForm class, which handles settings for the submission form */
$subForm = new SubForm($adminAccount->getCurrentConference());
/* Let's create an instance of the Conference class, which handles operations with currently selected conference */
$conference = new Conference($adminAccount->getCurrentConference());
/* Initialize page's template file */
$tpl = new Template("../templates/admin/conference_subform.tpl");
/* On user's attempt to add a new topic */
if (isset($_POST["new_topic"])) {
/* Check if Topic Title is entered */
$err_topic_title = empty($_POST["topic"]);
/* If Page Title is entered, add a new topic */
if ( !$err_topic_title ) {
/* Add topic to the DB */
$subForm->addTopic($_POST["topic"]);
/* Send a success message to the user */
$msg_add_success = true;
}
}
/* On user's attempt to delete a topic */
if (isset($_POST["delete_topic"])) {
/* Delete that page */
$subForm->deleteTopic($_POST["delete_topic"]);
/* Send a success message to the user */
$msg_delete_success = true;
}
/* On user's attempt to save submission form notes */
if (isset($_POST["edit_subform_notes"])) {
/* Save notes to the database */
$subForm->editNotes($_POST["subform_notes"]);
/* Show user a success message */
$msg_notes_success = true;
}
/* On user's attempt to save allowed file types */
if (isset($_POST["edit_file_types"])) {
/* Save file types to the database */
$subForm->editFileTypes($_POST["file_types"]);
/* Show user a success message */
$msg_file_types_success = true;
}
/* Lets assign each topic's data to the template file */
$result = $subForm->getAllTopics();
/* Are there any topics yet? */
if (mysqli_num_rows($result)) {
$topics_found = true;
$i = 1;
while ($data = mysqli_fetch_array($result)) {
/* If even iteration, we need to display different style of table */
if ($i % 2 == 0) {
$even = ' class="even"';
} else {
$even = '';
}
/* Assign data for the loop */
$tpl->assignLoop(array(
"TOPICS.ID" => $data['id'],
"TOPICS.TITLE" => $data['topic'],
"TOPICS.EVEN" => $even,
));
$i++;
}
$tpl->parseLoop('TOPICS');
$tpl->parseIf();
/* No topics yet */
} else {
$topics_not_found = true;
}
/* Parse the error/success message(s) */
$tpl->assignIf(array(
"TOPICS_FOUND" => $topics_found,
"TOPICS_NOT_FOUND" => $topics_not_found,
"ERR_TOPIC_TITLE" => $err_topic_title,
"MSG_DELETE_SUCCESS" => $msg_delete_success,
"MSG_ADD_SUCCESS" => $msg_add_success,
"MSG_NOTES_SUCCESS" => $msg_notes_success,
"MSG_FILE_TYPES_SUCCESS" => $msg_file_types_success,
));
$tpl->parseIf();
/* Get conference's configuration */
$conference_data = $conference->getConfiguration();
/* Assign and parse the submission form notes and allowed file types */
$tpl->assignStr(array(
"SUBFORM_NOTES" => $conference_data['subform_notes'],
"SUBFORM_FILE_TYPES" => $conference_data['subform_file_types'],
));
$tpl->parseStr();
/* Output the final HTML code */
$tpl->output();
/* Intitalize and output footer */
initFooter();
?> | jakkub/Confy | src/admin/conference_subform.php | PHP | mit | 3,708 |
'use strict';
/* global $: true */
/* global animation: true */
/* global boidWeights: true */
//Slider for selecting initial number of boids
//---------------------------------------------
$('#numBoidsSlider').slider({
min: 0,
max: 400,
step: 10,
value: animation.numBoids
});
$('#numBoidsVal').text(animation.numBoids);
$('#numBoidsSlider').on('slide', function (slideEvt) {
$('#numBoidsVal').text(slideEvt.value);
animation.numBoids = slideEvt.value;
});
//Sliders for weights
//--------------------
$('#slider1').slider({
min: 0,
max: 20,
step: 0.1,
value: boidWeights.separation
});
$('#slider1val').text(boidWeights.separation);
$('#slider1').on('slide', function (slideEvt) {
$('#slider1val').text(slideEvt.value);
boidWeights.separation = slideEvt.value;
});
$('#slider2').slider({
min: 0,
max: 20,
step: 0.1,
value: boidWeights.alginment
});
$('#slider2').on('slide', function (slideEvt) {
$('#slider2val').text(boidWeights.alginment);
$('#slider2val').text(slideEvt.value);
boidWeights.alginment = slideEvt.value;
});
$('#slider3').slider({
min: 0,
max: 20,
step: 0.1,
value: boidWeights.cohesion
});
$('#slider3val').text(boidWeights.cohesion);
$('#slider3').on('slide', function (slideEvt) {
$('#slider3val').text(slideEvt.value);
boidWeights.cohesion = slideEvt.value;
});
$('#slider4').slider({
min: 0,
max: 20,
step: 0.1,
value: boidWeights.obstacle
});
$('#slider4val').text(boidWeights.obstacle);
$('#slider4').on('slide', function (slideEvt) {
$('#slider4val').text(slideEvt.value);
boidWeights.obstacle = slideEvt.value;
});
$('#slider5').slider({
min: 0,
max: 20,
step: 0.1,
value: boidWeights.predators
});
$('#slider5val').text(boidWeights.predators);
$('#slider5').on('slide', function (slideEvt) {
$('#slider5val').text(slideEvt.value);
boidWeights.predators = slideEvt.value;
});
| johhat/boids | ui-components/ui.js | JavaScript | mit | 1,967 |
package test;
/**
scala> map
res6: java.util.HashMap[String,java.util.List[String]] = {AAA=[BBB, CCC, EEE], CCC=[DDD]}
scala> test.Test.printCompany(map)
-AAA
-BBB
-CCC
-DDD
-EEE
*/
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
public class Test {
public static void printCompany(HashMap<String, List<String>> graph) {
if (graph.size() == 0) return;
HashSet<String> roots = new HashSet<String>();
for (String v : graph.keySet()) {
roots.add(v);
}
for (String v : graph.keySet()) {
for (String l : graph.get(v)) {
roots.remove(l);
}
}
for (String v : roots) {
printCompany(graph, v, 0);
}
}
private static void printCompany(HashMap<String, List<String>> graph, String vertex, int depth) {
printVertex(vertex, depth);
if (graph.containsKey(vertex)) {
for (String v : graph.get(vertex)) {
printCompany(graph, v, depth + 1);
}
}
}
private static void printVertex(String vertex, int depth) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < depth; i++) {
sb.append(" ");
}
sb.append("-");
sb.append(vertex);
System.out.println(sb.toString());
}
}
| sadikovi/algorithms | careercup/company-structure.java | Java | mit | 1,233 |
<?php
/* @var $this UserController */
/* @var $data User */
?>
<div class="view">
<b><?php echo CHtml::encode($data->getAttributeLabel('id')); ?>:</b>
<?php echo CHtml::link(CHtml::encode($data->id), array('view', 'id'=>$data->id)); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('level_id')); ?>:</b>
<?php echo CHtml::encode($data->level_id); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('username')); ?>:</b>
<?php echo CHtml::encode($data->username); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('email')); ?>:</b>
<?php echo CHtml::encode($data->email); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('password')); ?>:</b>
<?php echo CHtml::encode($data->password); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('join_date')); ?>:</b>
<?php echo CHtml::encode($data->join_date); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('banned')); ?>:</b>
<?php echo CHtml::encode($data->banned); ?>
<br />
<?php /*
<b><?php echo CHtml::encode($data->getAttributeLabel('active')); ?>:</b>
<?php echo CHtml::encode($data->active); ?>
<br />
*/ ?>
</div> | felladrin/joinuo | protected/views/user/_view.php | PHP | mit | 1,185 |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright 2015 by PyCLibrary Authors, see AUTHORS for more details.
#
# Distributed under the terms of the MIT/X11 license.
#
# The full license is in the file LICENCE, distributed with this software.
# -----------------------------------------------------------------------------
"""
Used for extracting data such as macro definitions, variables, typedefs, and
function signatures from C header files.
"""
from __future__ import (division, unicode_literals, print_function,
absolute_import)
import sys
import re
import os
import logging
from inspect import cleandoc
from future.utils import istext, isbytes
from ast import literal_eval
from traceback import format_exc
from .errors import DefinitionError
from .utils import find_header
# Import parsing elements
from .thirdparty.pyparsing import \
(ParserElement, ParseResults, Forward, Optional, Word, WordStart,
WordEnd, Keyword, Regex, Literal, SkipTo, ZeroOrMore, OneOrMore,
Group, LineEnd, stringStart, quotedString, oneOf, nestedExpr,
delimitedList, restOfLine, cStyleComment, alphas, alphanums, hexnums,
lineno, Suppress)
ParserElement.enablePackrat()
logger = logging.getLogger(__name__)
__all__ = ['win_defs', 'CParser']
class Type(tuple):
"""
Representation of a C type. CParser uses this class to store the parsed
typedefs and the types of variable/func.
**ATTENTION:** Due to compatibility issues with 0.1.0 this class derives
from tuple and can be seen as the tuples from 0.1.0. In future this might
change to a tuple-like object!!!
Parameters
----------
type_spec : str
a string referring the base type of this type defintion. This may
either be a fundametal type (i.e. 'int', 'enum x') or a type definition
made by a typedef-statement
declarators : str or list of tuple
all following parameters are deriving a type from the type defined
until now. Types can be derived by:
- The string '*': define a pointer to the base type
(i.E. Type('int', '*'))
- The string '&': a reference. T.B.D.
- A list of integers of len 1: define an array with N elements
(N is the first and single entry in the list of integers). If N is
-1, the array definition is seen as 'int x[]'
(i.E. Type('int', [1])
- a N-tuple of 3-tuples: defines a function of N parameters. Every
parameter is a 3 tuple of the form:
(<parameter-name-or-None>, <param-type>, None).
Due to compatibility reasons the return value of the function is
stored in Type.type_spec parameter
(This is **not** the case for function pointers):
(i.E. Type(Type('int', '*'), ( ('param1', Type('int'), None), ) ) )
type_quals : dict of int to list of str (optional)
this optional (keyword-)argument allows to optionally add type
qualifiers for every declarator level. The key 0 refers the type
qualifier of type_spec, while 1 refers to declarators[0], 2 refers to
declarators[1] and so on.
To build more complex types any number of declarators can be combined. i.E.
>>> int * (*a[2])(char *, signed c[]);
if represented as:
>>> Type('int', '*',
>>> ( (None, Type('char', '*'), None),
>>> ('c', Type('signed', [-1]), None) )),
>>> '*', [2])
"""
# Cannot slot a subclass of tuple.
def __new__(cls, type_spec, *declarators, **argv):
return super(Type, cls).__new__(cls, (type_spec,) + declarators)
def __init__(self, type_spec, *declarators, **argv):
super(Type, self).__init__()
self.type_quals = (argv.pop('type_quals', None) or
((),) * (1 + len(declarators)))
if len(self.type_quals) != 1 + len(declarators):
raise ValueError("wrong number of type qualifiers")
assert len(argv) == 0, 'Invalid Parameter'
def __eq__(self, other):
if isinstance(other, Type):
if self.type_quals != other.type_quals:
return False
return super(Type, self).__eq__(other)
def __ne__(self, other):
return not self.__eq__(other)
@property
def declarators(self):
"""Return a tuple of all declarators.
"""
return tuple(self[1:])
@property
def type_spec(self):
"""Return the base type of this type.
"""
return self[0]
def is_fund_type(self):
"""Returns True, if this type is a fundamental type.
Fundamental types are all types, that are not defined via typedef
"""
if (self[0].startswith('struct ') or self[0].startswith('union ') or
self[0].startswith('enum ')):
return True
names = (num_types + nonnum_types + size_modifiers + sign_modifiers +
extra_type_list)
for w in self[0].split():
if w not in names:
return False
return True
def eval(self, type_map, used=None):
"""Resolves the type_spec of this type recursively if it is referring
to a typedef. For resolving the type type_map is used for lookup.
Returns a new Type object.
Parameters
----------
type_map : dict of str to Type
All typedefs that shall be resolved have to be stored in this
type_map.
used : list of str
For internal use only to prevent circular typedefs
"""
used = used or []
if self.is_fund_type():
# Remove 'signed' before returning evaluated type
return Type(re.sub(r'\bsigned\b', '', self.type_spec).strip(),
*self.declarators,
type_quals=self.type_quals)
parent = self.type_spec
if parent in used:
m = 'Recursive loop while evaluating types. (typedefs are {})'
raise DefinitionError(m.format(' -> '.join(used+[parent])))
used.append(parent)
if parent not in type_map:
m = 'Unknown type "{}" (typedefs are {})'
raise DefinitionError(m.format(parent, ' -> '.join(used)))
pt = type_map[parent]
evaled_type = Type(pt.type_spec, *(pt.declarators + self.declarators),
type_quals=(pt.type_quals[:-1] +
(pt.type_quals[-1] +
self.type_quals[0],) +
self.type_quals[1:])
)
return evaled_type.eval(type_map, used)
def add_compatibility_hack(self):
"""If This Type is refering to a function (**not** a function pointer)
a new type is returned, that matches the hack from version 0.1.0.
This hack enforces the return value be encapsulated in a separated Type
object:
Type('int', '*', ())
is converted to
Type(Type('int', '*'), ())
"""
if type(self[-1]) == tuple:
return Type(Type(*self[:-1], type_quals=self.type_quals[:-1]),
self[-1],
type_quals=((), self.type_quals[-1]))
else:
return self
def remove_compatibility_hack(self):
"""Returns a Type object, where the hack from .add_compatibility_hack()
is removed
"""
if len(self) == 2 and isinstance(self[0], Type):
return Type(*(self[0] + (self[1],)))
else:
return self
def __repr__(self):
type_qual_str = ('' if not any(self.type_quals) else
', type_quals='+repr(self.type_quals))
return (type(self).__name__ + '(' +
', '.join(map(repr, self)) + type_qual_str + ')')
class Compound(dict):
"""Base class for representing object using a dict-like interface.
"""
__slots__ = ()
def __init__(self, *members, **argv):
members = list(members)
pack = argv.pop('pack', None)
assert len(argv) == 0
super(Compound, self).__init__(dict(members=members, pack=pack))
def __repr__(self):
packParam = ', pack='+repr(self.pack) if self.pack is not None else ''
return (type(self).__name__ + '(' +
', '.join(map(repr, self.members)) + packParam + ')')
@property
def members(self):
return self['members']
@property
def pack(self):
return self['pack']
class Struct(Compound):
"""Representation of a C struct. CParser uses this class to store the parsed
structs.
**ATTENTION:** Due to compatibility issues with 0.1.0 this class derives
from dict and can be seen as the dicts from 0.1.0. In future this might
change to a dict-like object!!!
"""
__slots__ = ()
class Union(Compound):
"""Representation of a C union. CParser uses this class to store the parsed
unions.
**ATTENTION:** Due to compatibility issues with 0.1.0 this class derives
from dict and can be seen as the dicts from 0.1.0. In future this might
change to a dict-like object!!!
"""
__slots__ = ()
class Enum(dict):
"""Representation of a C enum. CParser uses this class to store the parsed
enums.
**ATTENTION:** Due to compatibility issues with 0.1.0 this class derives
from dict and can be seen as the dicts from 0.1.0. In future this might
change to a dict-like object!!!
"""
__slots__ = ()
def __init__(self, **args):
super(Enum, self).__init__(args)
def __repr__(self):
return (type(self).__name__ + '(' +
', '.join(nm + '=' + repr(val)
for nm, val in sorted(self.items())) +
')')
def win_defs(version='800'):
"""Loads selection of windows headers included with PyCLibrary.
These definitions can either be accessed directly or included before
parsing another file like this:
>>> windefs = c_parser.win_defs()
>>> p = c_parser.CParser("headerFile.h", copy_from=windefs)
Definitions are pulled from a selection of header files included in Visual
Studio (possibly not legal to distribute? Who knows.), some of which have
been abridged because they take so long to parse.
Parameters
----------
version : unicode
Version of the MSVC to consider when parsing.
Returns
-------
parser : CParser
CParser containing all the infos from te windows headers.
"""
header_files = ['WinNt.h', 'WinDef.h', 'WinBase.h', 'BaseTsd.h',
'WTypes.h', 'WinUser.h']
if not CParser._init:
logger.warning('Automatic initialisation : OS is assumed to be win32')
from .init import auto_init
auto_init('win32')
d = os.path.dirname(__file__)
p = CParser(
[os.path.join(d, 'headers', h) for h in header_files],
macros={'_WIN32': '', '_MSC_VER': version, 'CONST': 'const',
'NO_STRICT': None, 'MS_WIN32': ''},
process_all=False
)
p.process_all(cache=os.path.join(d, 'headers', 'WinDefs.cache'))
return p
class CParser(object):
"""Class for parsing C code to extract variable, struct, enum, and function
declarations as well as preprocessor macros.
This is not a complete C parser; instead, it is meant to simplify the
process of extracting definitions from header files in the absence of a
complete build system. Many files will require some amount of manual
intervention to parse properly (see 'replace' and extra arguments)
Parameters
----------
files : str or iterable, optional
File or files which should be parsed.
copy_from : CParser or iterable of CParser, optional
CParser whose definitions should be included.
replace : dict, optional
Specify som string replacements to perform before parsing. Format is
{'searchStr': 'replaceStr', ...}
process_all : bool, optional
Flag indicating whether files should be parsed immediatly. True by
default.
cache : unicode, optional
Path of the cache file from which to load definitions/to which save
definitions as parsing is an expensive operation.
kwargs :
Extra parameters may be used to specify the starting state of the
parser. For example, one could provide a set of missing type
declarations by types={'UINT': ('unsigned int'), 'STRING': ('char', 1)}
Similarly, preprocessor macros can be specified: macros={'WINAPI': ''}
Example
-------
Create parser object, load two files
>>> p = CParser(['header1.h', 'header2.h'])
Remove comments, preprocess, and search for declarations
>>> p.process_ all()
Just to see what was successfully parsed from the files
>>> p.print_all()
Access parsed declarations
>>> all_values = p.defs['values']
>>> functionSignatures = p.defs['functions']
To see what was not successfully parsed
>>> unp = p.process_all(return_unparsed=True)
>>> for s in unp:
print s
"""
#: Increment every time cache structure or parsing changes to invalidate
#: old cache files.
cache_version = 1
#: Private flag allowing to know if the parser has been initiliased.
_init = False
def __init__(self, files=None, copy_from=None, replace=None,
process_all=True, cache=None, **kwargs):
if not self._init:
logger.warning('Automatic initialisation based on OS detection')
from .init import auto_init
auto_init()
# Holds all definitions
self.defs = {}
# Holds definitions grouped by the file they came from
self.file_defs = {}
# Description of the struct packing rules as defined by #pragma pack
self.pack_list = {}
self.init_opts = kwargs.copy()
self.init_opts['files'] = []
self.init_opts['replace'] = {}
self.data_list = ['types', 'variables', 'fnmacros', 'macros',
'structs', 'unions', 'enums', 'functions', 'values']
self.file_order = []
self.files = {}
if files is not None:
if istext(files) or isbytes(files):
files = [files]
for f in self.find_headers(files):
self.load_file(f, replace)
# Initialize empty definition lists
for k in self.data_list:
self.defs[k] = {}
# Holds translations from typedefs/structs/unions to fundamental types
self.compiled_types = {}
self.current_file = None
# Import extra arguments if specified
for t in kwargs:
for k in kwargs[t].keys():
self.add_def(t, k, kwargs[t][k])
# Import from other CParsers if specified
if copy_from is not None:
if not isinstance(copy_from, (list, tuple)):
copy_from = [copy_from]
for p in copy_from:
self.import_dict(p.file_defs)
if process_all:
self.process_all(cache=cache)
def process_all(self, cache=None, return_unparsed=False,
print_after_preprocess=False):
""" Remove comments, preprocess, and parse declarations from all files.
This operates in memory, and thus does not alter the original files.
Parameters
----------
cache : unicode, optional
File path where cached results are be stored or retrieved. The
cache is automatically invalidated if any of the arguments to
__init__ are changed, or if the C files are newer than the cache.
return_unparsed : bool, optional
Passed directly to parse_defs.
print_after_preprocess : bool, optional
If true prints the result of preprocessing each file.
Returns
-------
results : list
List of the results from parse_defs.
"""
if cache is not None and self.load_cache(cache, check_validity=True):
logger.debug("Loaded cached definitions; will skip parsing.")
# Cached values loaded successfully, nothing left to do here
return
results = []
logger.debug(cleandoc('''Parsing C header files (no valid cache found).
This could take several minutes...'''))
for f in self.file_order:
if self.files[f] is None:
# This means the file could not be loaded and there was no
# cache.
mess = 'Could not find header file "{}" or a cache file.'
raise IOError(mess.format(f))
logger.debug("Removing comments from file '{}'...".format(f))
self.remove_comments(f)
logger.debug("Preprocessing file '{}'...".format(f))
self.preprocess(f)
if print_after_preprocess:
print("===== PREPROCSSED {} =======".format(f))
print(self.files[f])
logger.debug("Parsing definitions in file '{}'...".format(f))
results.append(self.parse_defs(f, return_unparsed))
if cache is not None:
logger.debug("Writing cache file '{}'".format(cache))
self.write_cache(cache)
return results
def load_cache(self, cache_file, check_validity=False):
"""Load a cache file.
Used internally if cache is specified in process_all().
Parameters
----------
cache_file : unicode
Path of the file from which the cache should be loaded.
check_validity : bool, optional
If True, then run several checks before loading the cache:
- cache file must not be older than any source files
- cache file must not be older than this library file
- options recorded in cache must match options used to initialize
CParser
Returns
-------
result : bool
Did the loading succeeded.
"""
# Make sure cache file exists
if not istext(cache_file):
raise ValueError("Cache file option must be a unicode.")
if not os.path.isfile(cache_file):
# If file doesn't exist, search for it in this module's path
d = os.path.dirname(__file__)
cache_file = os.path.join(d, "headers", cache_file)
if not os.path.isfile(cache_file):
logger.debug("Can't find requested cache file.")
return False
# Make sure cache is newer than all input files
if check_validity:
mtime = os.stat(cache_file).st_mtime
for f in self.file_order:
# If file does not exist, then it does not count against the
# validity of the cache.
if os.path.isfile(f) and os.stat(f).st_mtime > mtime:
logger.debug("Cache file is out of date.")
return False
try:
# Read cache file
import pickle
cache = pickle.load(open(cache_file, 'rb'))
# Make sure __init__ options match
if check_validity:
if cache['opts'] != self.init_opts:
db = logger.debug
db("Cache file is not valid")
db("It was created using different initialization options")
db('{}'.format(cache['opts']))
db('{}'.format(self.init_opts))
return False
else:
logger.debug("Cache init opts are OK:")
logger.debug('{}'.format(cache['opts']))
if cache['version'] < self.cache_version:
mess = "Cache file is not valid--cache format has changed."
logger.debug(mess)
return False
# Import all parse results
self.import_dict(cache['file_defs'])
return True
except Exception:
logger.exception("Warning--cache read failed:")
return False
def import_dict(self, data):
"""Import definitions from a dictionary.
The dict format should be the same as CParser.file_defs.
Used internally; does not need to be called manually.
"""
for f in data.keys():
self.current_file = f
for k in self.data_list:
for n in data[f][k]:
self.add_def(k, n, data[f][k][n])
def write_cache(self, cache_file):
"""Store all parsed declarations to cache. Used internally.
"""
cache = {}
cache['opts'] = self.init_opts
cache['file_defs'] = self.file_defs
cache['version'] = self.cache_version
import pickle
pickle.dump(cache, open(cache_file, 'wb'))
def find_headers(self, headers):
"""Try to find the specified headers.
"""
hs = []
for header in headers:
if os.path.isfile(header):
hs.append(header)
else:
h = find_header(header)
if not h:
raise OSError('Cannot find header: {}'.format(header))
hs.append(h)
return hs
def load_file(self, path, replace=None):
"""Read a file, make replacements if requested.
Called by __init__, should not be called manually.
Parameters
----------
path : unicode
Path of the file to load.
replace : dict, optional
Dictionary containing strings to replace by the associated value
when loading the file.
"""
if not os.path.isfile(path):
# Not a fatal error since we might be able to function properly if
# there is a cache file.
mess = "Warning: C header '{}' is missing, this may cause trouble."
logger.warning(mess.format(path))
self.files[path] = None
return False
# U causes all newline types to be converted to \n
with open(path, 'rU') as fd:
self.files[path] = fd.read()
if replace is not None:
for s in replace:
self.files[path] = re.sub(s, replace[s], self.files[path])
self.file_order.append(path)
bn = os.path.basename(path)
self.init_opts['replace'][bn] = replace
# Only interested in the file names, the directory may change between
# systems.
self.init_opts['files'].append(bn)
return True
def print_all(self, filename=None):
"""Print everything parsed from files. Useful for debugging.
Parameters
----------
filename : unicode, optional
Name of the file whose definition should be printed.
"""
from pprint import pprint
for k in self.data_list:
print("============== {} ==================".format(k))
if filename is None:
pprint(self.defs[k])
else:
pprint(self.file_defs[filename][k])
# =========================================================================
# --- Processing functions
# =========================================================================
def remove_comments(self, path):
"""Remove all comments from file.
Operates in memory, does not alter the original files.
"""
text = self.files[path]
cplusplus_line_comment = Literal("//") + restOfLine
# match quoted strings first to prevent matching comments inside quotes
comment_remover = (quotedString | cStyleComment.suppress() |
cplusplus_line_comment.suppress())
self.files[path] = comment_remover.transformString(text)
# --- Pre processing
def preprocess(self, path):
"""Scan named file for preprocessor directives, removing them while
expanding macros.
Operates in memory, does not alter the original files.
Currently support :
- conditionals : ifdef, ifndef, if, elif, else (defined can be used
in a if statement).
- definition : define, undef
- pragmas : pragma
"""
# We need this so that eval_expr works properly
self.build_parser()
self.current_file = path
# Stack for #pragma pack push/pop
pack_stack = [(None, None)]
self.pack_list[path] = [(0, None)]
packing = None # Current packing value
text = self.files[path]
# First join together lines split by \\n
text = Literal('\\\n').suppress().transformString(text)
# Define the structure of a macro definition
name = Word(alphas+'_', alphanums+'_')('name')
deli_list = Optional(lparen + delimitedList(name) + rparen)
self.pp_define = (name.setWhitespaceChars(' \t')("macro") +
deli_list.setWhitespaceChars(' \t')('args') +
SkipTo(LineEnd())('value'))
self.pp_define.setParseAction(self.process_macro_defn)
# Comb through lines, process all directives
lines = text.split('\n')
result = []
directive = re.compile(r'\s*#\s*([a-zA-Z]+)(.*)$')
if_true = [True]
if_hit = []
for i, line in enumerate(lines):
new_line = ''
m = directive.match(line)
# Regular code line
if m is None:
# Only include if we are inside the correct section of an IF
# block
if if_true[-1]:
new_line = self.expand_macros(line)
# Macro line
else:
d = m.groups()[0]
rest = m.groups()[1]
if d == 'ifdef':
d = 'if'
rest = 'defined ' + rest
elif d == 'ifndef':
d = 'if'
rest = '!defined ' + rest
# Evaluate 'defined' operator before expanding macros
if d in ['if', 'elif']:
def pa(t):
is_macro = t['name'] in self.defs['macros']
is_macro_func = t['name'] in self.defs['fnmacros']
return ['0', '1'][is_macro or is_macro_func]
rest = (Keyword('defined') +
(name | lparen + name + rparen)
).setParseAction(pa).transformString(rest)
elif d in ['define', 'undef']:
match = re.match(r'\s*([a-zA-Z_][a-zA-Z0-9_]*)(.*)$', rest)
macroName, rest = match.groups()
# Expand macros if needed
if rest is not None and (all(if_true) or d in ['if', 'elif']):
rest = self.expand_macros(rest)
if d == 'elif':
if if_hit[-1] or not all(if_true[:-1]):
ev = False
else:
ev = self.eval_preprocessor_expr(rest)
logger.debug(" "*(len(if_true)-2) + line +
'{}, {}'.format(rest, ev))
if_true[-1] = ev
if_hit[-1] = if_hit[-1] or ev
elif d == 'else':
logger.debug(" "*(len(if_true)-2) + line +
'{}'.format(not if_hit[-1]))
if_true[-1] = (not if_hit[-1]) and all(if_true[:-1])
if_hit[-1] = True
elif d == 'endif':
if_true.pop()
if_hit.pop()
logger.debug(" "*(len(if_true)-1) + line)
elif d == 'if':
if all(if_true):
ev = self.eval_preprocessor_expr(rest)
else:
ev = False
logger.debug(" "*(len(if_true)-1) + line +
'{}, {}'.format(rest, ev))
if_true.append(ev)
if_hit.append(ev)
elif d == 'define':
if not if_true[-1]:
continue
logger.debug(" "*(len(if_true)-1) + "define: " +
'{}, {}'.format(macroName, rest))
try:
# Macro is registered here
self.pp_define.parseString(macroName + ' ' + rest)
except Exception:
logger.exception("Error processing macro definition:" +
'{}, {}'.format(macroName, rest))
elif d == 'undef':
if not if_true[-1]:
continue
try:
self.rem_def('macros', macroName.strip())
except Exception:
if sys.exc_info()[0] is not KeyError:
mess = "Error removing macro definition '{}'"
logger.exception(mess.format(macroName.strip()))
# Check for changes in structure packing
# Support only for #pragme pack (with all its variants
# save show), None is used to signal that the default packing
# is used.
# Those two definition disagree :
# https://gcc.gnu.org/onlinedocs/gcc/Structure-Packing-Pragmas.html
# http://msdn.microsoft.com/fr-fr/library/2e70t5y1.aspx
# The current implementation follows the MSVC doc.
elif d == 'pragma':
if not if_true[-1]:
continue
m = re.match(r'\s+pack\s*\(([^\)]*)\)', rest)
if not m:
continue
if m.groups():
opts = [s.strip() for s in m.groups()[0].split(',')]
pushpop = id = val = None
for o in opts:
if o in ['push', 'pop']:
pushpop = o
elif o.isdigit():
val = int(o)
else:
id = o
packing = val
if pushpop == 'push':
pack_stack.append((packing, id))
elif opts[0] == 'pop':
if id is None:
pack_stack.pop()
else:
ind = None
for j, s in enumerate(pack_stack):
if s[1] == id:
ind = j
break
if ind is not None:
pack_stack = pack_stack[:ind]
if val is None:
packing = pack_stack[-1][0]
mess = ">> Packing changed to {} at line {}"
logger.debug(mess.format(str(packing), i))
self.pack_list[path].append((i, packing))
else:
# Ignore any other directives
mess = 'Ignored directive {} at line {}'
logger.debug(mess.format(d, i))
result.append(new_line)
self.files[path] = '\n'.join(result)
def eval_preprocessor_expr(self, expr):
# Make a few alterations so the expression can be eval'd
macro_diffs = (
Literal('!').setParseAction(lambda: ' not ') |
Literal('&&').setParseAction(lambda: ' and ') |
Literal('||').setParseAction(lambda: ' or ') |
Word(alphas + '_', alphanums + '_').setParseAction(lambda: '0'))
expr2 = macro_diffs.transformString(expr).strip()
try:
ev = bool(eval(expr2))
except Exception:
mess = "Error evaluating preprocessor expression: {} [{}]\n{}"
logger.debug(mess.format(expr, repr(expr2), format_exc()))
ev = False
return ev
def process_macro_defn(self, t):
"""Parse a #define macro and register the definition.
"""
logger.debug("Processing MACRO: {}".format(t))
macro_val = t.value.strip()
if macro_val in self.defs['fnmacros']:
self.add_def('fnmacros', t.macro, self.defs['fnmacros'][macro_val])
logger.debug(" Copy fn macro {} => {}".format(macro_val, t.macro))
else:
if t.args == '':
val = self.eval_expr(macro_val)
self.add_def('macros', t.macro, macro_val)
self.add_def('values', t.macro, val)
mess = " Add macro: {} ({}); {}"
logger.debug(mess.format(t.macro, val,
self.defs['macros'][t.macro]))
else:
self.add_def('fnmacros', t.macro,
self.compile_fn_macro(macro_val,
[x for x in t.args]))
mess = " Add fn macro: {} ({}); {}"
logger.debug(mess.format(t.macro, t.args,
self.defs['fnmacros'][t.macro]))
return "#define " + t.macro + " " + macro_val
def compile_fn_macro(self, text, args):
"""Turn a function macro spec into a compiled description.
"""
# Find all instances of each arg in text.
args_str = '|'.join(args)
arg_regex = re.compile(r'("(\\"|[^"])*")|(\b({})\b)'.format(args_str))
start = 0
parts = []
arg_order = []
# The group number to check for macro names
N = 3
for m in arg_regex.finditer(text):
arg = m.groups()[N]
if arg is not None:
parts.append(text[start:m.start(N)] + '{}')
start = m.end(N)
arg_order.append(args.index(arg))
parts.append(text[start:])
return (''.join(parts), arg_order)
def expand_macros(self, line):
"""Expand all the macro expressions in a string.
Faulty calls to macro function are left untouched.
"""
reg = re.compile(r'("(\\"|[^"])*")|(\b(\w+)\b)')
parts = []
# The group number to check for macro names
N = 3
macros = self.defs['macros']
fnmacros = self.defs['fnmacros']
while True:
m = reg.search(line)
if not m:
break
name = m.groups()[N]
if name in macros:
parts.append(line[:m.start(N)])
line = line[m.end(N):]
parts.append(macros[name])
elif name in fnmacros:
# If function macro expansion fails, just ignore it.
try:
exp, end = self.expand_fn_macro(name, line[m.end(N):])
except Exception:
exp = name
end = 0
mess = "Function macro expansion failed: {}, {}"
logger.error(mess.format(name, line[m.end(N):]))
parts.append(line[:m.start(N)])
start = end + m.end(N)
line = line[start:]
parts.append(exp)
else:
start = m.end(N)
parts.append(line[:start])
line = line[start:]
parts.append(line)
return ''.join(parts)
def expand_fn_macro(self, name, text):
"""Replace a function macro.
"""
# defn looks like ('%s + %s / %s', (0, 0, 1))
defn = self.defs['fnmacros'][name]
arg_list = (stringStart + lparen +
Group(delimitedList(expression))('args') + rparen)
res = [x for x in arg_list.scanString(text, 1)]
if len(res) == 0:
mess = "Function macro '{}' not followed by (...)"
raise DefinitionError(0, mess.format(name))
args, start, end = res[0]
args = [self.expand_macros(arg) for arg in args[0]]
new_str = defn[0].format(*[args[i] for i in defn[1]])
return (new_str, end)
# --- Compilation functions
def parse_defs(self, path, return_unparsed=False):
"""Scan through the named file for variable, struct, enum, and function
declarations.
Parameters
----------
path : unicode
Path of the file to parse for definitions.
return_unparsed : bool, optional
If true, return a string of all lines that failed to match (for
debugging purposes).
Returns
-------
tokens : list
Entire tree of successfully parsed tokens.
"""
self.current_file = path
parser = self.build_parser()
if return_unparsed:
text = parser.suppress().transformString(self.files[path])
return re.sub(r'\n\s*\n', '\n', text)
else:
return [x[0] for x in parser.scanString(self.files[path])]
def build_parser(self):
"""Builds the entire tree of parser elements for the C language (the
bits we support, anyway).
"""
if hasattr(self, 'parser'):
return self.parser
self.struct_type = Forward()
self.enum_type = Forward()
type_ = (fund_type |
Optional(kwl(size_modifiers + sign_modifiers)) + ident |
self.struct_type |
self.enum_type)
if extra_modifier is not None:
type_ += extra_modifier
type_.setParseAction(recombine)
self.type_spec = (type_qualifier('pre_qual') +
type_("name"))
# --- Abstract declarators for use in function pointer arguments
# Thus begins the extremely hairy business of parsing C declarators.
# Whomever decided this was a reasonable syntax should probably never
# breed.
# The following parsers combined with the process_declarator function
# allow us to turn a nest of type modifiers into a correctly
# ordered list of modifiers.
self.declarator = Forward()
self.abstract_declarator = Forward()
# Abstract declarators look like:
# <empty string>
# *
# **[num]
# (*)(int, int)
# *( )(int, int)[10]
# ...etc...
self.abstract_declarator << Group(
type_qualifier('first_typequal') +
Group(ZeroOrMore(Group(Suppress('*') + type_qualifier)))('ptrs') +
((Optional('&')('ref')) |
(lparen + self.abstract_declarator + rparen)('center')) +
Optional(lparen +
Optional(delimitedList(Group(
self.type_spec('type') +
self.abstract_declarator('decl') +
Optional(Literal('=').suppress() + expression,
default=None)('val')
)), default=None) +
rparen)('args') +
Group(ZeroOrMore(lbrack + Optional(expression, default='-1') +
rbrack))('arrays')
)
# Declarators look like:
# varName
# *varName
# **varName[num]
# (*fnName)(int, int)
# * fnName(int arg1=0)[10]
# ...etc...
self.declarator << Group(
type_qualifier('first_typequal') + call_conv +
Group(ZeroOrMore(Group(Suppress('*') + type_qualifier)))('ptrs') +
((Optional('&')('ref') + ident('name')) |
(lparen + self.declarator + rparen)('center')) +
Optional(lparen +
Optional(delimitedList(
Group(self.type_spec('type') +
(self.declarator |
self.abstract_declarator)('decl') +
Optional(Literal('=').suppress() +
expression, default=None)('val')
)),
default=None) +
rparen)('args') +
Group(ZeroOrMore(lbrack + Optional(expression, default='-1') +
rbrack))('arrays')
)
self.declarator_list = Group(delimitedList(self.declarator))
# Typedef
self.type_decl = (Keyword('typedef') + self.type_spec('type') +
self.declarator_list('decl_list') + semi)
self.type_decl.setParseAction(self.process_typedef)
# Variable declaration
self.variable_decl = (
Group(storage_class_spec +
self.type_spec('type') +
Optional(self.declarator_list('decl_list')) +
Optional(Literal('=').suppress() +
(expression('value') |
(lbrace +
Group(delimitedList(expression))('array_values') +
rbrace
)
)
)
) +
semi)
self.variable_decl.setParseAction(self.process_variable)
# Function definition
self.typeless_function_decl = (self.declarator('decl') +
nestedExpr('{', '}').suppress())
self.function_decl = (storage_class_spec +
self.type_spec('type') +
self.declarator('decl') +
nestedExpr('{', '}').suppress())
self.function_decl.setParseAction(self.process_function)
# Struct definition
self.struct_decl = Forward()
struct_kw = (Keyword('struct') | Keyword('union'))
self.struct_member = (
Group(self.variable_decl.copy().setParseAction(lambda: None)) |
# Hack to handle bit width specification.
Group(Group(self.type_spec('type') +
Optional(self.declarator_list('decl_list')) +
colon + integer('bit') + semi)) |
(self.type_spec + self.declarator +
nestedExpr('{', '}')).suppress() |
(self.declarator + nestedExpr('{', '}')).suppress()
)
self.decl_list = (lbrace +
Group(OneOrMore(self.struct_member))('members') +
rbrace)
self.struct_type << (struct_kw('struct_type') +
((Optional(ident)('name') +
self.decl_list) | ident('name'))
)
self.struct_type.setParseAction(self.process_struct)
self.struct_decl = self.struct_type + semi
# Enum definition
enum_var_decl = Group(ident('name') +
Optional(Literal('=').suppress() +
(integer('value') | ident('valueName'))))
self.enum_type << (Keyword('enum') +
(Optional(ident)('name') +
lbrace +
Group(delimitedList(enum_var_decl))('members') +
Optional(comma) + rbrace | ident('name'))
)
self.enum_type.setParseAction(self.process_enum)
self.enum_decl = self.enum_type + semi
self.parser = (self.type_decl | self.variable_decl |
self.function_decl)
return self.parser
def process_declarator(self, decl):
"""Process a declarator (without base type) and return a tuple
(name, [modifiers])
See process_type(...) for more information.
"""
toks = []
quals = [tuple(decl.get('first_typequal', []))]
name = None
logger.debug("DECL: {}".format(decl))
if 'call_conv' in decl and len(decl['call_conv']) > 0:
toks.append(decl['call_conv'])
quals.append(None)
if 'ptrs' in decl and len(decl['ptrs']) > 0:
toks += ('*',) * len(decl['ptrs'])
quals += map(tuple, decl['ptrs'])
if 'arrays' in decl and len(decl['arrays']) > 0:
toks.extend([self.eval_expr(x)] for x in decl['arrays'])
quals += [()] * len(decl['arrays'])
if 'args' in decl and len(decl['args']) > 0:
if decl['args'][0] is None:
toks.append(())
else:
toks.append(tuple([self.process_type(a['type'],
a['decl']) +
(a['val'][0],) for a in decl['args']]
)
)
quals.append(())
if 'ref' in decl:
toks.append('&')
quals.append(())
if 'center' in decl:
(n, t, q) = self.process_declarator(decl['center'][0])
if n is not None:
name = n
toks.extend(t)
quals = quals[:-1] + [quals[-1] + q[0]] + list(q[1:])
if 'name' in decl:
name = decl['name']
return (name, toks, tuple(quals))
def process_type(self, typ, decl):
"""Take a declarator + base type and return a serialized name/type
description.
The description will be a list of elements (name, [basetype, modifier,
modifier, ...]):
- name is the string name of the declarator or None for an abstract
declarator
- basetype is the string representing the base type
- modifiers can be:
- '*' : pointer (multiple pointers "***" allowed)
- '&' : reference
- '__X' : calling convention (windows only). X can be 'cdecl' or
'stdcall'
- list : array. Value(s) indicate the length of each array, -1
for incomplete type.
- tuple : function, items are the output of processType for each
function argument.
Examples:
- int *x[10] => ('x', ['int', [10], '*'])
- char fn(int x) => ('fn', ['char', [('x', ['int'])]])
- struct s (*)(int, int*) =>
(None, ["struct s", ((None, ['int']), (None, ['int', '*'])), '*'])
"""
logger.debug("PROCESS TYPE/DECL: {}/{}".format(typ['name'], decl))
(name, decl, quals) = self.process_declarator(decl)
pre_typequal = tuple(typ.get('pre_qual', []))
return (name, Type(typ['name'], *decl,
type_quals=(pre_typequal + quals[0],) + quals[1:]))
def process_enum(self, s, l, t):
"""
"""
try:
logger.debug("ENUM: {}".format(t))
if t.name == '':
n = 0
while True:
name = 'anon_enum{}'.format(n)
if name not in self.defs['enums']:
break
n += 1
else:
name = t.name[0]
logger.debug(" name: {}".format(name))
if name not in self.defs['enums']:
i = 0
enum = {}
for v in t.members:
if v.value != '':
i = literal_eval(v.value)
if v.valueName != '':
i = enum[v.valueName]
enum[v.name] = i
self.add_def('values', v.name, i)
i += 1
logger.debug(" members: {}".format(enum))
self.add_def('enums', name, enum)
self.add_def('types', 'enum '+name, Type('enum', name))
return ('enum ' + name)
except:
logger.exception("Error processing enum: {}".format(t))
def process_function(self, s, l, t):
"""Build a function definition from the parsing tokens.
"""
logger.debug("FUNCTION {} : {}".format(t, t.keys()))
try:
(name, decl) = self.process_type(t.type, t.decl[0])
if len(decl) == 0 or type(decl[-1]) != tuple:
logger.error('{}'.format(t))
mess = "Incorrect declarator type for function definition."
raise DefinitionError(mess)
logger.debug(" name: {}".format(name))
logger.debug(" sig: {}".format(decl))
self.add_def('functions', name, decl.add_compatibility_hack())
except Exception:
logger.exception("Error processing function: {}".format(t))
def packing_at(self, line):
"""Return the structure packing value at the given line number.
"""
packing = None
for p in self.pack_list[self.current_file]:
if p[0] <= line:
packing = p[1]
else:
break
return packing
def process_struct(self, s, l, t):
"""
"""
try:
str_typ = t.struct_type # struct or union
# Check for extra packing rules
packing = self.packing_at(lineno(l, s))
logger.debug('{} {} {}'.format(str_typ.upper(), t.name, t))
if t.name == '':
n = 0
while True:
sname = 'anon_{}{}'.format(str_typ, n)
if sname not in self.defs[str_typ+'s']:
break
n += 1
else:
if istext(t.name):
sname = t.name
else:
sname = t.name[0]
logger.debug(" NAME: {}".format(sname))
if (len(t.members) > 0 or sname not in self.defs[str_typ+'s'] or
self.defs[str_typ+'s'][sname] == {}):
logger.debug(" NEW " + str_typ.upper())
struct = []
for m in t.members:
typ = m[0].type
val = self.eval_expr(m[0].value)
logger.debug(" member: {}, {}, {}".format(
m, m[0].keys(), m[0].decl_list))
if len(m[0].decl_list) == 0: # anonymous member
member = [None, Type(typ[0]), None]
if m[0].bit:
member.append(int(m[0].bit))
struct.append(tuple(member))
for d in m[0].decl_list:
(name, decl) = self.process_type(typ, d)
member = [name, decl, val]
if m[0].bit:
member.append(int(m[0].bit))
struct.append(tuple(member))
logger.debug(" {} {} {} {}".format(name, decl,
val, m[0].bit))
str_cls = (Struct if str_typ == 'struct' else Union)
self.add_def(str_typ + 's', sname,
str_cls(*struct, pack=packing))
self.add_def('types', str_typ+' '+sname, Type(str_typ, sname))
return str_typ + ' ' + sname
except Exception:
logger.exception('Error processing struct: {}'.format(t))
def process_variable(self, s, l, t):
"""
"""
logger.debug("VARIABLE: {}".format(t))
try:
val = self.eval_expr(t[0])
for d in t[0].decl_list:
(name, typ) = self.process_type(t[0].type, d)
# This is a function prototype
if type(typ[-1]) is tuple:
logger.debug(" Add function prototype: {} {} {}".format(
name, typ, val))
self.add_def('functions', name,
typ.add_compatibility_hack())
# This is a variable
else:
logger.debug(" Add variable: {} {} {}".format(name,
typ, val))
self.add_def('variables', name, (val, typ))
self.add_def('values', name, val)
except Exception:
logger.exception('Error processing variable: {}'.format(t))
def process_typedef(self, s, l, t):
"""
"""
logger.debug("TYPE: {}".format(t))
typ = t.type
for d in t.decl_list:
(name, decl) = self.process_type(typ, d)
logger.debug(" {} {}".format(name, decl))
self.add_def('types', name, decl)
# --- Utility methods
def eval_expr(self, toks):
"""Evaluates expressions.
Currently only works for expressions that also happen to be valid
python expressions.
"""
logger.debug("Eval: {}".format(toks))
try:
if istext(toks) or isbytes(toks):
val = self.eval(toks, None, self.defs['values'])
elif toks.array_values != '':
val = [self.eval(x, None, self.defs['values'])
for x in toks.array_values]
elif toks.value != '':
val = self.eval(toks.value, None, self.defs['values'])
else:
val = None
return val
except Exception:
logger.debug(" failed eval {} : {}".format(toks, format_exc()))
return None
def eval(self, expr, *args):
"""Just eval with a little extra robustness."""
expr = expr.strip()
cast = (lparen + self.type_spec + self.abstract_declarator +
rparen).suppress()
expr = (quotedString | number | cast).transformString(expr)
if expr == '':
return None
return eval(expr, *args)
def add_def(self, typ, name, val):
"""Add a definition of a specific type to both the definition set for
the current file and the global definition set.
"""
self.defs[typ][name] = val
if self.current_file is None:
base_name = None
else:
base_name = os.path.basename(self.current_file)
if base_name not in self.file_defs:
self.file_defs[base_name] = {}
for k in self.data_list:
self.file_defs[base_name][k] = {}
self.file_defs[base_name][typ][name] = val
def rem_def(self, typ, name):
"""Remove a definition of a specific type to both the definition set
for the current file and the global definition set.
"""
if self.current_file is None:
base_name = None
else:
base_name = os.path.basename(self.current_file)
del self.defs[typ][name]
del self.file_defs[base_name][typ][name]
def is_fund_type(self, typ):
"""Return True if this type is a fundamental C type, struct, or
union.
**ATTENTION: This function is legacy and should be replaced by
Type.is_fund_type()**
"""
return Type(typ).is_fund_type()
def eval_type(self, typ):
"""Evaluate a named type into its fundamental type.
**ATTENTION: This function is legacy and should be replaced by
Type.eval()**
"""
if not isinstance(typ, Type):
typ = Type(*typ)
return typ.eval(self.defs['types'])
def find(self, name):
"""Search all definitions for the given name.
"""
res = []
for f in self.file_defs:
fd = self.file_defs[f]
for t in fd:
typ = fd[t]
for k in typ:
if istext(name):
if k == name:
res.append((f, t))
else:
if re.match(name, k):
res.append((f, t, k))
return res
def find_text(self, text):
"""Search all file strings for text, return matching lines.
"""
res = []
for f in self.files:
l = self.files[f].split('\n')
for i in range(len(l)):
if text in l[i]:
res.append((f, i, l[i]))
return res
# --- Basic parsing elements.
def kwl(strs):
"""Generate a match-first list of keywords given a list of strings."""
return Regex(r'\b({})\b'.format('|'.join(strs)))
def flatten(lst):
res = []
for i in lst:
if isinstance(i, (list, tuple)):
res.extend(flatten(i))
else:
res.append(str(i))
return res
def recombine(tok):
"""Flattens a tree of tokens and joins into one big string.
"""
return " ".join(flatten(tok.asList()))
def print_parse_results(pr, depth=0, name=''):
"""For debugging; pretty-prints parse result objects.
"""
start = name + " " * (20 - len(name)) + ':' + '..' * depth
if isinstance(pr, ParseResults):
print(start)
for i in pr:
name = ''
for k in pr.keys():
if pr[k] is i:
name = k
break
print_parse_results(i, depth+1, name)
else:
print(start + str(pr))
# Syntatic delimiters
comma = Literal(",").ignore(quotedString).suppress()
colon = Literal(":").ignore(quotedString).suppress()
semi = Literal(";").ignore(quotedString).suppress()
lbrace = Literal("{").ignore(quotedString).suppress()
rbrace = Literal("}").ignore(quotedString).suppress()
lbrack = Literal("[").ignore(quotedString).suppress()
rbrack = Literal("]").ignore(quotedString).suppress()
lparen = Literal("(").ignore(quotedString).suppress()
rparen = Literal(")").ignore(quotedString).suppress()
# Numbers
int_strip = lambda t: t[0].rstrip('UL')
hexint = Regex('[+-]?\s*0[xX][{}]+[UL]*'.format(hexnums)).setParseAction(int_strip)
decint = Regex('[+-]?\s*[0-9]+[UL]*').setParseAction(int_strip)
integer = (hexint | decint)
# The floating regex is ugly but it is because we do not want to match
# integer to it.
floating = Regex(r'[+-]?\s*((((\d(\.\d*)?)|(\.\d+))[eE][+-]?\d+)|((\d\.\d*)|(\.\d+)))')
number = (floating | integer)
# Miscelaneous
bi_operator = oneOf("+ - / * | & || && ! ~ ^ % == != > < >= <= -> . :: << >> = ? :")
uni_right_operator = oneOf("++ --")
uni_left_operator = oneOf("++ -- - + * sizeof new")
wordchars = alphanums+'_$'
name = (WordStart(wordchars) + Word(alphas+"_", alphanums+"_$") +
WordEnd(wordchars))
size_modifiers = ['short', 'long']
sign_modifiers = ['signed', 'unsigned']
# Syntax elements defined by _init_parser.
expression = Forward()
array_op = lbrack + expression + rbrack
base_types = None
ident = None
call_conv = None
type_qualifier = None
storage_class_spec = None
extra_modifier = None
fund_type = None
extra_type_list = []
num_types = ['int', 'float', 'double']
nonnum_types = ['char', 'bool', 'void']
# Define some common language elements when initialising.
def _init_cparser(extra_types=None, extra_modifiers=None):
global expression
global call_conv, ident
global base_types
global type_qualifier, storage_class_spec, extra_modifier
global fund_type
global extra_type_list
# Some basic definitions
extra_type_list = [] if extra_types is None else list(extra_types)
base_types = nonnum_types + num_types + extra_type_list
storage_classes = ['inline', 'static', 'extern']
qualifiers = ['const', 'volatile', 'restrict', 'near', 'far']
keywords = (['struct', 'enum', 'union', '__stdcall', '__cdecl'] +
qualifiers + base_types + size_modifiers + sign_modifiers)
keyword = kwl(keywords)
wordchars = alphanums+'_$'
ident = (WordStart(wordchars) + ~keyword +
Word(alphas + "_", alphanums + "_$") +
WordEnd(wordchars)).setParseAction(lambda t: t[0])
call_conv = Optional(Keyword('__cdecl') |
Keyword('__stdcall'))('call_conv')
# Removes '__name' from all type specs. may cause trouble.
underscore_2_ident = (WordStart(wordchars) + ~keyword + '__' +
Word(alphanums, alphanums+"_$") +
WordEnd(wordchars)).setParseAction(lambda t: t[0])
type_qualifier = ZeroOrMore((underscore_2_ident + Optional(nestedExpr())) |
kwl(qualifiers))
storage_class_spec = Optional(kwl(storage_classes))
if extra_modifiers:
extra_modifier = ZeroOrMore(kwl(extra_modifiers) +
Optional(nestedExpr())).suppress()
else:
extra_modifier = None
# Language elements
fund_type = OneOrMore(kwl(sign_modifiers + size_modifiers +
base_types)).setParseAction(lambda t: ' '.join(t))
# Is there a better way to process expressions with cast operators??
cast_atom = (
ZeroOrMore(uni_left_operator) + Optional('('+ident+')').suppress() +
((ident + '(' + Optional(delimitedList(expression)) + ')' |
ident + OneOrMore('[' + expression + ']') |
ident | number | quotedString
) |
('(' + expression + ')')) +
ZeroOrMore(uni_right_operator)
)
# XXX Added name here to catch macro functions on types
uncast_atom = (
ZeroOrMore(uni_left_operator) +
((ident + '(' + Optional(delimitedList(expression)) + ')' |
ident + OneOrMore('[' + expression + ']') |
ident | number | name | quotedString
) |
('(' + expression + ')')) +
ZeroOrMore(uni_right_operator)
)
atom = cast_atom | uncast_atom
expression << Group(atom + ZeroOrMore(bi_operator + atom))
expression.setParseAction(recombine)
| mrh1997/pyclibrary | pyclibrary/c_parser.py | Python | mit | 62,500 |
package com.slicer.utils;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Texture;
public class AssetLoader {
public static Texture bgGame, bgGameOver, bgFinish, score, soundOn, soundOff;
public static Sound gameOver, victory, slice, click;
public static FileHandle levelsFile;
public static boolean sound = true;
public static void load() {
bgGame = new Texture(Gdx.files.internal("data/images/bg1.jpeg"));
bgGameOver = new Texture(Gdx.files.internal("data/images/bg3.png"));
bgFinish = new Texture(Gdx.files.internal("data/images/bg2.png"));
soundOn = new Texture(Gdx.files.internal("data/images/on.png"));
soundOff = new Texture(Gdx.files.internal("data/images/off.png"));
score = new Texture(Gdx.files.internal("data/images/score.png"));
gameOver = Gdx.audio.newSound(Gdx.files.internal("data/sound/gameOver.wav"));
victory = Gdx.audio.newSound(Gdx.files.internal("data/sound/victory.wav"));
slice = Gdx.audio.newSound(Gdx.files.internal("data/sound/slice.wav"));
click = Gdx.audio.newSound(Gdx.files.internal("data/sound/click.wav"));
levelsFile = Gdx.files.internal("data/levels/levels.json");
}
public static void play(Sound s) {
if (sound)
s.play();
}
public static void dispose() {
bgGame.dispose();
bgGameOver.dispose();
bgFinish.dispose();
gameOver.dispose();
victory.dispose();
slice.dispose();
}
} | burakkose/libgdx-game-slicer | core/src/com/slicer/utils/AssetLoader.java | Java | mit | 1,612 |
/*
Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'iframe', 'ko', {
border: '프레임 테두리 표시',
noUrl: '아이프레임 주소(URL)를 입력해주세요.',
scrolling: '스크롤바 사용',
title: '아이프레임 속성',
toolbar: '아이프레임'
} );
| otto-torino/gino | ckeditor/plugins/iframe/lang/ko.js | JavaScript | mit | 424 |
/**
* Hydro configuration
*
* @param {Hydro} hydro
*/
module.exports = function(hydro) {
hydro.set({
suite: 'equals',
timeout: 500,
plugins: [
require('hydro-chai'),
require('hydro-bdd')
],
chai: {
chai: require('chai'),
styles: ['should'],
stack: true
}
})
}
| jkroso/equals | test/hydro.conf.js | JavaScript | mit | 324 |
# -*- coding: utf-8 -*-
from datetime import timedelta, datetime
import asyncio
import random
from .api import every, once_at, JobSchedule, default_schedule_manager
__all__ = ['every_day', 'every_week', 'every_monday', 'every_tuesday', 'every_wednesday',
'every_thursday', 'every_friday', 'every_saturday', 'every_sunday',
'once_at_next_monday', 'once_at_next_tuesday', 'once_at_next_wednesday',
'once_at_next_thursday', 'once_at_next_friday', 'once_at_next_saturday',
'once_at_next_sunday', 'every_random_interval']
def every_random_interval(job, interval: timedelta, loop=None):
"""
executes the job randomly once in the specified interval.
example:
run a job every day at random time
run a job every hour at random time
:param job: a callable(co-routine function) which returns
a co-routine or a future or an awaitable
:param interval: the interval can also be given in the format of datetime.timedelta,
then seconds, minutes, hours, days, weeks parameters are ignored.
:param loop: io loop if the provided job is a custom future linked up
with a different event loop.
:return: schedule object, so it could be cancelled at will of the user by
aschedule.cancel(schedule)
"""
if loop is None:
loop = asyncio.get_event_loop()
start = loop.time()
def wait_time_gen():
count = 0
while True:
rand = random.randrange(round(interval.total_seconds()))
tmp = round(start + interval.total_seconds() * count + rand - loop.time())
yield tmp
count += 1
schedule = JobSchedule(job, wait_time_gen(), loop=loop)
# add it to default_schedule_manager, so that user can aschedule.cancel it
default_schedule_manager.add_schedule(schedule)
return schedule
def every_day(job, loop=None):
return every(job, timedelta=timedelta(days=1), loop=loop)
def every_week(job, loop=None):
return every(job, timedelta=timedelta(days=7), loop=loop)
every_monday = lambda job, loop=None: _every_weekday(job, 0, loop=loop)
every_tuesday = lambda job, loop=None: _every_weekday(job, 1, loop=loop)
every_wednesday = lambda job, loop=None: _every_weekday(job, 2, loop=loop)
every_thursday = lambda job, loop=None: _every_weekday(job, 3, loop=loop)
every_friday = lambda job, loop=None: _every_weekday(job, 4, loop=loop)
every_saturday = lambda job, loop=None: _every_weekday(job, 5, loop=loop)
every_sunday = lambda job, loop=None: _every_weekday(job, 6, loop=loop)
once_at_next_monday = lambda job, loop=None: _once_at_weekday(job, 0, loop=loop)
once_at_next_tuesday = lambda job, loop=None: _once_at_weekday(job, 1, loop=loop)
once_at_next_wednesday = lambda job, loop=None: _once_at_weekday(job, 2, loop=loop)
once_at_next_thursday = lambda job, loop=None: _once_at_weekday(job, 3, loop=loop)
once_at_next_friday = lambda job, loop=None: _once_at_weekday(job, 4, loop=loop)
once_at_next_saturday = lambda job, loop=None: _once_at_weekday(job, 5, loop=loop)
once_at_next_sunday = lambda job, loop=None: _once_at_weekday(job, 6, loop=loop)
def _nearest_weekday(weekday):
return datetime.now() + timedelta(days=(weekday - datetime.now().weekday()) % 7)
def _every_weekday(job, weekday, loop=None):
return every(job, timedelta=timedelta(days=7), start_at=_nearest_weekday(weekday), loop=loop)
def _once_at_weekday(job, weekday, loop=None):
return once_at(job, _nearest_weekday(weekday), loop=loop)
| eightnoteight/aschedule | aschedule/ext.py | Python | mit | 3,564 |
import {QueryContext} from "../common/QueryContext";
import {IBoundQueryPart} from "./IBoundQueryPart";
export interface IQueryPart {
toCypher(ctx:QueryContext):IBoundQueryPart
} | robak86/neography | lib/cypher/abstract/IQueryPart.ts | TypeScript | mit | 183 |
package com.raymond.entrypoint;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import javax.servlet.http.HttpServletResponse;
/**
* Created by Raymond Kwong on 12/1/2018.
*/
@Qualifier("handlerExceptionResolver")
@RestControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(AuthenticationException.class)
public ErrorResponseBean handleAuthenticationException(AuthenticationException exception, HttpServletResponse response){
ErrorResponseBean errorResponseBean = new ErrorResponseBean();
errorResponseBean.setError(HttpStatus.UNAUTHORIZED.getReasonPhrase());
errorResponseBean.setMessage(exception.getMessage());
response.setStatus(HttpStatus.UNAUTHORIZED.value());
return errorResponseBean;
}
} | RaymondKwong/raymond_projects | services/jwtauth/src/main/java/com/raymond/entrypoint/GlobalExceptionHandler.java | Java | mit | 1,163 |
require 'spec_helper'
describe Dashdog do
it 'has a version number' do
expect(Dashdog::VERSION).not_to be nil
end
end
| serverworks/dashdog | spec/dashdog_spec.rb | Ruby | mit | 127 |