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 |
|---|---|---|---|---|---|
namespace ArchitectNow.ApiStarter.Api.Models.ViewModels
{
public class LoginResultVm
{
public string AuthToken { get; set; }
public UserVm CurrentUser { get; set; }
}
} | ArchitectNow/ArchitectNow.ApiStarter | src/ArchitectNow.ApiStarter.Api/Models/ViewModels/LoginResultVm.cs | C# | mit | 199 |
class ExpressionRelationshipType < ActiveRecord::Base
attr_accessible :name, :position, :definition, :url
acts_as_list
end
| nabeta/enju_root | app/models/expression_relationship_type.rb | Ruby | mit | 127 |
<?php
#############################################################################
# IMDBPHP (c) Giorgos Giagas & Itzchak Rehberg #
# written by Giorgos Giagas #
# extended & maintained by Itzchak Rehberg <izzysoft AT qumran DOT org> #
# http://www.izzysoft.de/ #
# ------------------------------------------------------------------------- #
# Budget data (c) Isyankar #
# ------------------------------------------------------------------------- #
# This program is free software; you can redistribute and/or modify it #
# under the terms of the GNU General Public License (see doc/LICENSE) #
#############################################################################
/* $Id: imdb_budget.class.php 482 2011-10-27 15:24:38Z izzy $ */
require_once (dirname(__FILE__)."/movie_base.class.php");
#=============================================================================
#=================================================[ The IMDB class itself ]===
#=============================================================================
/** Accessing IMDB Budget Data
* @package IMDB
* @class imdb_budget
* @extends movie_base
* @author Isyankar
* @author Izzy (izzysoft AT qumran DOT org)
* @version $Revision: 482 $ $Date: 2011-10-27 17:24:38 +0200 (Do, 27. Okt 2011) $
*/
class imdb_budget extends movie_base {
#======================================================[ Common functions ]===
#-----------------------------------------------------------[ Constructor ]---
/** Initialize the class
* @constructor imdb_budget
* @param string id IMDBID to use for data retrieval
*/
function __construct($id) {
parent::__construct($id);
$this->revision = preg_replace('|^.*?(\d+).*$|','$1','$Revision: 482 $');
$this->setid($id);
$this->reset_vars();
}
#--------------------------------------------------[ Start (over) / Reset ]---
/** Reset page vars
* @method protected reset_vars
*/
protected function reset_vars() {
$this->budget = '';
$this->openingWeekend = array();
$this->gross = array();
$this->weekendGross = array();
$this->admissions = array();
$this->filmingDates = array();
}
#-------------------------------------------------------------[ Open Page ]---
/** Define page urls
* @method protected set_pagename
* @param string wt internal name of the page
* @return string urlname page URL
*/
protected function set_pagename($wt) {
switch ($wt){
case "BoxOffice" : $urlname="/business"; break;
default :
$this->page[$wt] = "unknown page identifier";
$this->debug_scalar("Unknown page identifier: $wt");
return false;
}
return $urlname;
}
#-----------------------------------------------[ URL to movies main page ]---
/** Set up the URL to the movie title page
* @method main_url
* @return string url full URL to the current movies main page
*/
public function main_url(){
return "http://".$this->imdbsite."/title/tt".$this->imdbid()."/";
}
#====================================================[ /business page ]===
/* Get budget
* @method get_budget
* @param ref string budg
* @return string
* @brief Assuming budget is estimated, and in american dollar
* @see IMDB page / (TitlePage)
*/
private function get_budget(&$budg){
// Tries to get a single entry
if (@preg_match("!(.*?)\s*\(estimated\)!ims",$budg,$opWe)){
$result = $opWe[1];
return intval(substr(str_replace(",","",$result), 1));
}
else return "";
} // End of get_budget
/* Get budget
* @method get_budget
* @return string
* @brief Assuming budget is estimated, and in american dollar
* @see IMDB page / (TitlePage)
*/
public function budget() {
if (empty($this->budget)) {
if ($this->page["BoxOffice"] == "") $this->openpage ("BoxOffice");
if ($this->page["BoxOffice"] == "cannot open page" ) return $this->budget; // no such page
if (@preg_match("!<h5>Budget</h5>\s*\n*(.*?)(<br/>\n*)*<h5!ims",$this->page["BoxOffice"],$bud)) // Opening Weekend
$budget = $bud[1];
$this->budget = $this->get_budget($budget);
}
return $this->budget;
}
#-------------------------------------------------[ Openingbudget ]---
/** Get opening weekend budget
* @method get_openingWeekend
* @param ref string listOpening
* @return array[0..n] of array[value,country,date,nbScreens]
* @see IMDB page
*/
private function get_openingWeekend(&$listOpening){
$result = array();
$temp = $listOpening;
$i = 0;
while($temp != NULL){
// Tries to get a single entry
if (@preg_match("!(.*?)<br/>!ims",$temp,$opWe))
$entry = $opWe[1];
// Tries to extract the value
if (@preg_match("!(.*?)\(!ims",$opWe[1],$value))
$opWe[1] = str_replace($value,"",$opWe[1]);
// Tries to extract the country
if (@preg_match("!(.*?)\)\s*!ims",$opWe[1],$country))
$opWe[1] = str_replace($country,"",$opWe[1]);
// Tries to extract the date
if (@preg_match("!\((.*?)\)\s*!ims",$opWe[1],$date))
if (@preg_match("!<a href=\"/date/(.*?)/\">!ims",$date[1],$dayMonth))
if (@preg_match("!<a href=\"/year/(.*?)/\">!ims",$date[1],$year))
$dateValue = $year[1].'-'.$dayMonth[1];
$opWe[1] = str_replace($date,"",$opWe[1]);
// Tries to extract the number of screens
if (@preg_match("!\((.*?)\)\s*!ims",$opWe[1],$nbScreen))
$opWe[1] = str_replace($nbScreen,"",$opWe[1]);
// Parse the results in an array
$result[$i] = array(
'value' => $value[1],
'country' => $country[1],
'date' => $dateValue,
'nbScreens' => intval(str_replace(",","",$nbScreen[1]))
);
// Remove the entry from the list of entries
if (@preg_match("!<br/>(.*?)$!ims",$temp,$temp))
$temp = $temp[1];
$i++;
}
return $result;
} // End of get_openingWeekend
/** Opening weekend budget
* @method openingWeekend
* @return array[0..n] of array[value,country,date,nbScreens]
* @see IMDB page
*/
public function openingWeekend() {
if (empty($this->openingWeekend)) {
if ($this->page["BoxOffice"] == "") $this->openpage ("BoxOffice");
if ($this->page["BoxOffice"] == "cannot open page" ) return $this->openingWeekend; // no such page
if (@preg_match("!<h5>Opening Weekend</h5>\n*(.*?)<br/>\n*<h5!ims",$this->page["BoxOffice"],$opWe)) // Opening Weekend
$openingWeekend = $opWe[1];
$this->openingWeekend = $this->get_openingWeekend($openingWeekend);
}
return $this->openingWeekend;
}
#-------------------------------------------------[ Gross ]---
/** Get gross budget
* @method get_gross
* @param ref string listGross
* @return array[0..n] of array[value,country,date]
* @see IMDB page / (TitlePage)
*/
private function get_gross(&$listGross) {
$result = array();
$temp = $listGross;
$i = 0;
while($temp != NULL){
// Tries to get a single entry
if (@preg_match("!(.*?)<br/>!ims",$temp,$gr))
$entry = $gr[1];
//echo 'ici'.$entry.'ici';
// Tries to extract the value
if (@preg_match("!(.*?)\(!ims",$gr[1],$value))
$gr[1] = str_replace($value,"",$gr[1]);
// Tries to extract the country
if (@preg_match("!(.*?)\)\s*!ims",$gr[1],$country))
$gr[1] = str_replace($country,"",$gr[1]);
// Tries to extract the date
if (@preg_match("!\((.*?)\)\s*!ims",$gr[1],$date))
if (@preg_match("!<a href=\"/date/(.*?)/\">!ims",$date[1],$dayMonth))
if (@preg_match("!<a href=\"/year/(.*?)/\">!ims",$date[1],$year))
$dateValue = $year[1].'-'.$dayMonth[1];
$gr[1] = str_replace($date,"",$gr[1]);
// Parse the results in an array
$result[$i] = array(
'value' => $value[1],
'country' => $country[1],
'date' => $dateValue,
);
// Remove the entry from the list of entries
if (@preg_match("!<br/>(.*?)$!ims",$temp,$temp))
$temp = $temp[1];
$i++;
}
return $result;
} // End of get_gross
/** Get gross budget
* @method gross
* @return array[0..n] of array[value,country,date]
* @see IMDB page / (TitlePage)
*/
public function gross() {
if (empty($this->gross)) {
if ($this->page["BoxOffice"] == "") $this->openpage ("BoxOffice");
if ($this->page["BoxOffice"] == "cannot open page" ) return $this->gross; // no such page
if (@preg_match("!<h5>Gross</h5>\n*(.*?)<br/>\n*<h5!ims",$this->page["BoxOffice"],$gr)) // Gross
$gross = $gr[1];
$this->gross = $this->get_gross($gross);
}
return $this->gross;
}
#-------------------------------------------------[ Weekend Gross ]---
/** Get weekend gross budget
* @method get_weekendGross
* @param ref string listweekendGross
* @return array[0..n] of array[value,country,date,nbScreens]
* @see IMDB page / (TitlePage)
*/
private function get_weekendGross(&$listweekendGross){
$result = array();
$temp = $listweekendGross;
$i = 0;
while($temp != NULL){
// Tries to get a single entry
if (@preg_match("!(.*?)<br/>!ims",$temp,$weGr))
$entry = $weGr[1];
// Tries to extract the value
if (@preg_match("!(.*?)\(!ims",$weGr[1],$value))
$weGr[1] = str_replace($value,"",$weGr[1]);
// Tries to extract the country
if (@preg_match("!(.*?)\)\s*!ims",$weGr[1],$country))
$weGr[1] = str_replace($country,"",$weGr[1]);
// Tries to extract the date
if (@preg_match("!\((.*?)\)\s*!ims",$weGr[1],$date))
if (@preg_match("!<a href=\"/date/(.*?)/\">!ims",$date[1],$dayMonth))
if (@preg_match("!<a href=\"/year/(.*?)/\">!ims",$date[1],$year))
$dateValue = $year[1].'-'.$dayMonth[1];
$weGr[1] = str_replace($date,"",$weGr[1]);
// Tries to extract the number of screens
if (@preg_match("!\((.*?)\)\s*!ims",$weGr[1],$nbScreen))
$weGr[1] = str_replace($nbScreen,"",$weGr[1]);
// Parse the results in an array
$result[$i] = array(
'value' => $value[1],
'country' => $country[1],
'date' => $dateValue,
'nbScreens' => intval(str_replace(",","",$nbScreen[1]))
);
// Remove the entry from the list of entries
if (@preg_match("!<br/>(.*?)$!ims",$temp,$temp))
$temp = $temp[1];
$i++;
}
return $result;
} // End of get_weekendGross
/** Get weekend gross budget
* @method weekendGross
* @return array[0..n] of array[value,country,date,nbScreen]
* @see IMDB page / (TitlePage)
*/
public function weekendGross() {
if (empty($this->weekendGross)) {
if ($this->page["BoxOffice"] == "") $this->openpage ("BoxOffice");
if ($this->page["BoxOffice"] == "cannot open page" ) return $this->weekendGross; // no such page
if (@preg_match("!<h5>Weekend Gross</h5>\n*(.*?)<br/>\n*<h5!ims",$this->page["BoxOffice"],$weGr)) // Weekend Gross
$weekendGross = $weGr[1];
$this->weekendGross = $this->get_weekendGross($weekendGross);
}
return $this->weekendGross;
} // End of weekendGross
#-------------------------------------------------[ Admissions ]---
/** Get admissions budget
* @method get_admissions
* @param ref string listAdmissions
* @return array[0..n] of array[value,country,date]
* @see IMDB page / (TitlePage)
*/
private function get_admissions(&$listAdmissions) {
$result = array();
$temp = $listAdmissions;
$i = 0;
while($temp != NULL){
// Tries to get a single entry
if (@preg_match("!(.*?)<br/>!ims",$temp,$adm))
$entry = $adm[1];
// Tries to extract the value
if (@preg_match("!(.*?)\(!ims",$adm[1],$value))
$adm[1] = str_replace($value,"",$adm[1]);
// Tries to extract the country
if (@preg_match("!(.*?)\)\s*!ims",$adm[1],$country))
$adm[1] = str_replace($country,"",$adm[1]);
// Tries to extract the date
if (@preg_match("!\((.*?)\)\s*!ims",$adm[1],$date))
if (@preg_match("!<a href=\"/date/(.*?)/\">!ims",$date[1],$dayMonth))
if (@preg_match("!<a href=\"/year/(.*?)/\">!ims",$date[1],$year))
$dateValue = $year[1].'-'.$dayMonth[1];
$adm[1] = str_replace($date,"",$adm[1]);
// Parse the results in an array
$result[$i] = array(
'value' => intval(str_replace(",","",$value[1])),
'country' => $country[1],
'date' => $dateValue,
);
// Remove the entry from the list of entries
if (@preg_match("!<br/>(.*?)$!ims",$temp,$temp))
$temp = $temp[1];
$i++;
}
return $result;
} // End of get_admissions
/** Get admissions budget
* @method admissions
* @return array[0..n] of array[value,country,date]
* @see IMDB page / (TitlePage)
*/
public function admissions() {
if (empty($this->admissions)) {
if ($this->page["BoxOffice"] == "") $this->openpage ("BoxOffice");
if ($this->page["BoxOffice"] == "cannot open page" ) return $this->admissions; // no such page
if (@preg_match("!<h5>Admissions</h5>\n*(.*?)<br/>\n*<h5!ims",$this->page["BoxOffice"],$weGr)) // Admissions
$admissions = $weGr[1];
$this->admissions = $this->get_admissions($admissions);
}
return $this->admissions;
} // End of admissions
#-------------------------------------------------[ Filming Dates ]---
/** Get filming dates
* @method get_filmingDates
* @param ref string listFilmingDates
* @return array[0..n] of array[beginning,end]
* Time format : YYYY-MM-DD
* @see IMDB page / (TitlePage)
*/
function get_filmingDates($listFilmingDates){
$result = array();
$temp = $listFilmingDates;
// Tries to get the beginning
if (@preg_match("!(.*?) -!ims",$temp,$beginning))
if (@preg_match("#[A-Z0-9]#",$beginning[1])) { // Check if there is a date
if (@preg_match("!<a(.*?) -!ims",$temp)) { // Check if there is a linked date
if (@preg_match("!<a href=\"/date/(.*?)/\">!ims",$beginning[1],$dayMonthB))
if (@preg_match("!<a href=\"/year/(.*?)/\">!ims",$beginning[1],$yearB))
$beginningDate = $yearB[1].'-'.$dayMonthB[1];
} else if (@preg_match("!(.*?) -!ims",$temp,$beginning)) {
$beginningDate = date('Y-m-d', strtotime($beginning[1]));
}
}
// Tries to get the end
if (@preg_match("!- (.*?)$!ims",$temp,$end))
if (@preg_match("#[A-Z0-9]#",$end[1])) { // Check if there is a date
if (@preg_match("!- <a(.*?)!ims",$temp)) { // Check if there is a linked date
if (@preg_match("!<a href=\"/date/(.*?)/\">!ims",$end[1],$dayMonthE))
if (@preg_match("!<a href=\"/year/(.*?)/\">!ims",$end[1],$yearE))
$endDate = $yearE[1].'-'.$dayMonthE[1];
} else if (@preg_match("!- (.*?)$!ims",$temp,$end)) {
$endDate = date('Y-m-d', strtotime($end[1]));
}
}
// Parse the results in an array
$result = array(
'beginning' => $beginningDate,
'end' => $endDate
);
return $result;
} // End of get_filmingDates
/** Get filming dates
* @method filmingDates
* @return array[0..n] of array[beginning,end]
* Time format : YYYY-MM-DD
* @see IMDB page / (TitlePage)
*/
public function filmingDates() {
if (empty($this->filmingDates)) {
if ($this->page["BoxOffice"] == "") $this->openpage ("BoxOffice");
if ($this->page["BoxOffice"] == "cannot open page" ) return $this->filmingDates; // no such page
if (@preg_match("!<h5>Filming Dates</h5>\s*\n*(.*?)(<br/>\n*)*<h5!ims",$this->page["BoxOffice"],$filDates)) // Filming Dates
$filmingDates = $filDates[1];
$this->filmingDates = $this->get_filmingDates($filmingDates);
}
return $this->filmingDates;
} // End of filmingDates
} // end class imdb_budget
?> | rnavarro/Movie-Magic | imdbphp2/imdb_budget.class.php | PHP | mit | 15,927 |
/*jshint node: true, eqnull: true*/
exports.purge = require('./lib/purge').AkamaiPurge; | patrickkettner/grunt-akamai-clear | node_modules/akamai/akamai.js | JavaScript | mit | 88 |
() => {
const [startDate, setStartDate] = useState(new Date());
let handleColor = (time) => {
return time.getHours() > 12 ? "text-success" : "text-error";
};
return (
<DatePicker
showTimeSelect
selected={startDate}
onChange={(date) => setStartDate(date)}
timeClassName={handleColor}
/>
);
};
| Hacker0x01/react-datepicker | docs-site/src/examples/customTimeClassName.js | JavaScript | mit | 340 |
'use strict';
var arg = require('../util').arg;
var oneDHeightmapFactory = require('../1d-heightmap');
var rng = require('../rng');
var random = rng.float;
var randomRange = rng.range;
var randomRangeInt = rng.rangeInt;
var randomSpacedIndexes = rng.spacedIndexes;
var interpolators = require('../interpolators');
var math = require('../math');
var getDistance = math.getDistance;
var getNormalizedVector = math.getNormalizedVector;
module.exports = {
keyIndexes: createKeyIndexes,
fromKeyIndexes: fromKeyIndexes,
interpolateKeyIndexes: interpolateKeyIndexes,
addKeyIndexes: addKeyIndexes,
addDisplacementKeyIndexes: addDisplacementKeyIndexes,
}
function createKeyIndexes(settings) {
var defaults = {
length: null,
startHeight: undefined,
endHeight: undefined,
minSpacing: undefined,
maxSpacing: undefined,
interpolator: null,
min: 0,
max: 100,
minSlope: undefined,
maxSlope: undefined,
};
var s = Object.assign({}, defaults, settings);
var length = s.length;
var startHeight = s.startHeight;
var endHeight = s.endHeight;
var minSpacing = arg(s.minSpacing, length * 0.1);
var maxSpacing = arg(s.maxSpacing, length * 0.1);
var minHeight = s.min;
var maxHeight = s.max;
var minSlope = s.minSlope;
var maxSlope = s.maxSlope;
var keyIndexes = randomSpacedIndexes(length, minSpacing, maxSpacing);
var prev;
var out = keyIndexes.map(function(index, i, data) {
var value;
if (i === 0 && startHeight !== undefined) {
value = startHeight;
} else {
value = getValue(prev, index, minHeight, maxHeight, minSlope, maxSlope);
}
var result = {
index: index,
value: value,
};
prev = result;
return result;
});
if (endHeight !== undefined) {
out[out.length - 1].value = endHeight;
}
return out;
}
function getValue(prev, index, minHeight, maxHeight, minSlope, maxSlope) {
var min = minHeight;
var max = maxHeight;
if (prev !== undefined) {
var prevVal = prev.value;
var distance = index - prev.index;
if (minSlope !== undefined) {
min = Math.max(min, prevVal + (distance * minSlope));
}
if (maxSlope !== undefined) {
max = Math.min(max, prevVal + (distance * maxSlope));
}
}
return randomRangeInt(min, max);
}
function interpolateKeyIndexes(keyIndexes, interpolator) {
var results = [];
interpolator = arg(interpolator, interpolators.linear);
keyIndexes.forEach(function(item, i) {
results.push(item.value);
var next = keyIndexes[i + 1];
if (!next) {
return;
}
var curerntKeyIndex = item.index;
var nextKeyIndex = next.index;
var wavelength = Math.abs(nextKeyIndex - curerntKeyIndex - 1);
var a = item.value;
var b = next.value;
for (var j = 0; j < wavelength; j++) {
var x = j / wavelength;
var interpolatedVal = interpolator(a, b, x);
results.push(interpolatedVal);
}
});
return results;
}
function fromKeyIndexes(keyIndexes, interpolator) {
return oneDHeightmapFactory({
data: this.interpolateKeyIndexes(keyIndexes, interpolator)
});
}
function addKeyIndexes(settings) {
var defaults = {
keyIndexes: null,
// position on line determined by percent of distance between points
posRatioMin: 0.33,
posRatioMax: 0.66,
// distance from pos on line determined by percent of distance between points
distRatioMin: 0.1,
distRatioMax: 0.2,
// absolute min / max distance
distMin: undefined,
distMax: undefined,
direction: undefined,
upDirection: undefined,
downDirection: undefined,
upPosRatioMin: undefined,
upPosRatioMax: undefined,
downPosRatioMin: undefined,
downPosRatioMax: undefined,
upDistRatioMin: undefined,
upDistRatioMax: undefined,
downDistRatioMin: undefined,
downDistRatioMax: undefined,
};
var s = Object.assign({}, defaults, settings);
var keyIndexes = s.keyIndexes;
var result = [];
keyIndexes.forEach(function(item, i, data) {
var next = data[i + 1];
if (!next) {
result.push(item);
return;
}
var splitSettings = Object.assign({
left: item,
right: next,
}, settings);
var add = splitKeyIndexes(splitSettings);
result.push(item);
result.push(add);
});
return result;
}
function splitKeyIndexes(settings) {
var defaults = {
left: null,
right: null,
// position on line determined by percent of distance between points
posRatioMin: 0.33,
posRatioMax: 0.66,
// distance from pos on line determined by percent of distance between points
distRatioMin: 0.1,
distRatioMax: 0.2,
// absolute min / max distance
distMin: undefined,
distMax: undefined,
direction: undefined,
upDirection: undefined,
downDirection: undefined,
upPosRatioMin: undefined,
upPosRatioMax: undefined,
downPosRatioMin: undefined,
downPosRatioMax: undefined,
upDistRatioMin: undefined,
upDistRatioMax: undefined,
downDistRatioMin: undefined,
downDistRatioMax: undefined,
};
var s = Object.assign({}, defaults, settings);
var left = s.left;
var right = s.right;
var slopeUp = left.value < right.value;
var posRatioMin = s.posRatioMin;
var posRatioMax = s.posRatioMax;
var distRatioMin = s.distRatioMin;
var distRatioMax = s.distRatioMax;
var direction = s.direction;
var distMin = s.distMin;
var distMax = s.distMax;
if (slopeUp) {
posRatioMin = arg(s.upPosRatioMin, posRatioMin);
posRatioMax = arg(s.upPosRatioMax, posRatioMax);
distRatioMin = arg(s.upDistRatioMin, distRatioMin);
distRatioMax = arg(s.upDistRatioMax, distRatioMax);
direction = arg(s.upDirection, direction);
} else {
posRatioMin = arg(s.downPosRatioMin, posRatioMin);
posRatioMax = arg(s.downPosRatioMax, posRatioMax);
distRatioMin = arg(s.downDistRatioMin, distRatioMin);
distRatioMax = arg(s.downDistRatioMax, distRatioMax);
direction = arg(s.downDirection, direction);
}
direction = arg(direction, random() < 0.5 ? 'up' : 'down');
var posRatio = randomRange(posRatioMin, posRatioMax);
var distRatio = randomRange(distRatioMin, distRatioMax);
var a = {
x: left.index,
y: left.value,
};
var b = {
x: right.index,
y: right.value,
};
var p = generateMidPoint(a, b, posRatio, distRatio, direction, distMin, distMax);
return {
value: p.y,
index: p.x
};
}
function generateMidPoint(a, b, cPosRatio, distRatio, direction, distMin, distMax) {
var vDist = getDistance(a, b);
var v = getNormalizedVector(a, b, vDist);
var dx = b.x - a.x;
var dy = b.y - a.y;
// c is a point on line ab at given ratio
var c = {
x: (dx * cPosRatio),
y: (dy * cPosRatio)
};
// distance proportional to ab length
var dist = vDist * distRatio;
if (distMin !== undefined) {
dist = Math.max(distMin);
}
if (distMax !== undefined) {
dist = Math.min(distMax);
}
var vDir = vectorRotate90(v, direction);
var d = {
x: vDir.x * dist,
y: vDir.y * dist,
};
// width of line ab
var ab = dx;
// postion of d offset from c
var dC = c.x + d.x;
// scale to fit horizontal bounds of ab
var scale = false;
// d left of a
if (dC < 0) {
scale = -(c.x / d.x);
}
// d right of b
else if (dC > ab) {
scale = (dx - c.x) / (d.x);
}
if (scale !== false) {
d.x *= scale;
d.y *= scale;
}
// add offsets to d
d.x += c.x + a.x;
d.y += c.y + a.y;
d.x = Math.round(d.x);
if (d.x === a.x) {
d.x += 1;
}
if (d.x === b.x) {
d.x -= 1;
}
// set c offset for debug
// c.x += a.x;
// c.y += a.y;
return d;
}
function vectorRotate90(v, direction){
if (direction === 'left' || direction === 'up') {
return {
x: -v.y,
y: v.x,
}
}
else if (direction === 'right' || direction === 'down') {
return {
x: v.y,
y: -v.x,
}
}
}
function addDisplacementKeyIndexes(settings) {
var defaults = {
keyIndexes: null,
startingDisplacement: 50,
roughness: 0.77,
maxIterations: 1,
calcDisplacement: defaultCalcDisplacement,
};
var s = Object.assign({}, defaults, settings);
var keyIndexes = s.keyIndexes;
var roughness = s.roughness;
var maxIterations = s.maxIterations;
var calcDisplacement = s.calcDisplacement;
var startingDisplacement = s.startingDisplacement;
keyIndexes = keyIndexes.map(function(item) {
return Object.assign({}, item);
});
var results = [];
keyIndexes.forEach(function(item, i, data) {
var next = data[i + 1];
if (!next) {
results.push(item);
return;
}
var arr = split(item, next, startingDisplacement);
results = results.concat(item, arr);
});
return results;
function defaultCalcDisplacement(current, left, right, iteration) {
if (iteration == 1) {
return current;
}
return current * roughness;
}
function split(left, right, displacement, iteration) {
iteration = iteration || 0;
iteration++;
if (left.index + 1 == right.index) {
return false;
}
displacement = calcDisplacement(displacement, left, right, iteration);
var mid = splitNodes(left, right, displacement);
if (iteration >= maxIterations) {
return mid;
}
var result = [];
var canSplitLeft = left.index + 1 !== mid.index;
var canSplitRight = right.index - 1 !== mid.index;
if (canSplitLeft) {
var leftSplit = split(left, mid, displacement, iteration);
if (leftSplit) {
result = result.concat(leftSplit);
}
}
result.push(mid);
if (canSplitRight) {
var rightSplit = split(mid, right, displacement, iteration);
if (rightSplit) {
result = result.concat(rightSplit);
}
}
return result;
}
}
function splitNodes(left, right, displacement) {
var midIndex = Math.floor((left.index + right.index) * 0.5);
var midValue = (left.value + right.value) * 0.5;
var adjustment = (randomRange(-1, 1) * displacement);
return {
index: midIndex,
value: midValue + adjustment,
};
} | unstoppablecarl/1d-heightmap | src/key-indexes/index.js | JavaScript | mit | 11,619 |
namespace PaintShop.Models
{
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
}
| georgipyaramov/PaintShop | PaintShop/PaintShop.Models/ApplicationUser.cs | C# | mit | 693 |
package ruanmianbao.binetwork;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main{
boolean running = false;
Socket socket;
ByteOrder order;
String script = "";
public Main(String[] args) throws Exception {
String server = "localhost";
int port = 8788;
ByteOrder order = ByteOrder.LITTLE_ENDIAN;
for(String a: args) {
String[] a2 = a.split("=",2);
if (a2.length==2) {
switch(a2[0]) {
case "-s":
case "--server":
server = a2[1];
break;
case "-p":
case "--port":
port = Integer.parseInt(a2[1]);
break;
case "-e":
case "--endian":
order = a2[1].equalsIgnoreCase("be")?ByteOrder.BIG_ENDIAN:ByteOrder.LITTLE_ENDIAN;
break;
case "-r":
case "--run":
script = a2[1];
break;
}
}
}
Main.log("connect to:"+server+":"+port);
socket = new Socket(server, port);
socket.setSoTimeout(15000);
Main.log("connected.");
this.order = order;
if (this.script.isEmpty()) {
// read from input
this.running = true;
ExecutorService taskExecutor = Executors.newFixedThreadPool(2);
try {
taskExecutor.execute(new RecvWorker());
taskExecutor.execute(new SendWorker());
} finally {
taskExecutor.shutdown();
}
} else {
this.running = false;
this.RunWorker();
}
}
/**
* 进行一次测试
* @throws Exception
*/
private void RunWorker() throws Exception {
if(script.startsWith("'") && script.endsWith("'"))
script = script.substring(1, script.length()-1);
Main.log("run script:" + script);
sendData(script);
recvData();
}
private String recvData() throws IOException {
int buffer_size = 4096;
byte[] buffer = new byte[buffer_size];
BufferedInputStream in = new BufferedInputStream(socket.getInputStream());
int readed = 0, pos = 0;
readed = in.read(buffer, pos, buffer.length-pos);
if (readed>0) pos+=readed;
String msg = toHex(buffer,0,pos);
Main.log("recv["+pos+"]:"+msg);
return msg;
}
private void sendData(String line) throws IOException {
ByteBuffer outbuffer = ByteBuffer.allocate(4*1024);
outbuffer.order(order);
String[] items = line.split("\\|");
for(int i=0; i<items.length; i++) {
String[] sp = items[i].split(":");
if(sp.length!=3) {
Main.log("item ["+i+"] format error:"+items[i]);
continue;
}
switch(sp[0]) {
case "b": //二进制
putBin(outbuffer, Integer.parseInt(sp[1]), sp[2]);
break;
case "o": //八进制
putOct(outbuffer, Integer.parseInt(sp[1]), sp[2]);
break;
case "d": //十进制
putDec(outbuffer, Integer.parseInt(sp[1]), sp[2]);
break;
case "x": //十六进制
putHex(outbuffer, Integer.parseInt(sp[1]), sp[2]);
break;
case "s": //字符串
putStr(outbuffer, sp[1], sp[2]);
break;
}
}
outbuffer.flip();
socket.getOutputStream().write(outbuffer.array(), 0, outbuffer.limit());
socket.getOutputStream().flush();
Main.log("send["+outbuffer.limit()+"]"+toHex(outbuffer.array(), 0, outbuffer.limit()));
}
// 二进制
private void putBin(ByteBuffer outbuffer, int parseInt, String string) {
putByte(outbuffer, parseInt, string, 2);
}
// 八进制
private void putOct(ByteBuffer outbuffer, int parseInt, String string) {
putByte(outbuffer, parseInt, string, 8);
}
// 十进制
private void putDec(ByteBuffer outbuffer, int parseInt, String string) {
putByte(outbuffer, parseInt, string, 10);
}
// 十六进制
private void putHex(ByteBuffer outbuffer, int parseInt, String string) {
putByte(outbuffer, parseInt, string, 16);
}
// 字符串
private void putStr(ByteBuffer outbuffer, String encode, String string) throws UnsupportedEncodingException {
byte[] data = string.getBytes(encode);
outbuffer.put(data);
}
/**
* 把一个字符串按指定进制转换成字节,存入指定的缓冲区内。如果指定的长度与字符串拆分后的长度不符,则自动补0。
* @param outbuffer 填充的buffer
* @param parseInt 单位:1-byte 2-short 4-int 8-long
* @param string 待处理字符串
* @param radix 进制(2,8,10,16)
*/
private void putByte(ByteBuffer outbuffer, int parseInt, String string, int radix) {
String[] strs = string.split(" ");
for(int i=0; i<strs.length; i++) {
if (i<strs.length) {
switch(parseInt) {
case 1:
short b = Short.parseShort(strs[i], radix);
outbuffer.put((byte)(b&0x00ff));
break;
case 2:
int s = Integer.parseInt(strs[i], radix);
outbuffer.putShort((short)(s&0x00ffff));
break;
case 4:
long ii = Long.parseLong(strs[i], radix);
outbuffer.putInt((int)(ii&0x00ffffffff));
break;
case 8:
long l = Long.parseLong(strs[i], radix);
outbuffer.putLong(l);
break;
default:
Main.log("unsupport type:"+parseInt);
}
}
}
}
/**
* 发送信息的线程
*/
private class SendWorker implements Runnable {
@Override
public void run() {
try {
Scanner scan = new Scanner(System.in);
while (running) {
String line = scan.nextLine();
Main.log("input:"+line);
sendData(line);
}
scan.close();
} catch (Exception e) {
running = false;
e.printStackTrace();
}
}
}
/**
* 接收信息的线程
*/
private class RecvWorker implements Runnable{
@Override
public void run() {
try {
byte[] buffer = new byte[4*1024];
BufferedInputStream in = new BufferedInputStream(socket.getInputStream());
while (running) {
int readed = in.read(buffer, 0, buffer.length);
Main.log("recv["+readed+"]:"+toHex(buffer, 0, readed));
}
} catch (Exception e) {
running = false;
e.printStackTrace();
}
}
}
/**
* 统一输出
* @param string 要输出的信息
*/
static void log(String msg) {
Date dNow = new Date( );
SimpleDateFormat ft = new SimpleDateFormat ("yyyy.MM.dd HH:mm:ss");
System.out.println("["+ft.format(dNow)+"] "+msg);
}
/**
* 入口
* @param args host ip [le|be]
*/
public static void main(String[] args) {
if (args.length==0
|| args[0].equalsIgnoreCase("help")
|| args[0].equalsIgnoreCase("-h")
|| args[0].equalsIgnoreCase("?")
|| args[0].equalsIgnoreCase("--help")
) {
printHelp("binetwork");
System.exit(0);
}
try {
new Main(args);
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
private static void printHelp(String cmd) {
System.out.println("usage: check 'readme.md' for more info.\n\n" +
cmd + "[-s|--server]=<host> [-p|--port]=<port> [-e|-endian]=<le|be>\n" +
" -host or ip: the host name or ip (default: localhost)\n"+
" -port: the port of server (default: 8080) \n" +
" -le: little endian (default)\n"+
" -be: big endian \n\n" +
"example:\n"+
" "+ cmd + "-s=127.0.0.1 -p=8080 -e=le -r=\"x:1:fa fb fc fd\"\n");
}
/**
* 把一个数组用16进制格式输出
* @param buf 需要转换的数据
* @param start 起始位置
* @param length 长度
* @return 16进制字符串
*/
private String toHex(byte[] buf, int start, int length) {
if (buf == null)
return "";
StringBuffer result = new StringBuffer(2 * length);
for (int i = start; (( i < start+length) && (i<buf.length)); i++) {
appendHex(result, buf[i]);
}
return result.toString();
}
private final static String HEX = "0123456789ABCDEF";
private static void appendHex(StringBuffer sb, byte b) {
sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
}
}
| flairyu/binetwork | src/ruanmianbao/binetwork/Main.java | Java | mit | 7,911 |
using Keeper.Warm;
using System;
using System.Collections.Generic;
namespace Keeper.Warm
{
public class QueryResult
{
private Machine machine;
private Variable[] variables;
public QueryResult(bool success, Variable[] variables, Machine machine)
{
this.Success = success;
this.variables = variables;
this.machine = machine;
}
public bool Success
{
get;
private set;
}
public bool CanContinue
{
get
{
return this.machine.IsBacktrackAvailable;
}
}
public bool Continue()
{
bool result = this.machine.Continue();
this.Success = result;
return result;
}
public IEnumerable<Variable> Variables
{
get
{
return this.variables;
}
}
public ITerm GetVariable(Variable variable)
{
int index = Array.IndexOf(variables, variable);
if (index < 0)
{
return null;
}
else
{
return BuildTermFromHeap(this.machine, variables.Length - (index + 1));
}
}
public static ITerm BuildTermFromHeap(Machine machine, int index)
{
return BuildTermFromAddress(machine, new Address(AddressType.Heap, index));
}
public static ITerm BuildTermFromAddress(Machine machine, Address termAddress)
{
Cell value = new Cell(machine.DereferenceAndLoad(termAddress));
switch (value.Tag)
{
case Tag.Ref:
string name = value.Address.Pointer.ToString();
if(value.Address.Type == AddressType.Retained)
{
name = "R" + name;
}
return new Variable(name);
case Tag.Str:
Cell functorCell = new Cell(machine.DereferenceAndLoad(value.Address));
FunctorDescriptor functor = machine.GetFunctor(functorCell.Address.Pointer);
ITerm[] terms = null;
if (functor.Arity > 0)
{
terms = new ITerm[functor.Arity];
for (int termIndex = 0; termIndex < functor.Arity; termIndex++)
{
terms[termIndex] = BuildTermFromAddress(machine, value.Address + termIndex + 1);
}
}
return new CompoundTerm(functor.Name, terms);
case Tag.Con:
FunctorDescriptor constantFunctor = machine.GetFunctor(value.Address.Pointer);
if (constantFunctor.Name == "[]")
{
return EmptyList.Instance;
}
else
{
return new Atom(constantFunctor.Name);
}
case Tag.Lis:
var headTerm = BuildTermFromAddress(machine, value.Address);
var TailTerm = BuildTermFromAddress(machine, (value.Address + 1));
return new ListPair(headTerm, (IListTail)TailTerm);
default:
throw new Exception("Unexpected tag in term:" + value);
}
}
}
} | FacticiusVir/Warm | Keeper.Warm/QueryResult.cs | C# | mit | 3,572 |
using System;
using System.IO;
using System.Linq;
using SharpCompress.IO;
namespace SharpCompress.Common.SevenZip
{
internal class SevenZipFilePart : FilePart
{
private CompressionType? _type;
private readonly Stream _stream;
private readonly ArchiveDatabase _database;
internal SevenZipFilePart(Stream stream, ArchiveDatabase database, int index, CFileItem fileEntry, ArchiveEncoding archiveEncoding)
: base(archiveEncoding)
{
_stream = stream;
_database = database;
Index = index;
Header = fileEntry;
if (Header.HasStream)
{
Folder = database._folders[database._fileIndexToFolderIndexMap[index]];
}
}
internal CFileItem Header { get; }
internal CFolder? Folder { get; }
internal int Index { get; }
internal override string FilePartName => Header.Name;
internal override Stream? GetRawStream()
{
return null;
}
internal override Stream GetCompressedStream()
{
if (!Header.HasStream)
{
return null!;
}
var folderStream = _database.GetFolderStream(_stream, Folder!, _database.PasswordProvider);
int firstFileIndex = _database._folderStartFileIndex[_database._folders.IndexOf(Folder!)];
int skipCount = Index - firstFileIndex;
long skipSize = 0;
for (int i = 0; i < skipCount; i++)
{
skipSize += _database._files[firstFileIndex + i].Size;
}
if (skipSize > 0)
{
folderStream.Skip(skipSize);
}
return new ReadOnlySubStream(folderStream, Header.Size);
}
public CompressionType CompressionType
{
get
{
if (_type is null)
{
_type = GetCompression();
}
return _type.Value;
}
}
//copied from DecoderRegistry
private const uint K_COPY = 0x0;
private const uint K_DELTA = 3;
private const uint K_LZMA2 = 0x21;
private const uint K_LZMA = 0x030101;
private const uint K_PPMD = 0x030401;
private const uint K_BCJ = 0x03030103;
private const uint K_BCJ2 = 0x0303011B;
private const uint K_DEFLATE = 0x040108;
private const uint K_B_ZIP2 = 0x040202;
internal CompressionType GetCompression()
{
var coder = Folder!._coders.First();
switch (coder._methodId._id)
{
case K_LZMA:
case K_LZMA2:
{
return CompressionType.LZMA;
}
case K_PPMD:
{
return CompressionType.PPMd;
}
case K_B_ZIP2:
{
return CompressionType.BZip2;
}
default:
throw new NotImplementedException();
}
}
internal bool IsEncrypted => Folder!._coders.FindIndex(c => c._methodId._id == CMethodId.K_AES_ID) != -1;
}
} | adamhathcock/sharpcompress | src/SharpCompress/Common/SevenZip/SevenZipFilePart.cs | C# | mit | 3,350 |
using System;
using System.Collections.Generic;
using Mailer.NET.Mailer.Rendering;
using Mailer.NET.Mailer.Transport;
using Mailer.NET.Mailer.Internal;
using Mailer.NET.Mailer.Response;
using System.Threading.Tasks;
namespace Mailer.NET.Mailer
{
public class Email
{
public AbstractTransport Transport { get; set; }
public String Message { get; set; }
public String Template { get; set; }
public List<TemplateVar> TemplateVars { get; set; }
public List<Contact> To { get; set; }
public List<Contact> Cco { get; set; }
public List<Contact> Bco { get; set; }
public Contact From { get; set; }
public String Subject { get; set; }
public EmailContentType Type { get; set; }
public List<Attachment> Attachments { get; set; }
public Boolean HasReadNotification { get; set; }
public String ReplyTo { get; set; }
public Email(AbstractTransport transport, EmailContentType type = EmailContentType.Text)
{
Transport = transport;
Type = type;
}
public Email(EmailContentType type = EmailContentType.Text)
{
Transport = AppConfig.DefaultInstance.TryGetDefaultTransport();
Type = type;
}
public void AddTo(string email, string name = null)
{
if (To == null)
{
To = new List<Contact>();
}
To.Add(new Contact(){Email = email, Name=name});
}
public void AddCco(string email, string name = null)
{
if (Cco == null)
{
Cco = new List<Contact>();
}
Cco.Add(new Contact() { Email = email, Name = name });
}
public void AddBco(string email, string name = null)
{
if (Bco == null)
{
Bco = new List<Contact>();
}
Bco.Add(new Contact() { Email = email, Name = name });
}
public void AddTemplateVar(string name, object data)
{
if (TemplateVars == null)
{
TemplateVars = new List<TemplateVar>();
}
TemplateVars.Add(new TemplateVar(){Name = name, Data = data});
}
public void AddAttachment(Attachment file)
{
if (Attachments == null)
{
Attachments = new List<Attachment>();
}
Attachments.Add(file);
}
public EmailResponse Send()
{
ValidateEmail();
return Transport.SendEmail(this);
}
public async Task<EmailResponse> SendEmailAsync()
{
ValidateEmail();
return await Transport.SendEmailAsync(this);
}
private void ValidateEmail()
{
if (From == null)
{
throw new InvalidOperationException("The From is not defined!");
}
if (To == null && Bco == null && Cco == null)
{
throw new InvalidOperationException("You need specify one destination on to, cc or bcc.");
}
if (Transport == null)
{
throw new InvalidOperationException("Transport is not defined!");
}
if (!String.IsNullOrEmpty(Template))
{
Message = EmailRender.RenderEmail(this);
}
}
}
}
| Inside-Sistemas/mailer.net | src/Mailer.NET/Mailer/Email.cs | C# | mit | 3,511 |
// <copyright file="ParsingTests.cs" company="MIT License">
// Licensed under the MIT License. See LICENSE file in the project root for license information.
// </copyright>
namespace SmallBasic.Tests.Compiler
{
using SmallBasic.Compiler;
using SmallBasic.Compiler.Diagnostics;
using Xunit;
public sealed class ParsingTests : IClassFixture<CultureFixture>
{
[Fact]
public void ItReportsUnterminatedSubModules()
{
new SmallBasicCompilation(@"
Sub a").VerifyDiagnostics(
// Sub a
// ^
// I was expecting to see 'EndSub' after this.
new Diagnostic(DiagnosticCode.UnexpectedEndOfStream, ((1, 4), (1, 4)), "EndSub"));
}
[Fact]
public void ItReportsNestedSubModules()
{
new SmallBasicCompilation(@"
If x < 1 Then
Sub b
EndSub
EndIf").VerifyDiagnostics(
// Sub b
// ^^^
// I didn't expect to see 'Sub' here. I was expecting the start of a new statement.
new Diagnostic(DiagnosticCode.UnexpectedTokenInsteadOfStatement, ((2, 0), (2, 2)), "Sub"),
// EndSub
// ^^^^^^
// I didn't expect to see 'EndSub' here. I was expecting the start of a new statement.
new Diagnostic(DiagnosticCode.UnexpectedTokenInsteadOfStatement, ((3, 0), (3, 5)), "EndSub"));
}
[Fact]
public void ItReportsIncompleteNestedSubModules()
{
new SmallBasicCompilation(@"
Sub a
Sub b
EndSub").VerifyDiagnostics(
// Sub b
// ^^^
// I didn't expect to see 'Sub' here. I was expecting 'EndSub' instead.
new Diagnostic(DiagnosticCode.UnexpectedTokenFound, ((2, 0), (2, 2)), "Sub", "EndSub"));
}
[Fact]
public void ItReportsEndSubWithoutSub()
{
new SmallBasicCompilation(@"
x = 1
EndSub").VerifyDiagnostics(
// EndSub
// ^^^^^^
// I didn't expect to see 'EndSub' here. I was expecting the start of a new statement.
new Diagnostic(DiagnosticCode.UnexpectedTokenInsteadOfStatement, ((2, 0), (2, 5)), "EndSub"));
}
[Fact]
public void ItReportsElseIfWithoutIf()
{
new SmallBasicCompilation(@"
x = 1
ElseIf x < 1 Then
EndIf").VerifyDiagnostics(
// ElseIf x < 1 Then
// ^^^^^^
// I didn't expect to see 'ElseIf' here. I was expecting the start of a new statement.
new Diagnostic(DiagnosticCode.UnexpectedTokenInsteadOfStatement, ((2, 0), (2, 5)), "ElseIf"),
// EndIf
// ^^^^^
// I didn't expect to see 'EndIf' here. I was expecting the start of a new statement.
new Diagnostic(DiagnosticCode.UnexpectedTokenInsteadOfStatement, ((3, 0), (3, 4)), "EndIf"));
}
[Fact]
public void ItReportsElseWithoutIf()
{
new SmallBasicCompilation(@"
x = 1
Else
EndIf").VerifyDiagnostics(
// Else
// ^^^^
// I didn't expect to see 'Else' here. I was expecting the start of a new statement.
new Diagnostic(DiagnosticCode.UnexpectedTokenInsteadOfStatement, ((2, 0), (2, 3)), "Else"),
// EndIf
// ^^^^^
// I didn't expect to see 'EndIf' here. I was expecting the start of a new statement.
new Diagnostic(DiagnosticCode.UnexpectedTokenInsteadOfStatement, ((3, 0), (3, 4)), "EndIf"));
}
[Fact]
public void ItReportsEndIfWithoutIf()
{
new SmallBasicCompilation(@"
x = 1
EndIf").VerifyDiagnostics(
// EndIf
// ^^^^^
// I didn't expect to see 'EndIf' here. I was expecting the start of a new statement.
new Diagnostic(DiagnosticCode.UnexpectedTokenInsteadOfStatement, ((2, 0), (2, 4)), "EndIf"));
}
[Fact]
public void ItReportsElseIfAfterElse()
{
new SmallBasicCompilation(@"
x = 1
If x > 1 Then
Else
ElseIf x < 1
EndIf").VerifyDiagnostics(
// ElseIf x < 1
// ^^^^^^
// I didn't expect to see 'ElseIf' here. I was expecting 'EndIf' instead.
new Diagnostic(DiagnosticCode.UnexpectedTokenFound, ((4, 0), (4, 5)), "ElseIf", "EndIf"),
// ElseIf x < 1
// ^^^^^^
// I didn't expect to see 'ElseIf' here. I was expecting the start of a new statement.
new Diagnostic(DiagnosticCode.UnexpectedTokenInsteadOfStatement, ((4, 0), (4, 5)), "ElseIf"),
// EndIf
// ^^^^^
// I didn't expect to see 'EndIf' here. I was expecting the start of a new statement.
new Diagnostic(DiagnosticCode.UnexpectedTokenInsteadOfStatement, ((5, 0), (5, 4)), "EndIf"));
}
[Fact]
public void ItReportsEndWhileWithoutWhile()
{
new SmallBasicCompilation(@"
x = 1
EndWhile").VerifyDiagnostics(
// EndWhile
// ^^^^^^^^
// I didn't expect to see 'EndWhile' here. I was expecting the start of a new statement.
new Diagnostic(DiagnosticCode.UnexpectedTokenInsteadOfStatement, ((2, 0), (2, 7)), "EndWhile"));
}
[Fact]
public void ItReportsInvalidStartOfStatements()
{
new SmallBasicCompilation(@"
x = 1
Then").VerifyDiagnostics(
// Then
// ^^^^
// I didn't expect to see 'Then' here. I was expecting the start of a new statement.
new Diagnostic(DiagnosticCode.UnexpectedTokenInsteadOfStatement, ((2, 0), (2, 3)), "Then"));
}
[Fact]
public void ItReportsTokensAfterACompleteStatement()
{
new SmallBasicCompilation(@"
If x = 1 Then y
EndIf").VerifyDiagnostics(
// If x = 1 Then y
// ^
// This statement should go on a new line.
new Diagnostic(DiagnosticCode.UnexpectedStatementInsteadOfNewLine, ((1, 14), (1, 14))));
}
[Fact]
public void ItReportsAssignmentWithNonExpressions()
{
new SmallBasicCompilation(@"
x = .").VerifyDiagnostics(
// x = .
// ^
// I didn't expect to see '.' here. I was expecting 'identifier' instead.
new Diagnostic(DiagnosticCode.UnexpectedTokenFound, ((1, 4), (1, 4)), ".", "identifier"));
}
[Fact]
public void ItReportsAssignmentWithNothing()
{
new SmallBasicCompilation(@"
x =").VerifyDiagnostics(
// x =
// ^
// I was expecting to see 'identifier' after this.
new Diagnostic(DiagnosticCode.UnexpectedEndOfStream, ((1, 2), (1, 2)), "identifier"));
}
[Fact]
public void ItReportsNonExpressionsInWhileLoop()
{
new SmallBasicCompilation(@"
While .
EndWhile").VerifyDiagnostics(
// While .
// ^
// I didn't expect to see '.' here. I was expecting 'identifier' instead.
new Diagnostic(DiagnosticCode.UnexpectedTokenFound, ((1, 6), (1, 6)), ".", "identifier"));
}
[Fact]
public void ItReportsMissingThenAfterIf()
{
new SmallBasicCompilation(@"
If x < 1
EndIf").VerifyDiagnostics(
// EndIf
// ^^^^^
// I didn't expect to see 'EndIf' here. I was expecting 'Then' instead.
new Diagnostic(DiagnosticCode.UnexpectedTokenFound, ((2, 0), (2, 4)), "EndIf", "Then"));
}
[Fact]
public void ItReportsMissingThenAfterElseIf()
{
new SmallBasicCompilation(@"
If x < 1 Then
ElseIf x > 1
EndIf").VerifyDiagnostics(
// EndIf
// ^^^^^
// I didn't expect to see 'EndIf' here. I was expecting 'Then' instead.
new Diagnostic(DiagnosticCode.UnexpectedTokenFound, ((3, 0), (3, 4)), "EndIf", "Then"));
}
[Fact]
public void ItReportsStepAfterIf()
{
new SmallBasicCompilation(@"
If x < 1 Step
EndIf").VerifyDiagnostics(
// If x < 1 Step
// ^^^^
// I didn't expect to see 'Step' here. I was expecting 'Then' instead.
new Diagnostic(DiagnosticCode.UnexpectedTokenFound, ((1, 9), (1, 12)), "Step", "Then"),
// If x < 1 Step
// ^^^^
// This statement should go on a new line.
new Diagnostic(DiagnosticCode.UnexpectedStatementInsteadOfNewLine, ((1, 9), (1, 12))));
}
[Fact]
public void ItReportsStepAfterElseIf()
{
new SmallBasicCompilation(@"
If x > 1 Then
ElseIf x < 1 Step
EndIf").VerifyDiagnostics(
// ElseIf x < 1 Step
// ^^^^
// I didn't expect to see 'Step' here. I was expecting 'Then' instead.
new Diagnostic(DiagnosticCode.UnexpectedTokenFound, ((2, 13), (2, 16)), "Step", "Then"),
// ElseIf x < 1 Step
// ^^^^
// This statement should go on a new line.
new Diagnostic(DiagnosticCode.UnexpectedStatementInsteadOfNewLine, ((2, 13), (2, 16))));
}
[Fact]
public void ItReportsExtraTokensAfterIfStatement()
{
new SmallBasicCompilation(@"
For x = 1 To 2 Step 1 :
EndFor").VerifyDiagnostics(
// For x = 1 To 2 Step 1 :
// ^
// This statement should go on a new line.
new Diagnostic(DiagnosticCode.UnexpectedStatementInsteadOfNewLine, ((1, 23), (1, 23))));
}
[Fact]
public void ItReportsUnevenParenthesis()
{
new SmallBasicCompilation(@"
TextWindow.WriteLine(5").VerifyDiagnostics(
// TextWindow.WriteLine(5
// ^
// I was expecting to see ')' after this.
new Diagnostic(DiagnosticCode.UnexpectedEndOfStream, ((1, 21), (1, 21)), ")"));
}
[Fact]
public void ItReportsUnevenBrackets()
{
new SmallBasicCompilation(@"
x = a[1").VerifyDiagnostics(
// x = a[1
// ^
// I was expecting to see ']' after this.
new Diagnostic(DiagnosticCode.UnexpectedEndOfStream, ((1, 6), (1, 6)), "]"));
}
[Fact]
public void ItReportsArgumentsWithoutCommasInInvocation()
{
new SmallBasicCompilation(@"
x = Math.Power(1 4)").VerifyDiagnostics(
// x = Math.Power(1 4)
// ^
// I didn't expect to see 'number' here. I was expecting ',' instead.
new Diagnostic(DiagnosticCode.UnexpectedTokenFound, ((1, 17), (1, 17)), "number", ","));
}
[Fact]
public void ItReportsCommasWithoutArgumentsInInvocation()
{
new SmallBasicCompilation(@"
x = Math.Sin(, )").VerifyDiagnostics(
// x = Math.Sin(, )
// ^
// I didn't expect to see ',' here. I was expecting 'identifier' instead.
new Diagnostic(DiagnosticCode.UnexpectedTokenFound, ((1, 13), (1, 13)), ",", "identifier"));
}
}
}
| OmarTawfik/SuperBasic | Source/SmallBasic.Tests/Compiler/ParsingTests.cs | C# | mit | 11,842 |
'use strict';
/**
* practice Node.js project
*
* @author Huiming Hou <240050497@qq.com>
*/
import mongoose from 'mongoose';
module.exports = function(done){
const debug = $.createDebug('init:mongodb');
debug('connecting to MongoDB...');
const conn = mongoose.createConnection($.config.get('db.mongodb'));
$.mongodb = conn;
$.model = {};
const ObjectId = mongoose.Types.ObjectId;
$.utils.ObjectId = ObjectId;
done();
};
| hhmpro/node-practice-project | src/init/mongodb.js | JavaScript | mit | 450 |
#!/usr/bin/env ruby
require 'rubygems'
require 'json'
require 'net/http'
require 'google_drive'
require 'yaml'
require 'time'
require 'twitter'
require 'active_support/all'
require 'pry'
require 'logger'
def log_time(input, type = 'info')
puts Time.now.to_s + " " + type + ": " + input
$LOG.error(input) if type == 'error'
$LOG.info(input) if type == 'info'
$LOG.warn(input) if type == 'warn'
$LOG.debug(input) if type == 'debug'
$LOG.fatal(input) if type == 'fatal'
end
$LOG = Logger.new('log.log')
# Set back to default formatter because active_support/all is messing things up
$LOG.formatter = Logger::Formatter.new
def loadyaml(yaml)
begin
return YAML::load(File.open(yaml))
rescue Exception => e
log_time("error loading #{yaml} - #{e.message}", 'error')
end
end
def fetch_tweets_from_event(twitter_client, event, since_id)
log_time("Collecting tweets for " + event[:name] + " since " + since_id.to_s)
parameters = { :geocode => "#{event[:lat]},#{event[:long]},#{event[:range]}km", :count => 100, :result_type => 'recent', :since_id => since_id }
twitter_client.search( "", parameters ).to_h
end
def create_sheet_headers(sheet, headers)
n = 1
headers.each do |header|
sheet[1,n] = header
n +=1
end
sheet.save()
end
def stage_tweet(sheet, tweet, row)
sheet[row, 1] = "'" + tweet[:id].to_s
sheet[row, 2] = tweet[:text]
sheet[row, 3] = tweet[:created_at]
sheet[row, 4] = tweet[:retweet_count]
sheet[row, 5] = tweet[:favorite_count]
sheet[row, 6] = tweet[:source]
sheet[row, 7] = tweet[:geo][:coordinates][0]
sheet[row, 8] = tweet[:geo][:coordinates][1]
sheet[row, 9] = "'" + tweet[:user][:id].to_s
sheet[row, 10] = tweet[:user][:name]
sheet[row, 11] = tweet[:user][:screen_name]
sheet[row, 12] = tweet[:user][:created_at]
sheet[row, 13] = tweet[:user][:location]
sheet[row, 14] = tweet[:user][:description]
sheet[row, 15] = tweet[:user][:url]
sheet[row, 16] = tweet[:user][:followers_count]
sheet[row, 17] = tweet[:user][:friends_count]
sheet[row, 18] = tweet[:user][:listed_count]
sheet[row, 19] = tweet[:user][:favourites_count]
sheet[row, 20] = tweet[:user][:statuses_count]
sheet[row, 21] = tweet[:user][:utc_offset]
end
def stage_media(sheet, tweet, media, row)
sheet[row,1] = "'" + media[:id].to_s
sheet[row,2] = "'" + tweet[:id].to_s
sheet[row,3] = media[:expanded_url]
sheet[row,4] = media[:type]
end
def stage_hashtag(sheet, tweet, hashtag, row)
sheet[row,1] = "'" + tweet[:id].to_s
sheet[row,2] = hashtag
end
def stage_url(sheet, tweet, url, row)
sheet[row,1] = "'" + tweet[:id].to_s
sheet[row,2] = url
end
def stage_user_mention(sheet, tweet, user_mention, row)
sheet[row,1] = "'" + tweet[:id].to_s
sheet[row,2] = user_mention[:id]
sheet[row,3] = user_mention[:screen_name]
end
log_time("Loading variables")
yml = loadyaml('config.yml')
log_time("Seting event parameters")
event = {
:name => yml['event'].first['name'],
:lat => yml['event'].first['lat'],
:long => yml['event'].first['long'],
:range => yml['event'].first['range']}
log_time("Connecting to twitter API")
twitter_client = Twitter::REST::Client.new do |config|
config.consumer_key = yml['twitter']['consumer_key']
config.consumer_secret = yml['twitter']['consumer_secret']
config.access_token = yml['twitter']['access_token']
config.access_token_secret = yml['twitter']['access_token_secret']
end
log_time("Connecting to Google Drive API")
session = GoogleDrive.login(yml['google']['user'], yml['google']['password'])
log_time("Loading sheets")
sheets = {}
sheets[:tweets] = session.spreadsheet_by_key(yml['google']['doc']).worksheets[0]
sheets[:media] = session.spreadsheet_by_key(yml['google']['doc']).worksheets[1]
sheets[:hashtags] = session.spreadsheet_by_key(yml['google']['doc']).worksheets[2]
sheets[:urls] = session.spreadsheet_by_key(yml['google']['doc']).worksheets[3]
sheets[:user_mentions] = session.spreadsheet_by_key(yml['google']['doc']).worksheets[4]
sheets[:meta] = session.spreadsheet_by_key(yml['google']['doc']).worksheets[5]
log_time("Loading meta data")
meta = {}
meta[:since_id] = sheets[:meta][1,2][/\d+/].to_i
meta[:tweets_last_row] = sheets[:meta][4,2]
meta[:media_last_row] = sheets[:meta][5,2]
meta[:hashtags_last_row] = sheets[:meta][6,2]
meta[:urls_last_row] = sheets[:meta][7,2]
meta[:user_mentions_last_row] = sheets[:meta][8,2]
log_time("Setting sheet headers")
create_sheet_headers(sheets[:tweets], ['tweet id','text','tweet created_at','retweeted count','favorite count','source','lat','long','user id','user name','screen name','user created_at','user location','user description','user url', 'followers count', 'friends count', 'listed count', 'favourites count', 'statuses count', 'utc offset'])
create_sheet_headers(sheets[:media], ['media id','tweet id','expanded url', 'media type'])
create_sheet_headers(sheets[:hashtags], ['tweet id', 'hashtag'])
create_sheet_headers(sheets[:urls], ['tweet id', 'url'])
create_sheet_headers(sheets[:user_mentions], ['tweet id', 'user id', 'user screen name'])
loop do
log_time("Reloading meta data")
sheets[:meta].reload
log_time("Collecting last rows meta data")
tweet_row = meta[:tweets_last_row].to_i
media_row = meta[:media_last_row].to_i
hashtag_row = meta[:hashtags_last_row].to_i
url_row = meta[:urls_last_row].to_i
user_mention_row = meta[:user_mentions_last_row].to_i
log_time("Fetching Twitter statuses")
tweets = fetch_tweets_from_event(twitter_client, event, meta[:since_id])
log_time("#{tweets[:statuses].length} fetched")
log_time("Staging tweets")
tweets[:statuses].each do |tweet|
tweet_row += 1
stage_tweet(sheets[:tweets], tweet, tweet_row)
unless tweet[:entities][:media].nil?
tweet[:entities][:media].each do |media|
media_row += 1
stage_media(sheets[:media], tweet, media, media_row)
end
end
unless tweet[:entities][:hashtags].nil?
tweet[:entities][:hashtags].each do |hashtag|
hashtag_row += 1
stage_hashtag(sheets[:hashtags], tweet, hashtag[:text], hashtag_row)
end
end
unless tweet[:entities][:urls].nil?
tweet[:entities][:urls].each do |url|
url_row += 1
stage_url(sheets[:urls], tweet, url[:expanded_url], url_row)
end
end
unless tweet[:entities][:user_mentions].nil?
tweet[:entities][:user_mentions].each do |user_mention|
user_mention_row += 1
stage_user_mention(sheets[:user_mentions], tweet, user_mention, user_mention_row)
end
end
end
log_time("Saving staged tweets to sheet")
sheets[:tweets].save()
log_time("Saving staged media to sheet")
sheets[:media].save()
log_time("Saving staged hashtags to sheet")
sheets[:hashtags].save()
log_time("Saving staged urls to sheet")
sheets[:urls].save()
log_time("Saving staged user_mentions to sheet")
sheets[:user_mentions].save()
log_time("Staging max since_id to " + tweets[:search_metadata][:max_id].to_s)
sheets[:meta][1,2] = "'" + tweets[:search_metadata][:max_id].to_s
log_time("Staging last rows")
sheets[:meta][4,2] = tweet_row
sheets[:meta][5,2] = media_row
sheets[:meta][6,2] = hashtag_row
sheets[:meta][7,2] = url_row
sheets[:meta][8,2] = user_mention_row
log_time("Saving staged data to sheet")
sheets[:meta].save()
log_time("sleeping for 60 seconds")
sleep 60
end
| AmnestyInternational/visor | twitter_to_gdoc.rb | Ruby | mit | 7,536 |
<?php
location(BASEURL ."/view/t411/search"); | Reeska/restinpi | src/server/plugins/t411/views/index.php | PHP | mit | 46 |
using System;
using System.Collections.Generic;
using System.Linq;
using Polyglot;
using Cysharp.Threading.Tasks;
using LiteDB;
using Sentry;
using UnityEngine;
#if UNITY_IOS
using UnityEngine.iOS;
#elif UNITY_ANDROID
using Google.Play.Review;
#endif
public class Player
{
public string Id => Settings.PlayerId;
public LocalPlayerSettings Settings { get; private set; }
public bool ShouldMigrate { get; private set; }
private readonly LocalPlayerLegacy legacy = new LocalPlayerLegacy();
public void Initialize()
{
LoadSettings();
ValidateData();
if (!Settings.PlayerId.IsNullOrWhiteSpace())
{
SentrySdk.ConfigureScope(scope => scope.User = new User {Username = Settings.PlayerId});
}
}
public async void BoostStoreReviewConfidence()
{
Settings.RequestStoreReviewConfidence++;
if (Settings.RequestStoreReviewConfidence >= 5 && !Settings.RequestedForStoreReview)
{
Settings.RequestedForStoreReview = true;
await RequestStoreReview();
}
SaveSettings();
}
public async UniTask RequestStoreReview()
{
#if UNITY_IOS
Device.RequestStoreReview();
#elif UNITY_ANDROID
if (Context.Distribution == Distribution.TapTap)
{
Context.AudioManager.Get("ActionSuccess").Play();
Dialog.Prompt("享受 Cytoid 吗?\n请在 TapTap 上给我们打个分吧!", () =>
{
Application.OpenURL("https://www.taptap.com/app/158749");
});
}
else
{
var reviewManager = new ReviewManager();
var requestFlow = reviewManager.RequestReviewFlow();
await requestFlow;
if (requestFlow.Error != ReviewErrorCode.NoError)
{
Debug.LogWarning("Failed to launch Google Play review request flow");
Debug.LogWarning(requestFlow.Error.ToString());
return;
}
var reviewInfo = requestFlow.GetResult();
var launchFlow = reviewManager.LaunchReviewFlow(reviewInfo);
await launchFlow;
if (launchFlow.Error != ReviewErrorCode.NoError)
{
Debug.LogWarning("Failed to launch Google Play review request flow");
Debug.LogWarning(launchFlow.Error.ToString());
}
}
#endif
}
public bool ShouldEnableDebug()
{
return Id == "tigerhix" || Id == "neo";
}
public void ValidateData()
{
var col = Context.Database.GetCollection<LevelRecord>("level_records");
col.DeleteMany(it => it.LevelId == null);
if (!Localization.Instance.SupportedLanguages.Contains((Language) Settings.Language))
{
Settings.Language = (int) Language.English;
}
// Save default Sayaka character meta
var characterCol = Context.Database.GetCollection<CharacterMeta>("characters");
if (!characterCol.Exists(it => it.Id == BuiltInData.DefaultCharacterId))
{
characterCol.Insert(BuiltInData.DefaultCharacterMeta);
}
}
public void LoadSettings()
{
Context.Database.Let(it =>
{
if (!it.CollectionExists("settings"))
{
Debug.LogWarning("Cannot find 'settings' collections");
}
var col = it.GetCollection<LocalPlayerSettings>("settings");
var result = col.FindOne(x => true);
if (result == null)
{
Debug.LogWarning("First time startup. Initializing settings...");
// TODO: Remove migration... one day
ShouldMigrate = true;
result = InitializeSettings();
col.Insert(result);
}
Settings = result;
FillDefault();
Settings.TotalLaunches++;
SaveSettings();
});
}
public void SaveSettings()
{
if (Settings == null) throw new InvalidOperationException();
Context.Database.Let(it =>
{
var col = it.GetCollection<LocalPlayerSettings>("settings");
col.DeleteMany(x => true);
col.Insert(Settings);
});
}
private void FillDefault()
{
var dummy = new LocalPlayerSettings();
Settings.NoteRingColors = dummy.NoteRingColors.WithOverrides(Settings.NoteRingColors);
Settings.NoteFillColors = dummy.NoteFillColors.WithOverrides(Settings.NoteFillColors);
Settings.NoteFillColorsAlt = dummy.NoteFillColorsAlt.WithOverrides(Settings.NoteFillColorsAlt);
if (ShouldOneShot("Reset Graphics Quality"))
{
Settings.GraphicsQuality = GetDefaultGraphicsQuality();
}
if (ShouldOneShot("Enable/Disable Menu Transitions Based On Graphics Quality"))
{
Settings.UseMenuTransitions = Settings.GraphicsQuality >= GraphicsQuality.High;
}
}
public async UniTask Migrate()
{
await UniTask.DelayFrame(30);
try
{
Context.Database.Let(it =>
{
foreach (var level in Context.LevelManager.LoadedLocalLevels.Values)
{
if (level.Id == null) continue;
var record = new LevelRecord
{
LevelId = level.Id,
RelativeNoteOffset = legacy.GetLevelNoteOffset(level.Id),
AddedDate = legacy.GetAddedDate(level.Id).Let(time =>
time == default ? DateTimeOffset.MinValue : new DateTimeOffset(time)),
LastPlayedDate = legacy.GetLastPlayedDate(level.Id).Let(time =>
time == default ? DateTimeOffset.MinValue : new DateTimeOffset(time)),
BestPerformances = new Dictionary<string, LevelRecord.Performance>(),
BestPracticePerformances = new Dictionary<string, LevelRecord.Performance>(),
PlayCounts = new Dictionary<string, int>(),
};
foreach (var chart in level.Meta.charts)
{
record.PlayCounts[chart.type] = legacy.GetPlayCount(level.Id, chart.type);
if (legacy.HasPerformance(level.Id, chart.type, true))
{
var bestPerformance = legacy.GetBestPerformance(level.Id, chart.type, true).Let(p =>
new LevelRecord.Performance
{
Score = p.Score,
Accuracy = p.Accuracy / 100.0,
});
record.BestPerformances[chart.type] = bestPerformance;
}
if (legacy.HasPerformance(level.Id, chart.type, false))
{
var bestPracticePerformance = legacy.GetBestPerformance(level.Id, chart.type, false).Let(
p =>
new LevelRecord.Performance
{
Score = p.Score,
Accuracy = p.Accuracy / 100.0,
});
record.BestPracticePerformances[chart.type] = bestPracticePerformance;
}
}
Context.Database.SetLevelRecord(record, true);
level.Record = record;
}
});
}
catch (Exception e)
{
Debug.LogError(e);
}
}
private LocalPlayerSettings InitializeSettings()
{
var settings = new LocalPlayerSettings
{
SchemaVersion = 1,
PlayerId = PlayerPrefs.GetString("Uid"),
LoginToken = SecuredPlayerPrefs.GetString("JwtToken", null),
ActiveCharacterId = null,
Language = (int) Localization.Instance.ConvertSystemLanguage(Application.systemLanguage)
.Let(it => Localization.Instance.SupportedLanguages.Contains(it) ? it : Language.English),
PlayRanked = legacy.PlayRanked,
EnabledMods = legacy.EnabledMods.ToList(),
DisplayBoundaries = true,
DisplayEarlyLateIndicators = true,
HitboxSizes = new Dictionary<NoteType, int>
{
{NoteType.Click, legacy.ClickHitboxSize},
{NoteType.DragChild, legacy.DragHitboxSize},
{NoteType.DragHead, legacy.DragHitboxSize},
{NoteType.Hold, legacy.HoldHitboxSize},
{NoteType.LongHold, legacy.HoldHitboxSize},
{NoteType.Flick, legacy.FlickHitboxSize},
},
NoteRingColors = new Dictionary<NoteType, Color>
{
{NoteType.Click, legacy.GetRingColor(NoteType.Click, false)},
{NoteType.DragChild, legacy.GetRingColor(NoteType.DragChild, false)},
{NoteType.DragHead, legacy.GetRingColor(NoteType.DragHead, false)},
{NoteType.Hold, legacy.GetRingColor(NoteType.Hold, false)},
{NoteType.LongHold, legacy.GetRingColor(NoteType.LongHold, false)},
{NoteType.Flick, legacy.GetRingColor(NoteType.Flick, false)},
},
NoteFillColors = new Dictionary<NoteType, Color>
{
{NoteType.Click, legacy.GetFillColor(NoteType.Click, false)},
{NoteType.DragChild, legacy.GetFillColor(NoteType.DragChild, false)},
{NoteType.DragHead, legacy.GetFillColor(NoteType.DragHead, false)},
{NoteType.Hold, legacy.GetFillColor(NoteType.Hold, false)},
{NoteType.LongHold, legacy.GetFillColor(NoteType.LongHold, false)},
{NoteType.Flick, legacy.GetFillColor(NoteType.Flick, false)},
},
NoteFillColorsAlt = new Dictionary<NoteType, Color>
{
{NoteType.Click, legacy.GetFillColor(NoteType.Click, true)},
{NoteType.DragChild, legacy.GetFillColor(NoteType.DragChild, true)},
{NoteType.DragHead, legacy.GetFillColor(NoteType.DragHead, true)},
{NoteType.Hold, legacy.GetFillColor(NoteType.Hold, true)},
{NoteType.LongHold, legacy.GetFillColor(NoteType.LongHold, true)},
{NoteType.Flick, legacy.GetFillColor(NoteType.Flick, true)},
},
HoldHitSoundTiming = (HoldHitSoundTiming) legacy.HoldHitSoundTiming,
NoteSize = legacy.NoteSize,
HorizontalMargin = legacy.HorizontalMargin,
VerticalMargin = legacy.VerticalMargin,
CoverOpacity = legacy.CoverOpacity,
MusicVolume = legacy.MusicVolume,
SoundEffectsVolume = legacy.SoundEffectsVolume,
HitSound = "none",
HitTapticFeedback = legacy.HitTapticFeedback,
DisplayStoryboardEffects = legacy.UseStoryboardEffects,
GraphicsQuality = GetDefaultGraphicsQuality(),
BaseNoteOffset = legacy.BaseNoteOffset,
HeadsetNoteOffset = legacy.HeadsetNoteOffset,
ClearEffectsSize = legacy.ClearFXSize,
DisplayProfiler = legacy.DisplayProfiler,
DisplayNoteIds = legacy.DisplayNoteIds,
LocalLevelSort = Enum.TryParse<LevelSort>(legacy.LocalLevelsSortBy, out var sort) ? sort : LevelSort.AddedDate,
AndroidDspBufferSize = 1024, // Force 1024
LocalLevelSortIsAscending = legacy.LocalLevelsSortInAscendingOrder
};
return settings;
}
private GraphicsQuality GetDefaultGraphicsQuality()
{
if (Application.platform == RuntimePlatform.IPhonePlayer)
{
#if UNITY_IOS
if (UnityEngine.iOS.Device.generation >= UnityEngine.iOS.DeviceGeneration.iPadPro2Gen)
{
return GraphicsQuality.Ultra;
}
if (UnityEngine.iOS.Device.generation >= UnityEngine.iOS.DeviceGeneration.iPhone8)
{
return GraphicsQuality.High;
}
if (UnityEngine.iOS.Device.generation >= UnityEngine.iOS.DeviceGeneration.iPhone7)
{
return GraphicsQuality.Medium;
}
return GraphicsQuality.Low;
#endif
}
if (Application.platform == RuntimePlatform.Android)
{
var freq = SystemInfo.processorFrequency;
Debug.Log("Processor count: " + SystemInfo.processorCount);
Debug.Log("Processor frequency: ");
return GraphicsQuality.Medium;
}
return GraphicsQuality.Ultra;
}
public bool ShouldOneShot(string key)
{
if (Settings == null) throw new InvalidOperationException();
var used = Settings.PerformedOneShots.Contains(key);
if (used) return false;
Settings.PerformedOneShots.Add(key);
SaveSettings();
return true;
}
public void ClearOneShot(string key)
{
if (Settings == null) throw new InvalidOperationException();
Settings.PerformedOneShots.Remove(key);
SaveSettings();
}
public bool ShouldTrigger(string key, bool clear = true)
{
if (Settings == null) throw new InvalidOperationException();
var set = Settings.SetTriggers.Contains(key);
if (!set) return false;
if (clear)
{
Settings.SetTriggers.Remove(key);
SaveSettings();
}
return true;
}
public void ClearTrigger(string key)
{
ShouldTrigger(key);
}
public void SetTrigger(string key)
{
if (Settings == null) throw new InvalidOperationException();
Settings.SetTriggers.Add(key);
SaveSettings();
}
}
public class StringKey
{
public const string FirstLaunch = "First Launch1211111111111";
}
public class LocalPlayerLegacy
{
public bool PlayRanked
{
get => PlayerPrefsExtensions.GetBool("ranked");
set => PlayerPrefsExtensions.SetBool("ranked", value);
}
public HashSet<Mod> EnabledMods
{
get => new HashSet<Mod>(PlayerPrefsExtensions.GetStringArray("mods").Select(it => (Mod) Enum.Parse(typeof(Mod), it)).ToList());
set => PlayerPrefsExtensions.SetStringArray("mods", value.Select(it => it.ToString()).ToArray());
}
public bool ShowBoundaries
{
get => PlayerPrefsExtensions.GetBool("boundaries", false);
set => PlayerPrefsExtensions.SetBool("boundaries", value);
}
public bool DisplayEarlyLateIndicators
{
get => PlayerPrefsExtensions.GetBool("early_late_indicator", true);
set => PlayerPrefsExtensions.SetBool("early_late_indicator", value);
}
public int ClickHitboxSize
{
get => PlayerPrefs.GetInt("click hitbox size", 2);
set => PlayerPrefs.SetInt("click hitbox size", value);
}
public int DragHitboxSize
{
get => PlayerPrefs.GetInt("drag hitbox size", 2);
set => PlayerPrefs.SetInt("drag hitbox size", value);
}
public int HoldHitboxSize
{
get => PlayerPrefs.GetInt("hold hitbox size", 2);
set => PlayerPrefs.SetInt("hold hitbox size", value);
}
public int FlickHitboxSize
{
get => PlayerPrefs.GetInt("flick hitbox size", 1);
set => PlayerPrefs.SetInt("flick hitbox size", value);
}
public int HoldHitSoundTiming
{
get => PlayerPrefs.GetInt("HoldHitSoundTiming", (int) global::HoldHitSoundTiming.Both);
set => PlayerPrefs.SetInt("HoldHitSoundTiming", value);
}
// Bounded by -0.5~0.5.
public float NoteSize
{
get => PlayerPrefs.GetFloat("NoteSize", 0);
set => PlayerPrefs.SetFloat("NoteSize", value);
}
// Bounded by 1~5.
public int HorizontalMargin
{
get => (int) PlayerPrefs.GetFloat("HorizontalMargin", 3);
set => PlayerPrefs.SetFloat("HorizontalMargin", value);
}
// Bounded by 1~5.
public int VerticalMargin
{
get => (int) PlayerPrefs.GetFloat("VerticalMargin", 3);
set => PlayerPrefs.SetFloat("VerticalMargin", value);
}
// Bounded by 0~1.
public float CoverOpacity
{
get => PlayerPrefs.GetFloat("CoverOpacity", 0.15f);
set => PlayerPrefs.SetFloat("CoverOpacity", value);
}
// Bounded by 0~1.
public float MusicVolume
{
get => PlayerPrefs.GetFloat("MusicVolume", 0.85f);
set => PlayerPrefs.SetFloat("MusicVolume", value);
}
// Bounded by 0~1.
public float SoundEffectsVolume
{
get => PlayerPrefs.GetFloat("SoundEffectsVolume", 1f);
set => PlayerPrefs.SetFloat("SoundEffectsVolume", value);
}
public string HitSound
{
get => PlayerPrefs.GetString("HitSound", "none").ToLower();
set => PlayerPrefs.SetString("HitSound", value.ToLower());
}
public bool HitTapticFeedback
{
get => PlayerPrefsExtensions.GetBool("HitTapticFeedback", true);
set => PlayerPrefsExtensions.SetBool("HitTapticFeedback", value);
}
public bool UseStoryboardEffects
{
get => PlayerPrefsExtensions.GetBool("StoryboardEffects", true);
set => PlayerPrefsExtensions.SetBool("StoryboardEffects", value);
}
public string GraphicsQuality
{
get => PlayerPrefs.GetString("GraphicsQuality",
Application.platform == RuntimePlatform.Android ? "medium" : "high");
set => PlayerPrefs.SetString("GraphicsQuality", value.ToLower());
}
public float BaseNoteOffset
{
get => PlayerPrefs.GetFloat("main chart offset",
Application.platform == RuntimePlatform.Android ? 0.2f : 0.1f);
set => PlayerPrefs.SetFloat("main chart offset", value);
}
public float HeadsetNoteOffset
{
get => PlayerPrefs.GetFloat("headset chart offset", -0.05f);
set => PlayerPrefs.SetFloat("headset chart offset", value);
}
public float ClearFXSize
{
get => PlayerPrefs.GetFloat("ClearFXSize", 0);
set => PlayerPrefs.SetFloat("ClearFXSize", value);
}
public bool DisplayProfiler
{
get => PlayerPrefsExtensions.GetBool("profiler", false);
set
{
PlayerPrefsExtensions.SetBool("profiler", value);
Context.UpdateProfilerDisplay();
}
}
public bool DisplayNoteIds
{
get => PlayerPrefsExtensions.GetBool("note ids");
set => PlayerPrefsExtensions.SetBool("note ids", value);
}
public string LocalLevelsSortBy
{
get => PlayerPrefs.GetString("local levels sort by", LevelSort.AddedDate.ToString());
set => PlayerPrefs.SetString("local levels sort by", value);
}
public int DspBufferSize
{
get => PlayerPrefs.GetInt("AndroidDspBufferSize", -1);
set => PlayerPrefs.SetInt("AndroidDspBufferSize", value);
}
public bool LocalLevelsSortInAscendingOrder
{
get => PlayerPrefsExtensions.GetBool("local levels sort in ascending order", false);
set => PlayerPrefsExtensions.SetBool("local levels sort in ascending order", value);
}
public float GetLevelNoteOffset(string levelId)
{
return PlayerPrefs.GetFloat($"level {levelId} chart offset", 0);
}
public void SetLevelNoteOffset(string levelId, float offset)
{
PlayerPrefs.SetFloat($"level {levelId} chart offset", offset);
}
public Color GetRingColor(NoteType type, bool alt)
{
return PlayerPrefsExtensions.GetColor("ring color", "#FFFFFF");
}
public void SetRingColor(NoteType type, bool alt, Color color)
{
PlayerPrefsExtensions.SetColor("ring color", color);
}
private static Dictionary<NoteType, string> NoteTypeConfigKeyMapping = new Dictionary<NoteType, string>
{
{NoteType.Click, "click"}, {NoteType.DragHead, "drag"}, {NoteType.DragChild, "drag"},
{NoteType.Hold, "hold"}, {NoteType.LongHold, "long hold"}, {NoteType.Flick, "flick"}
};
private static Dictionary<NoteType, string[]> NoteTypeDefaultFillColors = new Dictionary<NoteType, string[]>
{
{NoteType.Click, new[] {"#35A7FF", "#FF5964"}},
{NoteType.DragHead, new[] {"#39E59E", "#39E59E"}},
{NoteType.DragChild, new[] {"#39E59E", "#39E59E"}},
{NoteType.Hold, new[] {"#35A7FF", "#FF5964"}},
{NoteType.LongHold, new[] {"#F2C85A", "#F2C85A"}},
{NoteType.Flick, new[] {"#35A7FF", "#FF5964"}}
};
public Color GetFillColor(NoteType type, bool alt)
{
return PlayerPrefsExtensions.GetColor($"fill color ({NoteTypeConfigKeyMapping[type]} {(alt ? 2 : 1)})", NoteTypeDefaultFillColors[type][alt ? 1 : 0]);
}
public void SetFillColor(NoteType type, bool alt, Color color)
{
PlayerPrefsExtensions.SetColor($"fill color ({NoteTypeConfigKeyMapping[type]} {(alt ? 2 : 1)})", color);
}
public class Performance
{
public int Score;
public float Accuracy; // 0~100
public string ClearType;
}
public bool HasPerformance(string levelId, string chartType, bool ranked)
{
return GetBestPerformance(levelId, chartType, ranked).Score >= 0;
}
public Performance GetBestPerformance(string levelId, string chartType, bool ranked)
{
return new Performance
{
Score = (int) SecuredPlayerPrefs.GetFloat(BestScoreKey(levelId, chartType, ranked), -1),
Accuracy = SecuredPlayerPrefs.GetFloat(BestAccuracyKey(levelId, chartType, ranked), -1),
ClearType = SecuredPlayerPrefs.GetString(BestClearTypeKey(levelId, chartType, ranked), "")
};
}
public void SetBestPerformance(string levelId, string chartType, bool ranked, Performance performance)
{
SecuredPlayerPrefs.SetFloat(BestScoreKey(levelId, chartType, ranked), performance.Score);
SecuredPlayerPrefs.SetFloat(BestAccuracyKey(levelId, chartType, ranked), performance.Accuracy);
SecuredPlayerPrefs.SetString(BestClearTypeKey(levelId, chartType, ranked), performance.ClearType);
}
public DateTime GetAddedDate(string levelId)
{
return SecuredPlayerPrefs.HasKey(AddedKey(levelId)) ?
DateTime.Parse(SecuredPlayerPrefs.GetString(AddedKey(levelId), null)) :
default;
}
public void SetAddedDate(string levelId, DateTime dateTime)
{
SecuredPlayerPrefs.SetString(AddedKey(levelId), dateTime.ToString("s"));
}
public DateTime GetLastPlayedDate(string levelId)
{
return SecuredPlayerPrefs.HasKey(LastPlayedKey(levelId)) ?
DateTime.Parse(SecuredPlayerPrefs.GetString(LastPlayedKey(levelId), null)) :
default;
}
public void SetLastPlayedDate(string levelId, DateTime dateTime)
{
SecuredPlayerPrefs.SetString(LastPlayedKey(levelId), dateTime.ToString("s"));
}
public int GetPlayCount(string levelId, string chartType)
{
return SecuredPlayerPrefs.GetInt(PlayCountKey(levelId, chartType), 0);
}
public void SetPlayCount(string levelId, string chartType, int playCount)
{
SecuredPlayerPrefs.SetInt(PlayCountKey(levelId, chartType), playCount);
}
private static string AddedKey(string level) => level + " : " + "added";
private static string LastPlayedKey(string level) => level + " : " + "last played";
private static string BestScoreKey(string level, string type, bool ranked) => level + " : " + type + " : " + "best score" + (ranked ? " ranked" : "");
private static string BestAccuracyKey(string level, string type, bool ranked) => level + " : " + type + " : " + "best accuracy" + (ranked ? " ranked" : "");
private static string BestClearTypeKey(string level, string type, bool ranked) => level + " : " + type + " : " + "best clear type" + (ranked ? " ranked" : "");
private static string PlayCountKey(string level, string type) => level + " : " + type + " : " + "play count";
} | TigerHix/Cytoid | Assets/Scripts/Player/Player.cs | C# | mit | 24,520 |
namespace GiveCRM.Web.Areas.Admin.Controllers
{
using System;
using System.Web;
using System.Web.Mvc;
internal class ElmahResult : ActionResult
{
private readonly string resourceType;
public ElmahResult(): this(null)
{ }
public ElmahResult(string resourceType)
{
this.resourceType = resourceType;
}
public override void ExecuteResult(ControllerContext context)
{
var factory = new Elmah.ErrorLogPageFactory();
if (!string.IsNullOrEmpty(this.resourceType))
{
var pathInfo = "/" + this.resourceType;
context.HttpContext.RewritePath(FilePath(context), pathInfo, context.HttpContext.Request.QueryString.ToString());
}
var currentContext = GetCurrentContext(context);
var httpHandler = factory.GetHandler(currentContext, null, null, null);
var httpAsyncHandler = httpHandler as IHttpAsyncHandler;
if (httpAsyncHandler != null)
{
httpAsyncHandler.BeginProcessRequest(currentContext, r => { }, null);
return;
}
httpHandler.ProcessRequest(currentContext);
}
private static HttpContext GetCurrentContext(ControllerContext context)
{
var currentApplication = (HttpApplication)context.HttpContext.GetService(typeof(HttpApplication));
return currentApplication.Context;
}
private string FilePath(ControllerContext context)
{
return this.resourceType != "stylesheet" ?
context.HttpContext.Request.Path.Replace(String.Format("/{0}", this.resourceType), string.Empty) :
context.HttpContext.Request.Path;
}
}
} | GiveCampUK/GiveCRM | src/GiveCRM.Web/Areas/Admin/Controllers/ElmahResult.cs | C# | mit | 1,826 |
// Copyright (C) 2011-2019 Roki. Distributed under the MIT License
#ifndef INCLUDED_SROOK_TMPL_VT_SET_DIFFERENCE_HPP
#define INCLUDED_SROOK_TMPL_VT_SET_DIFFERENCE_HPP
#include <srook/tmpl/vt/detail/config.hpp>
#include <srook/tmpl/vt/unique.hpp>
#include <srook/tmpl/vt/concat.hpp>
#include <srook/tmpl/vt/not_fn.hpp>
#include <srook/tmpl/vt/bind.hpp>
#include <srook/tmpl/vt/is_contained_in.hpp>
#include <srook/type_traits/conditional.hpp>
SROOK_NESTED_NAMESPACE(srook, tmpl, vt) {
SROOK_INLINE_NAMESPACE(v1)
namespace detail {
template <class T, class... U>
struct contained_if
: conditional<not_fn<is_contained_in>::type<T, U...>::value, T, packer<>> {};
template <class T, class... U>
struct contained_if<T, packer<U...>> : contained_if<T, U...> {};
template <class, class>
struct set_difference_impl1;
template <class X, class... Xs, class R>
struct set_difference_impl1<packer<X, Xs...>, R>
: concat<
SROOK_DEDUCED_TYPENAME contained_if<X, R>::type,
SROOK_DEDUCED_TYPENAME set_difference_impl1<packer<Xs...>, R>::type
> {};
template <class... R>
struct set_difference_impl1<packer<>, packer<R...>>
: type_constant<packer<>> {};
template <class L, class R>
struct set_difference_impl2
: set_difference_impl1<
SROOK_DEDUCED_TYPENAME unique<L>::type,
SROOK_DEDUCED_TYPENAME unique<R>::type
> {};
} // namespace detail
template <class L, class R>
struct set_difference : detail::set_difference_impl2<L, R> {};
#if SROOK_CPP_ALIAS_TEMPLATES
template <class L, class R>
using set_difference_t = SROOK_DEDUCED_TYPENAME set_difference<L, R>::type;
#endif
SROOK_INLINE_NAMESPACE_END
} SROOK_NESTED_NAMESPACE_END(vt, tmpl, srook)
#endif
| falgon/SrookCppLibraries | srook/tmpl/vt/set_difference.hpp | C++ | mit | 1,711 |
/*
* The MIT License
*
* Copyright 2014 Paulius Šukys.
*
* 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.
*/
package smartfood;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.HttpsURLConnection;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
/**
* A wrapper for Yummly
* @author Paulius Šukys
*/
public class YummlyWrapper
{
private final Logger logger = jade.util.Logger.getMyLogger(this.getClass().getName());
private final static String API_URL = "https://api.yummly.com/v1/api/";
private final static String APP_ID = "1cf18976";
private final static String APP_KEY = "59bc08e9d8e8d840454478fbca8ae959";
YummlyWrapper()
{
//exists to defeat instantiation
}
/**
* Searches for a recipe and returns a list of recipes
* @param recipe recipe name
* @param allowedIngredients list of allowed ingredients
* @return list of found recipes
*/
public List searchRecipe(String recipe, String[] allowedIngredients)
{
String query = "recipes?q=" + recipe;
List<Recipe> recipes;
recipes = new ArrayList();
try
{
query += getAllowedIngredients(allowedIngredients);
String response = getResponse(API_URL + query);
Iterator<JSONObject> iterator = getJSONmatchArray(response, "matches");
while (iterator.hasNext())
{
JSONObject match = iterator.next();
//setting up a Recipe object and appending to arraylist
Recipe r = new Recipe();
JSONObject flavors = (JSONObject)match.get("flavors");
if (flavors != null)
{
r.addFlavor("salty", (double)flavors.get("salty"));
r.addFlavor("meaty", (double)flavors.get("meaty"));
r.addFlavor("sour", (double)flavors.get("sour"));
r.addFlavor("sweet", (double)flavors.get("sweet"));
r.addFlavor("bitter", (double)flavors.get("bitter"));
}
r.setRating((long)match.get("rating"));
r.setName((String)match.get("recipeName"));
r.setSource((String)match.get("sourceDisplayName"));
JSONArray ing = (JSONArray)match.get("ingredients");
Iterator<String> ii = ing.iterator();
while(ii.hasNext())
{
r.addIngredient(ii.next());
}
r.setId((String)match.get("id"));
recipes.add(r);
}
}catch(UnsupportedEncodingException exc)
{
logger.log(Level.SEVERE, "Encoding error");
logger.log(Level.SEVERE, exc.getMessage());
}
return recipes;
}
private String getResponse(String query)
{
StringBuilder response = new StringBuilder();
try
{
URL url = new URL(query);
HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("X-Yummly-App-ID", APP_ID);
conn.setRequestProperty("X-Yummly-App-Key", APP_KEY);
String res = checkResponse(conn.getResponseCode());
if(!res.isEmpty())
{
System.out.println(res);
}else
{
try (BufferedReader in = new BufferedReader(new InputStreamReader(
conn.getInputStream())))
{
String inputLine = in.readLine();
while (inputLine != null)
{
response.append(inputLine);
inputLine =in.readLine();
}
}
}
conn.disconnect();
}catch(MalformedURLException exc)
{
logger.log(Level.SEVERE, "Malformed URL:");
logger.log(Level.SEVERE, exc.getMessage());
}catch(IOException exc)
{
logger.log(Level.SEVERE, "IO error");
logger.log(Level.SEVERE, exc.getMessage());
}
return response.toString();
}
private String checkResponse(int response)
{
String msg = "";
switch(response)
{
case 400:
msg = "Bad request";
break;
case 409:
msg = "API Rate Limit Exceeded";
break;
case 500:
msg = "Internal Server Error";
break;
default:
msg = "Unknown error";
break;
}
return msg;
}
/**
* Simply a method to make a query string for GET request
* @param ingredients String array of ingredients
* @return query string for GET request part
*/
private String getAllowedIngredients(String[] ingredients) throws UnsupportedEncodingException
{
String query = "";
for (String ingredient: ingredients)
{
query += "&allowedIngredient[]=";
query += URLEncoder.encode(ingredient, "UTF-8");
}
return query;
}
/**
* Parses JSON into found queried objects iterator
* @param content string to parse as json
* @param query text to match in json
* @return iterator for jsonarray
*/
private Iterator<JSONObject> getJSONmatchArray(String content, String query)
{
try
{
//since response is in json - parse it!
JSONParser jsonparser = new JSONParser();
JSONObject obj = (JSONObject)jsonparser.parse(content);
//adding all matches to array
JSONArray matches = (JSONArray)obj.get(query);
return matches.iterator();
} catch (ParseException ex)
{
logger.log(Level.SEVERE, "Error while parsing JSON");
logger.log(Level.SEVERE, null, ex);
}
return null;
}
}
| shookees/SmartFood_old | src/smartfood/YummlyWrapper.java | Java | mit | 7,629 |
var request = require('request'),
Q = require('q'),
xml2js = require('xml2js'),
_ = require('lodash');
module.exports = {
/**
* Helper function that handles the http request
*
* @param {string} url
*/
httprequest: function(url) {
var deferred = Q.defer();
request(url, function(err, response, body) {
if (err) {
deferred.reject(new Error(err));
} else if (!err && response.statusCode !== 200) {
deferred.reject(new Error(response.statusCode));
} else {
deferred.resolve(body);
}
});
return deferred.promise;
},
/**
* Helper function that converts xml to json
*
* @param {xml} xml
*/
toJson: function(xml) {
var deferred = Q.defer();
xml2js.parseString(xml, function(err, result) {
if (err) {
deferred.reject(new Error(err));
} else {
deferred.resolve(result);
}
});
return deferred.promise;
},
/**
* Helper function that takes params hash and converts it into query string
*
* @param {object} params
* @param {Number} id
*/
toQueryString: function(params, id) {
var paramsString = '';
for (var key in params) {
if (params.hasOwnProperty(key)) {
paramsString += '&' + key + '=' + encodeURIComponent(params[key]);
}
}
return 'zws-id=' + id + paramsString;
},
/**
* Helper function that checks for the required params
*
* @param {object} params
* @param {array} reqParams -- required parameters
*/
checkParams: function(params, reqParams) {
if ( reqParams.length < 1 ) return;
if ( (_.isEmpty(params) || !params) && (reqParams.length > 0) ){
throw new Error('Missing parameters: ' + reqParams.join(', '));
}
var paramsKeys = _.keys(params);
_.each(reqParams, function(reqParam) {
if ( paramsKeys.indexOf(reqParam) === -1 ) {
throw new Error('Missing parameter: ' + reqParam);
}
});
}
};
| LoganArnett/node-zillow | lib/helpers.js | JavaScript | mit | 1,998 |
# frozen_string_literal: true
module Signable
module Concerns
module Query
extend ActiveSupport::Concern
def save
return false unless valid?
persisted? ? update : create
end
def delete
self.class.client.delete self.class.entry_point, id
end
def persisted?
id.present?
rescue StandardError
false
end
private
def update
response = self.class.client.update self.class.entry_point, id, self
response.ok?
end
def create
response = self.class.client.create self.class.entry_point, self
if response.ok?
self.attributes = response.object
true
else
false
end
end
module ClassMethods
def all(offset: 0, limit: 30)
response = client.all(entry_point, offset, limit)
if response.ok?
List.new(self, response.object)
else
[]
end
end
def find(id)
response = client.find(entry_point, id)
new response.object if response.ok?
end
def entry_point
prefix.pluralize
end
def client
@client ||= Signable::Query::Client.new
end
end
end
end
end
| smartpension/signable | lib/signable/concerns/query.rb | Ruby | mit | 1,321 |
var closet = closet || {};
(function($) {
closet.folders = (function() {
var iconPlus = '<img class="icon" style="width:10px" src="/static/image/16x16/Plus.png"/>';
var iconMinus = '<img class="icon" style="width:10px" src="/static/image/16x16/Minus.png"/>';
var iconEmpty = '<img class="icon" style="width:10px" src="/static/image/16x16/Folder3.png"/>';
var toggle = function($root) {
var $children = $root.children('div.children');
var $toggle = $root.children('a.toggle');
if ($children.css('display') === 'none') {
$children.css('display', '');
$toggle.html(iconMinus);
} else {
$children.css('display', 'none');
$toggle.html(iconPlus);
}
};
var addFolders = function($root, depth, cb) {
var root = $root.data('path');
var $children = $root.children('div.children');
toggle($root);
var url = '/pcaps/1/list?by=path';
if (depth > 1) {
var paths = root.split('/');
var startkey = paths.concat([0]);
var endkey = paths.concat([{}]);
url += '&startkey=' + JSON.stringify(startkey);
url += '&endkey=' + JSON.stringify(endkey);
}
$.ajax({
url: url,
data: { group_level: depth, limit: 20 },
dataType: 'json',
success: function(kvs) {
if (kvs.rows.length === 0 && depth > 1) {
$root.find('a.toggle').replaceWith(iconEmpty);
return;
}
$.each(kvs.rows, function(_, kv) {
if (kv.key.length !== depth) { return; }
var path = kv.key.join('/');
$children.append(
'<div class="folder">' +
'<a class="toggle"/> ' +
'<a class="link" title="' + path + '">' + kv.key[depth-1] + '</a>' +
' ' +
'<sup style="font-size:smaller">' + kv.value + '</sup>' +
'<div class="children" style="margin-left:20px;display:none"/>' +
'</div>'
).find('div.folder:last').data('path', path);
});
$children
.find('a.toggle').attr('href', 'javascript:void(0)')
.html('<img class="icon" style="width:10px" src="/static/image/16x16/Plus.png"/>')
.click(function() {
var folder = $(this).parent('div.folder');
var children = $(this).nextAll('div.children');
if (children.children().length === 0) {
addFolders(folder, depth+1, cb);
} else {
toggle(folder);
}
})
.end()
.find('a.link').attr('href', 'javascript:void(0)')
.click(function() {
cb($(this).parent('div.folder').data('path'));
});
}
});
};
return {
manage: function($root, cb) {
var $f = $root.data('folders');
if (!$f) {
$f = $('<div class="folder" style="margin-top: 20px;margin-bottom:20px"><div class="children" style="display:none"/></div>');
$f.data('path', '/');
$root.data('folders', $f);
addFolders($f, 1, cb);
}
$root.empty().append($f);
}
};
}());
}(jQuery));
| mudynamics/pcapr-local | lib/pcapr_local/www/static/script/closet/closet.folders.js | JavaScript | mit | 3,861 |
import sys
import pdb
import svgfig
import json
import os
import math
import random
def show_help():
print("Usage: main.py input_file [--silent] [--output=<out.svg>]" +
" [--order=order.txt]")
print("Input file is either a text file containing t u v," +
"or a JSON file where the following properties are available:")
print(" from")
print(" to")
print(" time")
print(" color: to be chosen in " +
"http://www.december.com/html/spec/colorsvg.html")
print("The orderFile contains a list of all nodes to display " +
"in the order of appearance in orderFile.")
def read_argv(argv):
for arg in sys.argv:
if "=" in arg:
content = arg.split("=")
arg_name = content[0].replace("--", "")
argv[arg_name] = content[1]
elif "--" in arg:
arg_name = arg.replace("--", "")
argv[arg_name] = True
def version():
sys.stderr.write("\tLinkStreamViz 1.0 -- Jordan Viard 2015\n")
class idGenerator:
"""generates id"""
def __init__(self):
self.lookUp = dict() # dict[Node] = id
self.idCount = 0
self.reverse = dict() # dict[id] = node
def impose(self, node, id_):
self.lookUp[node] = id_
self.reverse[id_] = node
def contains(self, element):
return element in self.lookUp
def get(self, element):
if element not in self.lookUp:
while self.idCount in self.reverse and self.reverse[self.idCount] != element:
self.idCount += 1
self.lookUp[element] = self.idCount
self.reverse[self.idCount] = element
return self.lookUp[element]
def size(self):
return len(self.lookUp)
class Link:
def __init__(self, t, u, v, color="black", direction=0, duration=0, duration_color="black"):
self.t = float(t)
self.u = int(min(u, v))
self.v = int(max(u, v))
self.color = color
self.direction = direction
self.duration = duration
self.duration_color = duration_color
@staticmethod
def from_dict(link):
obj = Link(link["time"],
link["from"],
link["to"])
obj.color = link.get("color", "black")
obj.direction = link.get("direction", 0)
obj.duration = float(link.get("duration", 0))
obj.duration_color = link.get("duration_color", "black")
return obj
class LinkStream:
def __init__(self, inputFile, orderFile=""):
self.links = []
self.max_time = 0
self.nodeID = idGenerator()
self.max_label_len = 0
self.g = svgfig.SVG("g")
self.ppux = 10 # piwel per unit time
if "json" in inputFile:
with open(inputFile, 'r') as inFile:
json_struct = json.loads(inFile.read())
for link_json in json_struct:
link = Link.from_dict(link_json)
self.addNode(link.u)
self.addNode(link.v)
if (link.t + link.duration) > self.max_time:
self.max_time = link.t + link.duration
self.links.append(link)
else:
with open(inputFile, 'r') as inFile:
for line in inFile:
contents = line.split(" ")
t = float(contents[0])
u = int(contents[1])
v = int(contents[2])
d = 0
if len(contents) > 3:
d = float(contents[3])
self.addNode(u)
self.addNode(v)
if t > self.max_time:
self.max_time = t
self.links.append(Link(t, u, v, duration=d))
if orderFile != "":
tmp_nodes = set()
with open(orderFile, 'r') as order:
for i, n in enumerate(order):
node = int(n)
tmp_nodes.add(node)
if self.nodeID.contains(node):
self.nodeID.impose(node, i)
self.nodes.append(node)
else:
print('The node', node, "is not present in the stream")
exit()
for node in self.nodeID.lookUp:
if node not in tmp_nodes:
print('The node', node, "is not present in", orderFile)
exit()
def addNode(self, node):
self.nodeID.get(node)
if self.max_label_len < len(str(node)):
self.max_label_len = len(str(node))
def evaluateOrder(self, order):
distance = 0
for link in self.links:
distance += abs(order[link.u]-order[link.v])
return distance
def findOrder(self):
cur_solution = self.nodeID.lookUp
cur_reverse = self.nodeID.reverse
dist = self.evaluateOrder(cur_solution)
sys.stderr.write("Order improved from "+str(dist))
for i in range(0, 10000):
i = random.randint(0, len(cur_solution) - 1)
j = random.randint(0, len(cur_solution) - 1)
cur_reverse[j], cur_reverse[i] = cur_reverse[i], cur_reverse[j]
cur_solution[cur_reverse[j]] = j
cur_solution[cur_reverse[i]] = i
tmp = self.evaluateOrder(cur_solution)
if tmp >= dist:
# re swap to go back.
cur_reverse[j], cur_reverse[i] = cur_reverse[i], cur_reverse[j]
cur_solution[cur_reverse[j]] = j
cur_solution[cur_reverse[i]] = i
else:
dist = tmp
self.nodeID.lookUp = cur_solution
new_order = "new_order.txt"
with open(new_order, "w") as out:
for node in self.nodeID.reverse:
out.write(str(self.nodeID.reverse[node]) + "\n")
sys.stderr.write(" to "+str(dist)+". Order saved in:"+new_order+"\n")
def addDuration(self, origin, duration, color, amplitude=1):
freq = 0.8 # angular frequency
duration = duration * self.ppux
self.g.append(svgfig.SVG("line",
stroke=color,
stroke_opacity=0.8,
stroke_width=1.1,
x1=origin["x"],
y1=origin["y"],
x2=origin["x"]+duration,
y2=origin["y"]))
def draw(self, outputFile):
self.findOrder()
offset = 1.5 * self.ppux
# Define dimensions
label_margin = 5 * self.max_label_len
origleft = label_margin + 1 * self.ppux
right_margin = self.ppux
width = origleft + self.ppux * math.ceil(self.max_time) + right_margin
svgfig._canvas_defaults["width"] = str(width) + 'px'
arrow_of_time_height = 5
height = 5 + 10 * int(self.nodeID.size() + 1) + arrow_of_time_height
svgfig._canvas_defaults["height"] = str(height) + 'px'
origtop = 10
################
# Draw background lines
for node in self.nodeID.lookUp:
horizonta_axe = self.ppux * self.nodeID.get(node) + origtop
self.g.append(svgfig.SVG("text", str(node),
x=str(label_margin),
y=horizonta_axe + 2,
fill="black", stroke_width=0,
text_anchor="end",
font_size="6"))
self.g.append(svgfig.SVG("line", stroke_dasharray="2,2",
stroke_width=0.5,
x1=str(origleft-5),
y1=horizonta_axe,
x2=width - right_margin,
y2=horizonta_axe))
# Add timearrow
self.g.append(svgfig.SVG("line",
stroke_width=0.5,
x1=self.ppux ,
y1=10*(self.nodeID.size()+1),
x2=width-5,
y2=10*(self.nodeID.size()+1)))
self.g.append(svgfig.SVG("line", stroke_width=0.5,
x1=width-8,
y1=10*(self.nodeID.size()+1)-3,
x2=width-5,
y2=10*(self.nodeID.size()+1)))
self.g.append(svgfig.SVG("line", stroke_width=0.5,
x1=width-8,
y1=10*(self.nodeID.size()+1)+3,
x2=width-5,
y2=10*(self.nodeID.size()+1)))
self.g.append(svgfig.SVG("text", str("Time"),
x=width-19,
y=10*(self.nodeID.size()+1)-3,
fill="black", stroke_width=0,
font_size="6"))
#
# Add time ticks
for i in range(0, int(math.ceil(self.max_time)+1), 5):
x_tick = i * self.ppux + origleft
self.g.append(svgfig.SVG("line",
stroke_width=0.5,
x1=str(x_tick),
y1=10*(self.nodeID.size()+1)-3,
x2=str(x_tick),
y2=10*(self.nodeID.size()+1)+3))
self.g.append(svgfig.SVG("text", str(i),
x=str(x_tick), y=10*(self.nodeID.size()+1)+7,
fill="black", stroke_width=0,
font_size="6"))
for link in self.links:
ts = link.t
node_1 = min(self.nodeID.get(link.u), self.nodeID.get(link.v))
node_2 = max(self.nodeID.get(link.u), self.nodeID.get(link.v))
offset = ts * self.ppux + origleft
y_node1 = 10 * node_1 + origtop
y_node2 = 10 * node_2 + origtop
# Add nodes
self.g.append(svgfig.SVG("circle",
cx=offset, cy=y_node1,
r=1, fill=link.color))
self.g.append(svgfig.SVG("circle",
cx=offset, cy=y_node2,
r=1, fill=link.color))
x = 0.2 * ((10 * node_2 - 10 * node_1) / math.tan(math.pi / 3)) + offset
y = (y_node1 + y_node2) / 2
param_d = "M" + str(offset) + "," + str(y_node1) +\
" C" + str(x) + "," + str(y) + " " + str(x) + "," + str(y) +\
" " + str(offset) + "," + str(y_node2)
self.g.append(svgfig.SVG("path", stroke=link.color,
d=param_d))
self.addDuration({"x": x, "y": (y_node1+y_node2)/2}, link.duration, link.duration_color)
# Save to svg file
viewBoxparam = "0 0 " + str(width) + " " + str(height)
svgfig.canvas(self.g, viewBox=viewBoxparam).save(outputFile)
if __name__ == '__main__':
if len(sys.argv) < 2 or "--help" in sys.argv or "-h" in sys.argv:
show_help()
sys.exit()
if "-v" in sys.argv or "--version" in sys.argv:
version()
exit()
argv = {"order": "", "silent": False}
read_argv(argv)
Links = LinkStream(sys.argv[1], argv["order"])
default_output = os.path.basename(sys.argv[1]).split(".")[0]+".svg"
argv["output"] = argv.get("output", default_output)
Links.draw(argv["output"])
if not argv["silent"]:
sys.stderr.write("Output generated to " + argv["output"] + ".\n")
| JordanV/LinkStreamViz | main.py | Python | mit | 11,963 |
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-comp-4719',
templateUrl: './comp-4719.component.html',
styleUrls: ['./comp-4719.component.css']
})
export class Comp4719Component implements OnInit {
constructor() { }
ngOnInit() {
}
}
| angular/angular-cli-stress-test | src/app/components/comp-4719/comp-4719.component.ts | TypeScript | mit | 484 |
from django.contrib import admin
from player.models import Room, PlaylistTrack
from ordered_model.admin import OrderedModelAdmin
class RoomAdmin(admin.ModelAdmin):
list_display = ('name', 'shuffle', 'current_music', 'can_adjust_volume')
class ItemAdmin(OrderedModelAdmin):
list_display = ('move_up_down_links', 'order', 'track', 'room')
admin.site.register(Room, RoomAdmin)
admin.site.register(PlaylistTrack, ItemAdmin)
| Amoki/Amoki-Music | player/admin.py | Python | mit | 434 |
define(function(require) {
var $ = require('jquery');
var Point = require('joss/geometry/Point');
var _scrollIsRelative = !($.browser.opera || $.browser.safari && $.browser.version < "532");
/**
* Returns a DOM element lying at a point
*
* @param {joss/geometry/Point} p
* @return {Element}
*/
var fromPoint = function(x, y) {
if(!document.elementFromPoint) {
return null;
}
var p;
if (x.constructor === Point) {
p = x;
}
else {
p = new Point(x, y);
}
if(_scrollIsRelative)
{
p.x -= $(document).scrollLeft();
p.y -= $(document).scrollTop();
}
return document.elementFromPoint(p.x, p.y);
};
return fromPoint;
});
| zship/joss | src/joss/util/elements/fromPoint.js | JavaScript | mit | 681 |
/* Google Material Design Icons */
export declare const sharp10k: string;
export declare const sharp10mp: string;
export declare const sharp11mp: string;
export declare const sharp12mp: string;
export declare const sharp13mp: string;
export declare const sharp14mp: string;
export declare const sharp15mp: string;
export declare const sharp16mp: string;
export declare const sharp17mp: string;
export declare const sharp18mp: string;
export declare const sharp19mp: string;
export declare const sharp1k: string;
export declare const sharp1kPlus: string;
export declare const sharp1xMobiledata: string;
export declare const sharp20mp: string;
export declare const sharp21mp: string;
export declare const sharp22mp: string;
export declare const sharp23mp: string;
export declare const sharp24mp: string;
export declare const sharp2k: string;
export declare const sharp2kPlus: string;
export declare const sharp2mp: string;
export declare const sharp30fps: string;
export declare const sharp30fpsSelect: string;
export declare const sharp360: string;
export declare const sharp3dRotation: string;
export declare const sharp3gMobiledata: string;
export declare const sharp3k: string;
export declare const sharp3kPlus: string;
export declare const sharp3mp: string;
export declare const sharp3p: string;
export declare const sharp4gMobiledata: string;
export declare const sharp4gPlusMobiledata: string;
export declare const sharp4k: string;
export declare const sharp4kPlus: string;
export declare const sharp4mp: string;
export declare const sharp5g: string;
export declare const sharp5k: string;
export declare const sharp5kPlus: string;
export declare const sharp5mp: string;
export declare const sharp60fps: string;
export declare const sharp60fpsSelect: string;
export declare const sharp6FtApart: string;
export declare const sharp6k: string;
export declare const sharp6kPlus: string;
export declare const sharp6mp: string;
export declare const sharp7k: string;
export declare const sharp7kPlus: string;
export declare const sharp7mp: string;
export declare const sharp8k: string;
export declare const sharp8kPlus: string;
export declare const sharp8mp: string;
export declare const sharp9k: string;
export declare const sharp9kPlus: string;
export declare const sharp9mp: string;
export declare const sharpAccessAlarm: string;
export declare const sharpAccessAlarms: string;
export declare const sharpAccessibility: string;
export declare const sharpAccessibilityNew: string;
export declare const sharpAccessible: string;
export declare const sharpAccessibleForward: string;
export declare const sharpAccessTime: string;
export declare const sharpAccessTimeFilled: string;
export declare const sharpAccountBalance: string;
export declare const sharpAccountBalanceWallet: string;
export declare const sharpAccountBox: string;
export declare const sharpAccountCircle: string;
export declare const sharpAccountTree: string;
export declare const sharpAcUnit: string;
export declare const sharpAdb: string;
export declare const sharpAdd: string;
export declare const sharpAddAlarm: string;
export declare const sharpAddAlert: string;
export declare const sharpAddAPhoto: string;
export declare const sharpAddBox: string;
export declare const sharpAddBusiness: string;
export declare const sharpAddchart: string;
export declare const sharpAddChart: string;
export declare const sharpAddCircle: string;
export declare const sharpAddCircleOutline: string;
export declare const sharpAddComment: string;
export declare const sharpAddIcCall: string;
export declare const sharpAddLink: string;
export declare const sharpAddLocation: string;
export declare const sharpAddLocationAlt: string;
export declare const sharpAddModerator: string;
export declare const sharpAddPhotoAlternate: string;
export declare const sharpAddReaction: string;
export declare const sharpAddRoad: string;
export declare const sharpAddShoppingCart: string;
export declare const sharpAddTask: string;
export declare const sharpAddToDrive: string;
export declare const sharpAddToHomeScreen: string;
export declare const sharpAddToPhotos: string;
export declare const sharpAddToQueue: string;
export declare const sharpAdfScanner: string;
export declare const sharpAdjust: string;
export declare const sharpAdminPanelSettings: string;
export declare const sharpAdsClick: string;
export declare const sharpAdUnits: string;
export declare const sharpAgriculture: string;
export declare const sharpAir: string;
export declare const sharpAirlines: string;
export declare const sharpAirlineSeatFlat: string;
export declare const sharpAirlineSeatFlatAngled: string;
export declare const sharpAirlineSeatIndividualSuite: string;
export declare const sharpAirlineSeatLegroomExtra: string;
export declare const sharpAirlineSeatLegroomNormal: string;
export declare const sharpAirlineSeatLegroomReduced: string;
export declare const sharpAirlineSeatReclineExtra: string;
export declare const sharpAirlineSeatReclineNormal: string;
export declare const sharpAirlineStops: string;
export declare const sharpAirplanemodeActive: string;
export declare const sharpAirplanemodeInactive: string;
export declare const sharpAirplaneTicket: string;
export declare const sharpAirplay: string;
export declare const sharpAirportShuttle: string;
export declare const sharpAlarm: string;
export declare const sharpAlarmAdd: string;
export declare const sharpAlarmOff: string;
export declare const sharpAlarmOn: string;
export declare const sharpAlbum: string;
export declare const sharpAlignHorizontalCenter: string;
export declare const sharpAlignHorizontalLeft: string;
export declare const sharpAlignHorizontalRight: string;
export declare const sharpAlignVerticalBottom: string;
export declare const sharpAlignVerticalCenter: string;
export declare const sharpAlignVerticalTop: string;
export declare const sharpAllInbox: string;
export declare const sharpAllInclusive: string;
export declare const sharpAllOut: string;
export declare const sharpAlternateEmail: string;
export declare const sharpAltRoute: string;
export declare const sharpAnalytics: string;
export declare const sharpAnchor: string;
export declare const sharpAndroid: string;
export declare const sharpAnimation: string;
export declare const sharpAnnouncement: string;
export declare const sharpAod: string;
export declare const sharpApartment: string;
export declare const sharpApi: string;
export declare const sharpAppBlocking: string;
export declare const sharpAppRegistration: string;
export declare const sharpApproval: string;
export declare const sharpApps: string;
export declare const sharpAppSettingsAlt: string;
export declare const sharpAppShortcut: string;
export declare const sharpAppsOutage: string;
export declare const sharpArchitecture: string;
export declare const sharpArchive: string;
export declare const sharpAreaChart: string;
export declare const sharpArrowBack: string;
export declare const sharpArrowBackIos: string;
export declare const sharpArrowBackIosNew: string;
export declare const sharpArrowCircleDown: string;
export declare const sharpArrowCircleUp: string;
export declare const sharpArrowDownward: string;
export declare const sharpArrowDropDown: string;
export declare const sharpArrowDropDownCircle: string;
export declare const sharpArrowDropUp: string;
export declare const sharpArrowForward: string;
export declare const sharpArrowForwardIos: string;
export declare const sharpArrowLeft: string;
export declare const sharpArrowRight: string;
export declare const sharpArrowRightAlt: string;
export declare const sharpArrowUpward: string;
export declare const sharpArticle: string;
export declare const sharpArtTrack: string;
export declare const sharpAspectRatio: string;
export declare const sharpAssessment: string;
export declare const sharpAssignment: string;
export declare const sharpAssignmentInd: string;
export declare const sharpAssignmentLate: string;
export declare const sharpAssignmentReturn: string;
export declare const sharpAssignmentReturned: string;
export declare const sharpAssignmentTurnedIn: string;
export declare const sharpAssistant: string;
export declare const sharpAssistantDirection: string;
export declare const sharpAssistantPhoto: string;
export declare const sharpAtm: string;
export declare const sharpAttachEmail: string;
export declare const sharpAttachFile: string;
export declare const sharpAttachment: string;
export declare const sharpAttachMoney: string;
export declare const sharpAttractions: string;
export declare const sharpAttribution: string;
export declare const sharpAudiotrack: string;
export declare const sharpAutoAwesome: string;
export declare const sharpAutoAwesomeMosaic: string;
export declare const sharpAutoAwesomeMotion: string;
export declare const sharpAutoDelete: string;
export declare const sharpAutoFixHigh: string;
export declare const sharpAutoFixNormal: string;
export declare const sharpAutoFixOff: string;
export declare const sharpAutofpsSelect: string;
export declare const sharpAutoGraph: string;
export declare const sharpAutorenew: string;
export declare const sharpAutoStories: string;
export declare const sharpAvTimer: string;
export declare const sharpBabyChangingStation: string;
export declare const sharpBackHand: string;
export declare const sharpBackpack: string;
export declare const sharpBackspace: string;
export declare const sharpBackup: string;
export declare const sharpBackupTable: string;
export declare const sharpBadge: string;
export declare const sharpBakeryDining: string;
export declare const sharpBalance: string;
export declare const sharpBalcony: string;
export declare const sharpBallot: string;
export declare const sharpBarChart: string;
export declare const sharpBatchPrediction: string;
export declare const sharpBathroom: string;
export declare const sharpBathtub: string;
export declare const sharpBatteryAlert: string;
export declare const sharpBatteryChargingFull: string;
export declare const sharpBatteryFull: string;
export declare const sharpBatterySaver: string;
export declare const sharpBatteryStd: string;
export declare const sharpBatteryUnknown: string;
export declare const sharpBeachAccess: string;
export declare const sharpBed: string;
export declare const sharpBedroomBaby: string;
export declare const sharpBedroomChild: string;
export declare const sharpBedroomParent: string;
export declare const sharpBedtime: string;
export declare const sharpBeenhere: string;
export declare const sharpBento: string;
export declare const sharpBikeScooter: string;
export declare const sharpBiotech: string;
export declare const sharpBlender: string;
export declare const sharpBlock: string;
export declare const sharpBloodtype: string;
export declare const sharpBluetooth: string;
export declare const sharpBluetoothAudio: string;
export declare const sharpBluetoothConnected: string;
export declare const sharpBluetoothDisabled: string;
export declare const sharpBluetoothDrive: string;
export declare const sharpBluetoothSearching: string;
export declare const sharpBlurCircular: string;
export declare const sharpBlurLinear: string;
export declare const sharpBlurOff: string;
export declare const sharpBlurOn: string;
export declare const sharpBolt: string;
export declare const sharpBook: string;
export declare const sharpBookmark: string;
export declare const sharpBookmarkAdd: string;
export declare const sharpBookmarkAdded: string;
export declare const sharpBookmarkBorder: string;
export declare const sharpBookmarkRemove: string;
export declare const sharpBookmarks: string;
export declare const sharpBookOnline: string;
export declare const sharpBorderAll: string;
export declare const sharpBorderBottom: string;
export declare const sharpBorderClear: string;
export declare const sharpBorderColor: string;
export declare const sharpBorderHorizontal: string;
export declare const sharpBorderInner: string;
export declare const sharpBorderLeft: string;
export declare const sharpBorderOuter: string;
export declare const sharpBorderRight: string;
export declare const sharpBorderStyle: string;
export declare const sharpBorderTop: string;
export declare const sharpBorderVertical: string;
export declare const sharpBrandingWatermark: string;
export declare const sharpBreakfastDining: string;
export declare const sharpBrightness1: string;
export declare const sharpBrightness2: string;
export declare const sharpBrightness3: string;
export declare const sharpBrightness4: string;
export declare const sharpBrightness5: string;
export declare const sharpBrightness6: string;
export declare const sharpBrightness7: string;
export declare const sharpBrightnessAuto: string;
export declare const sharpBrightnessHigh: string;
export declare const sharpBrightnessLow: string;
export declare const sharpBrightnessMedium: string;
export declare const sharpBrokenImage: string;
export declare const sharpBrowserNotSupported: string;
export declare const sharpBrowserUpdated: string;
export declare const sharpBrunchDining: string;
export declare const sharpBrush: string;
export declare const sharpBubbleChart: string;
export declare const sharpBugReport: string;
export declare const sharpBuild: string;
export declare const sharpBuildCircle: string;
export declare const sharpBungalow: string;
export declare const sharpBurstMode: string;
export declare const sharpBusAlert: string;
export declare const sharpBusiness: string;
export declare const sharpBusinessCenter: string;
export declare const sharpCabin: string;
export declare const sharpCable: string;
export declare const sharpCached: string;
export declare const sharpCake: string;
export declare const sharpCalculate: string;
export declare const sharpCalendarToday: string;
export declare const sharpCalendarViewDay: string;
export declare const sharpCalendarViewMonth: string;
export declare const sharpCalendarViewWeek: string;
export declare const sharpCall: string;
export declare const sharpCallEnd: string;
export declare const sharpCallMade: string;
export declare const sharpCallMerge: string;
export declare const sharpCallMissed: string;
export declare const sharpCallMissedOutgoing: string;
export declare const sharpCallReceived: string;
export declare const sharpCallSplit: string;
export declare const sharpCallToAction: string;
export declare const sharpCamera: string;
export declare const sharpCameraAlt: string;
export declare const sharpCameraEnhance: string;
export declare const sharpCameraFront: string;
export declare const sharpCameraIndoor: string;
export declare const sharpCameraOutdoor: string;
export declare const sharpCameraRear: string;
export declare const sharpCameraRoll: string;
export declare const sharpCameraswitch: string;
export declare const sharpCampaign: string;
export declare const sharpCancel: string;
export declare const sharpCancelPresentation: string;
export declare const sharpCancelScheduleSend: string;
export declare const sharpCandlestickChart: string;
export declare const sharpCardGiftcard: string;
export declare const sharpCardMembership: string;
export declare const sharpCardTravel: string;
export declare const sharpCarpenter: string;
export declare const sharpCarRental: string;
export declare const sharpCarRepair: string;
export declare const sharpCases: string;
export declare const sharpCasino: string;
export declare const sharpCast: string;
export declare const sharpCastConnected: string;
export declare const sharpCastForEducation: string;
export declare const sharpCatchingPokemon: string;
export declare const sharpCategory: string;
export declare const sharpCelebration: string;
export declare const sharpCellWifi: string;
export declare const sharpCenterFocusStrong: string;
export declare const sharpCenterFocusWeak: string;
export declare const sharpChair: string;
export declare const sharpChairAlt: string;
export declare const sharpChalet: string;
export declare const sharpChangeCircle: string;
export declare const sharpChangeHistory: string;
export declare const sharpChargingStation: string;
export declare const sharpChat: string;
export declare const sharpChatBubble: string;
export declare const sharpChatBubbleOutline: string;
export declare const sharpCheck: string;
export declare const sharpCheckBox: string;
export declare const sharpCheckBoxOutlineBlank: string;
export declare const sharpCheckCircle: string;
export declare const sharpCheckCircleOutline: string;
export declare const sharpChecklist: string;
export declare const sharpChecklistRtl: string;
export declare const sharpCheckroom: string;
export declare const sharpChevronLeft: string;
export declare const sharpChevronRight: string;
export declare const sharpChildCare: string;
export declare const sharpChildFriendly: string;
export declare const sharpChromeReaderMode: string;
export declare const sharpCircle: string;
export declare const sharpCircleNotifications: string;
export declare const sharpClass: string;
export declare const sharpCleanHands: string;
export declare const sharpCleaningServices: string;
export declare const sharpClear: string;
export declare const sharpClearAll: string;
export declare const sharpClose: string;
export declare const sharpClosedCaption: string;
export declare const sharpClosedCaptionDisabled: string;
export declare const sharpClosedCaptionOff: string;
export declare const sharpCloseFullscreen: string;
export declare const sharpCloud: string;
export declare const sharpCloudCircle: string;
export declare const sharpCloudDone: string;
export declare const sharpCloudDownload: string;
export declare const sharpCloudOff: string;
export declare const sharpCloudQueue: string;
export declare const sharpCloudSync: string;
export declare const sharpCloudUpload: string;
export declare const sharpCo2: string;
export declare const sharpCode: string;
export declare const sharpCodeOff: string;
export declare const sharpCoffee: string;
export declare const sharpCoffeeMaker: string;
export declare const sharpCollections: string;
export declare const sharpCollectionsBookmark: string;
export declare const sharpColorize: string;
export declare const sharpColorLens: string;
export declare const sharpComment: string;
export declare const sharpCommentBank: string;
export declare const sharpCommentsDisabled: string;
export declare const sharpCommit: string;
export declare const sharpCommute: string;
export declare const sharpCompare: string;
export declare const sharpCompareArrows: string;
export declare const sharpCompassCalibration: string;
export declare const sharpCompost: string;
export declare const sharpCompress: string;
export declare const sharpComputer: string;
export declare const sharpConfirmationNumber: string;
export declare const sharpConnectedTv: string;
export declare const sharpConnectingAirports: string;
export declare const sharpConnectWithoutContact: string;
export declare const sharpConstruction: string;
export declare const sharpContactless: string;
export declare const sharpContactMail: string;
export declare const sharpContactPage: string;
export declare const sharpContactPhone: string;
export declare const sharpContacts: string;
export declare const sharpContactSupport: string;
export declare const sharpContentCopy: string;
export declare const sharpContentCut: string;
export declare const sharpContentPaste: string;
export declare const sharpContentPasteOff: string;
export declare const sharpContentPasteSearch: string;
export declare const sharpContrast: string;
export declare const sharpControlCamera: string;
export declare const sharpControlPoint: string;
export declare const sharpControlPointDuplicate: string;
export declare const sharpCookie: string;
export declare const sharpCoPresent: string;
export declare const sharpCopyAll: string;
export declare const sharpCopyright: string;
export declare const sharpCoronavirus: string;
export declare const sharpCorporateFare: string;
export declare const sharpCottage: string;
export declare const sharpCountertops: string;
export declare const sharpCreate: string;
export declare const sharpCreateNewFolder: string;
export declare const sharpCreditCard: string;
export declare const sharpCreditCardOff: string;
export declare const sharpCreditScore: string;
export declare const sharpCrib: string;
export declare const sharpCrop: string;
export declare const sharpCrop169: string;
export declare const sharpCrop32: string;
export declare const sharpCrop54: string;
export declare const sharpCrop75: string;
export declare const sharpCropDin: string;
export declare const sharpCropFree: string;
export declare const sharpCropLandscape: string;
export declare const sharpCropOriginal: string;
export declare const sharpCropPortrait: string;
export declare const sharpCropRotate: string;
export declare const sharpCropSquare: string;
export declare const sharpCrueltyFree: string;
export declare const sharpCurrencyFranc: string;
export declare const sharpCurrencyLira: string;
export declare const sharpCurrencyPound: string;
export declare const sharpCurrencyRuble: string;
export declare const sharpCurrencyRupee: string;
export declare const sharpCurrencyYen: string;
export declare const sharpCurrencyYuan: string;
export declare const sharpDangerous: string;
export declare const sharpDarkMode: string;
export declare const sharpDashboard: string;
export declare const sharpDashboardCustomize: string;
export declare const sharpDataArray: string;
export declare const sharpDataExploration: string;
export declare const sharpDataObject: string;
export declare const sharpDataSaverOff: string;
export declare const sharpDataSaverOn: string;
export declare const sharpDataUsage: string;
export declare const sharpDateRange: string;
export declare const sharpDeck: string;
export declare const sharpDehaze: string;
export declare const sharpDelete: string;
export declare const sharpDeleteForever: string;
export declare const sharpDeleteOutline: string;
export declare const sharpDeleteSweep: string;
export declare const sharpDeliveryDining: string;
export declare const sharpDepartureBoard: string;
export declare const sharpDescription: string;
export declare const sharpDesignServices: string;
export declare const sharpDesktopAccessDisabled: string;
export declare const sharpDesktopMac: string;
export declare const sharpDesktopWindows: string;
export declare const sharpDetails: string;
export declare const sharpDeveloperBoard: string;
export declare const sharpDeveloperBoardOff: string;
export declare const sharpDeveloperMode: string;
export declare const sharpDeviceHub: string;
export declare const sharpDevices: string;
export declare const sharpDevicesOther: string;
export declare const sharpDeviceThermostat: string;
export declare const sharpDeviceUnknown: string;
export declare const sharpDialerSip: string;
export declare const sharpDialpad: string;
export declare const sharpDiamond: string;
export declare const sharpDining: string;
export declare const sharpDinnerDining: string;
export declare const sharpDirections: string;
export declare const sharpDirectionsBike: string;
export declare const sharpDirectionsBoat: string;
export declare const sharpDirectionsBoatFilled: string;
export declare const sharpDirectionsBus: string;
export declare const sharpDirectionsBusFilled: string;
export declare const sharpDirectionsCar: string;
export declare const sharpDirectionsCarFilled: string;
export declare const sharpDirectionsOff: string;
export declare const sharpDirectionsRailway: string;
export declare const sharpDirectionsRailwayFilled: string;
export declare const sharpDirectionsRun: string;
export declare const sharpDirectionsSubway: string;
export declare const sharpDirectionsSubwayFilled: string;
export declare const sharpDirectionsTransit: string;
export declare const sharpDirectionsTransitFilled: string;
export declare const sharpDirectionsWalk: string;
export declare const sharpDirtyLens: string;
export declare const sharpDisabledByDefault: string;
export declare const sharpDisabledVisible: string;
export declare const sharpDiscFull: string;
export declare const sharpDns: string;
export declare const sharpDock: string;
export declare const sharpDocumentScanner: string;
export declare const sharpDoDisturb: string;
export declare const sharpDoDisturbAlt: string;
export declare const sharpDoDisturbOff: string;
export declare const sharpDoDisturbOn: string;
export declare const sharpDomain: string;
export declare const sharpDomainDisabled: string;
export declare const sharpDomainVerification: string;
export declare const sharpDone: string;
export declare const sharpDoneAll: string;
export declare const sharpDoneOutline: string;
export declare const sharpDoNotDisturb: string;
export declare const sharpDoNotDisturbAlt: string;
export declare const sharpDoNotDisturbOff: string;
export declare const sharpDoNotDisturbOn: string;
export declare const sharpDoNotDisturbOnTotalSilence: string;
export declare const sharpDoNotStep: string;
export declare const sharpDoNotTouch: string;
export declare const sharpDonutLarge: string;
export declare const sharpDonutSmall: string;
export declare const sharpDoorBack: string;
export declare const sharpDoorbell: string;
export declare const sharpDoorFront: string;
export declare const sharpDoorSliding: string;
export declare const sharpDoubleArrow: string;
export declare const sharpDownhillSkiing: string;
export declare const sharpDownload: string;
export declare const sharpDownloadDone: string;
export declare const sharpDownloadForOffline: string;
export declare const sharpDownloading: string;
export declare const sharpDrafts: string;
export declare const sharpDragHandle: string;
export declare const sharpDragIndicator: string;
export declare const sharpDraw: string;
export declare const sharpDriveEta: string;
export declare const sharpDriveFileMove: string;
export declare const sharpDriveFileMoveRtl: string;
export declare const sharpDriveFileRenameOutline: string;
export declare const sharpDriveFolderUpload: string;
export declare const sharpDry: string;
export declare const sharpDryCleaning: string;
export declare const sharpDuo: string;
export declare const sharpDvr: string;
export declare const sharpDynamicFeed: string;
export declare const sharpDynamicForm: string;
export declare const sharpEarbuds: string;
export declare const sharpEarbudsBattery: string;
export declare const sharpEast: string;
export declare const sharpEdgesensorHigh: string;
export declare const sharpEdgesensorLow: string;
export declare const sharpEdit: string;
export declare const sharpEditAttributes: string;
export declare const sharpEditCalendar: string;
export declare const sharpEditLocation: string;
export declare const sharpEditLocationAlt: string;
export declare const sharpEditNote: string;
export declare const sharpEditNotifications: string;
export declare const sharpEditOff: string;
export declare const sharpEditRoad: string;
export declare const sharpEgg: string;
export declare const sharpEggAlt: string;
export declare const sharpEject: string;
export declare const sharpElderly: string;
export declare const sharpElectricalServices: string;
export declare const sharpElectricBike: string;
export declare const sharpElectricCar: string;
export declare const sharpElectricMoped: string;
export declare const sharpElectricRickshaw: string;
export declare const sharpElectricScooter: string;
export declare const sharpElevator: string;
export declare const sharpEmail: string;
export declare const sharpEmergency: string;
export declare const sharpEMobiledata: string;
export declare const sharpEmojiEmotions: string;
export declare const sharpEmojiEvents: string;
export declare const sharpEmojiFoodBeverage: string;
export declare const sharpEmojiNature: string;
export declare const sharpEmojiObjects: string;
export declare const sharpEmojiPeople: string;
export declare const sharpEmojiSymbols: string;
export declare const sharpEmojiTransportation: string;
export declare const sharpEngineering: string;
export declare const sharpEnhancedEncryption: string;
export declare const sharpEqualizer: string;
export declare const sharpError: string;
export declare const sharpErrorOutline: string;
export declare const sharpEscalator: string;
export declare const sharpEscalatorWarning: string;
export declare const sharpEuro: string;
export declare const sharpEuroSymbol: string;
export declare const sharpEvent: string;
export declare const sharpEventAvailable: string;
export declare const sharpEventBusy: string;
export declare const sharpEventNote: string;
export declare const sharpEventSeat: string;
export declare const sharpEvStation: string;
export declare const sharpExitToApp: string;
export declare const sharpExpand: string;
export declare const sharpExpandCircleDown: string;
export declare const sharpExpandLess: string;
export declare const sharpExpandMore: string;
export declare const sharpExplicit: string;
export declare const sharpExplore: string;
export declare const sharpExploreOff: string;
export declare const sharpExposure: string;
export declare const sharpExposureNeg1: string;
export declare const sharpExposureNeg2: string;
export declare const sharpExposurePlus1: string;
export declare const sharpExposurePlus2: string;
export declare const sharpExposureZero: string;
export declare const sharpExtension: string;
export declare const sharpExtensionOff: string;
export declare const sharpFace: string;
export declare const sharpFaceRetouchingNatural: string;
export declare const sharpFaceRetouchingOff: string;
export declare const sharpFactCheck: string;
export declare const sharpFamilyRestroom: string;
export declare const sharpFastfood: string;
export declare const sharpFastForward: string;
export declare const sharpFastRewind: string;
export declare const sharpFavorite: string;
export declare const sharpFavoriteBorder: string;
export declare const sharpFax: string;
export declare const sharpFeaturedPlayList: string;
export declare const sharpFeaturedVideo: string;
export declare const sharpFeed: string;
export declare const sharpFeedback: string;
export declare const sharpFemale: string;
export declare const sharpFence: string;
export declare const sharpFestival: string;
export declare const sharpFiberDvr: string;
export declare const sharpFiberManualRecord: string;
export declare const sharpFiberNew: string;
export declare const sharpFiberPin: string;
export declare const sharpFiberSmartRecord: string;
export declare const sharpFileCopy: string;
export declare const sharpFileDownload: string;
export declare const sharpFileDownloadDone: string;
export declare const sharpFileDownloadOff: string;
export declare const sharpFileOpen: string;
export declare const sharpFilePresent: string;
export declare const sharpFileUpload: string;
export declare const sharpFilter: string;
export declare const sharpFilter1: string;
export declare const sharpFilter2: string;
export declare const sharpFilter3: string;
export declare const sharpFilter4: string;
export declare const sharpFilter5: string;
export declare const sharpFilter6: string;
export declare const sharpFilter7: string;
export declare const sharpFilter8: string;
export declare const sharpFilter9: string;
export declare const sharpFilter9Plus: string;
export declare const sharpFilterAlt: string;
export declare const sharpFilterAltOff: string;
export declare const sharpFilterBAndW: string;
export declare const sharpFilterCenterFocus: string;
export declare const sharpFilterDrama: string;
export declare const sharpFilterFrames: string;
export declare const sharpFilterHdr: string;
export declare const sharpFilterList: string;
export declare const sharpFilterListOff: string;
export declare const sharpFilterNone: string;
export declare const sharpFilterTiltShift: string;
export declare const sharpFilterVintage: string;
export declare const sharpFindInPage: string;
export declare const sharpFindReplace: string;
export declare const sharpFingerprint: string;
export declare const sharpFireExtinguisher: string;
export declare const sharpFireplace: string;
export declare const sharpFirstPage: string;
export declare const sharpFitbit: string;
export declare const sharpFitnessCenter: string;
export declare const sharpFitScreen: string;
export declare const sharpFlag: string;
export declare const sharpFlagCircle: string;
export declare const sharpFlaky: string;
export declare const sharpFlare: string;
export declare const sharpFlashAuto: string;
export declare const sharpFlashlightOff: string;
export declare const sharpFlashlightOn: string;
export declare const sharpFlashOff: string;
export declare const sharpFlashOn: string;
export declare const sharpFlatware: string;
export declare const sharpFlight: string;
export declare const sharpFlightClass: string;
export declare const sharpFlightLand: string;
export declare const sharpFlightTakeoff: string;
export declare const sharpFlip: string;
export declare const sharpFlipCameraAndroid: string;
export declare const sharpFlipCameraIos: string;
export declare const sharpFlipToBack: string;
export declare const sharpFlipToFront: string;
export declare const sharpFlourescent: string;
export declare const sharpFlutterDash: string;
export declare const sharpFmdBad: string;
export declare const sharpFmdGood: string;
export declare const sharpFolder: string;
export declare const sharpFolderDelete: string;
export declare const sharpFolderOpen: string;
export declare const sharpFolderShared: string;
export declare const sharpFolderSpecial: string;
export declare const sharpFolderZip: string;
export declare const sharpFollowTheSigns: string;
export declare const sharpFontDownload: string;
export declare const sharpFontDownloadOff: string;
export declare const sharpFoodBank: string;
export declare const sharpFormatAlignCenter: string;
export declare const sharpFormatAlignJustify: string;
export declare const sharpFormatAlignLeft: string;
export declare const sharpFormatAlignRight: string;
export declare const sharpFormatBold: string;
export declare const sharpFormatClear: string;
export declare const sharpFormatColorFill: string;
export declare const sharpFormatColorReset: string;
export declare const sharpFormatColorText: string;
export declare const sharpFormatIndentDecrease: string;
export declare const sharpFormatIndentIncrease: string;
export declare const sharpFormatItalic: string;
export declare const sharpFormatLineSpacing: string;
export declare const sharpFormatListBulleted: string;
export declare const sharpFormatListNumbered: string;
export declare const sharpFormatListNumberedRtl: string;
export declare const sharpFormatPaint: string;
export declare const sharpFormatQuote: string;
export declare const sharpFormatShapes: string;
export declare const sharpFormatSize: string;
export declare const sharpFormatStrikethrough: string;
export declare const sharpFormatTextdirectionLToR: string;
export declare const sharpFormatTextdirectionRToL: string;
export declare const sharpFormatUnderlined: string;
export declare const sharpForum: string;
export declare const sharpForward: string;
export declare const sharpForward10: string;
export declare const sharpForward30: string;
export declare const sharpForward5: string;
export declare const sharpForwardToInbox: string;
export declare const sharpFoundation: string;
export declare const sharpFreeBreakfast: string;
export declare const sharpFreeCancellation: string;
export declare const sharpFrontHand: string;
export declare const sharpFullscreen: string;
export declare const sharpFullscreenExit: string;
export declare const sharpFunctions: string;
export declare const sharpGamepad: string;
export declare const sharpGames: string;
export declare const sharpGarage: string;
export declare const sharpGavel: string;
export declare const sharpGeneratingTokens: string;
export declare const sharpGesture: string;
export declare const sharpGetApp: string;
export declare const sharpGif: string;
export declare const sharpGifBox: string;
export declare const sharpGite: string;
export declare const sharpGMobiledata: string;
export declare const sharpGolfCourse: string;
export declare const sharpGppBad: string;
export declare const sharpGppGood: string;
export declare const sharpGppMaybe: string;
export declare const sharpGpsFixed: string;
export declare const sharpGpsNotFixed: string;
export declare const sharpGpsOff: string;
export declare const sharpGrade: string;
export declare const sharpGradient: string;
export declare const sharpGrading: string;
export declare const sharpGrain: string;
export declare const sharpGraphicEq: string;
export declare const sharpGrass: string;
export declare const sharpGrid3x3: string;
export declare const sharpGrid4x4: string;
export declare const sharpGridGoldenratio: string;
export declare const sharpGridOff: string;
export declare const sharpGridOn: string;
export declare const sharpGridView: string;
export declare const sharpGroup: string;
export declare const sharpGroupAdd: string;
export declare const sharpGroupOff: string;
export declare const sharpGroupRemove: string;
export declare const sharpGroups: string;
export declare const sharpGroupWork: string;
export declare const sharpGTranslate: string;
export declare const sharpHail: string;
export declare const sharpHandyman: string;
export declare const sharpHardware: string;
export declare const sharpHd: string;
export declare const sharpHdrAuto: string;
export declare const sharpHdrAutoSelect: string;
export declare const sharpHdrEnhancedSelect: string;
export declare const sharpHdrOff: string;
export declare const sharpHdrOffSelect: string;
export declare const sharpHdrOn: string;
export declare const sharpHdrOnSelect: string;
export declare const sharpHdrPlus: string;
export declare const sharpHdrStrong: string;
export declare const sharpHdrWeak: string;
export declare const sharpHeadphones: string;
export declare const sharpHeadphonesBattery: string;
export declare const sharpHeadset: string;
export declare const sharpHeadsetMic: string;
export declare const sharpHeadsetOff: string;
export declare const sharpHealing: string;
export declare const sharpHealthAndSafety: string;
export declare const sharpHearing: string;
export declare const sharpHearingDisabled: string;
export declare const sharpHeartBroken: string;
export declare const sharpHeight: string;
export declare const sharpHelp: string;
export declare const sharpHelpCenter: string;
export declare const sharpHelpOutline: string;
export declare const sharpHevc: string;
export declare const sharpHexagon: string;
export declare const sharpHideImage: string;
export declare const sharpHideSource: string;
export declare const sharpHighlight: string;
export declare const sharpHighlightAlt: string;
export declare const sharpHighlightOff: string;
export declare const sharpHighQuality: string;
export declare const sharpHiking: string;
export declare const sharpHistory: string;
export declare const sharpHistoryEdu: string;
export declare const sharpHistoryToggleOff: string;
export declare const sharpHMobiledata: string;
export declare const sharpHolidayVillage: string;
export declare const sharpHome: string;
export declare const sharpHomeMax: string;
export declare const sharpHomeMini: string;
export declare const sharpHomeRepairService: string;
export declare const sharpHomeWork: string;
export declare const sharpHorizontalDistribute: string;
export declare const sharpHorizontalRule: string;
export declare const sharpHorizontalSplit: string;
export declare const sharpHotel: string;
export declare const sharpHotelClass: string;
export declare const sharpHotTub: string;
export declare const sharpHourglassBottom: string;
export declare const sharpHourglassDisabled: string;
export declare const sharpHourglassEmpty: string;
export declare const sharpHourglassFull: string;
export declare const sharpHourglassTop: string;
export declare const sharpHouse: string;
export declare const sharpHouseboat: string;
export declare const sharpHouseSiding: string;
export declare const sharpHowToReg: string;
export declare const sharpHowToVote: string;
export declare const sharpHPlusMobiledata: string;
export declare const sharpHttp: string;
export declare const sharpHttps: string;
export declare const sharpHub: string;
export declare const sharpHvac: string;
export declare const sharpIcecream: string;
export declare const sharpIceSkating: string;
export declare const sharpImage: string;
export declare const sharpImageAspectRatio: string;
export declare const sharpImageNotSupported: string;
export declare const sharpImageSearch: string;
export declare const sharpImagesearchRoller: string;
export declare const sharpImportantDevices: string;
export declare const sharpImportContacts: string;
export declare const sharpImportExport: string;
export declare const sharpInbox: string;
export declare const sharpIncompleteCircle: string;
export declare const sharpIndeterminateCheckBox: string;
export declare const sharpInfo: string;
export declare const sharpInput: string;
export declare const sharpInsertChart: string;
export declare const sharpInsertChartOutlined: string;
export declare const sharpInsertComment: string;
export declare const sharpInsertDriveFile: string;
export declare const sharpInsertEmoticon: string;
export declare const sharpInsertInvitation: string;
export declare const sharpInsertLink: string;
export declare const sharpInsertPageBreak: string;
export declare const sharpInsertPhoto: string;
export declare const sharpInsights: string;
export declare const sharpIntegrationInstructions: string;
export declare const sharpInterests: string;
export declare const sharpInventory: string;
export declare const sharpInventory2: string;
export declare const sharpInvertColors: string;
export declare const sharpInvertColorsOff: string;
export declare const sharpIosShare: string;
export declare const sharpIron: string;
export declare const sharpIso: string;
export declare const sharpJoinFull: string;
export declare const sharpJoinInner: string;
export declare const sharpJoinLeft: string;
export declare const sharpJoinRight: string;
export declare const sharpKayaking: string;
export declare const sharpKebabDining: string;
export declare const sharpKey: string;
export declare const sharpKeyboard: string;
export declare const sharpKeyboardAlt: string;
export declare const sharpKeyboardArrowDown: string;
export declare const sharpKeyboardArrowLeft: string;
export declare const sharpKeyboardArrowRight: string;
export declare const sharpKeyboardArrowUp: string;
export declare const sharpKeyboardBackspace: string;
export declare const sharpKeyboardCapslock: string;
export declare const sharpKeyboardCommandKey: string;
export declare const sharpKeyboardControlKey: string;
export declare const sharpKeyboardDoubleArrowDown: string;
export declare const sharpKeyboardDoubleArrowLeft: string;
export declare const sharpKeyboardDoubleArrowRight: string;
export declare const sharpKeyboardDoubleArrowUp: string;
export declare const sharpKeyboardHide: string;
export declare const sharpKeyboardOptionKey: string;
export declare const sharpKeyboardReturn: string;
export declare const sharpKeyboardTab: string;
export declare const sharpKeyboardVoice: string;
export declare const sharpKingBed: string;
export declare const sharpKitchen: string;
export declare const sharpKitesurfing: string;
export declare const sharpLabel: string;
export declare const sharpLabelImportant: string;
export declare const sharpLabelOff: string;
export declare const sharpLan: string;
export declare const sharpLandscape: string;
export declare const sharpLanguage: string;
export declare const sharpLaptop: string;
export declare const sharpLaptopChromebook: string;
export declare const sharpLaptopMac: string;
export declare const sharpLaptopWindows: string;
export declare const sharpLastPage: string;
export declare const sharpLaunch: string;
export declare const sharpLayers: string;
export declare const sharpLayersClear: string;
export declare const sharpLeaderboard: string;
export declare const sharpLeakAdd: string;
export declare const sharpLeakRemove: string;
export declare const sharpLegendToggle: string;
export declare const sharpLens: string;
export declare const sharpLensBlur: string;
export declare const sharpLibraryAdd: string;
export declare const sharpLibraryAddCheck: string;
export declare const sharpLibraryBooks: string;
export declare const sharpLibraryMusic: string;
export declare const sharpLight: string;
export declare const sharpLightbulb: string;
export declare const sharpLightMode: string;
export declare const sharpLinearScale: string;
export declare const sharpLineStyle: string;
export declare const sharpLineWeight: string;
export declare const sharpLink: string;
export declare const sharpLinkedCamera: string;
export declare const sharpLinkOff: string;
export declare const sharpLiquor: string;
export declare const sharpList: string;
export declare const sharpListAlt: string;
export declare const sharpLiveHelp: string;
export declare const sharpLiveTv: string;
export declare const sharpLiving: string;
export declare const sharpLocalActivity: string;
export declare const sharpLocalAirport: string;
export declare const sharpLocalAtm: string;
export declare const sharpLocalBar: string;
export declare const sharpLocalCafe: string;
export declare const sharpLocalCarWash: string;
export declare const sharpLocalConvenienceStore: string;
export declare const sharpLocalDining: string;
export declare const sharpLocalDrink: string;
export declare const sharpLocalFireDepartment: string;
export declare const sharpLocalFlorist: string;
export declare const sharpLocalGasStation: string;
export declare const sharpLocalGroceryStore: string;
export declare const sharpLocalHospital: string;
export declare const sharpLocalHotel: string;
export declare const sharpLocalLaundryService: string;
export declare const sharpLocalLibrary: string;
export declare const sharpLocalMall: string;
export declare const sharpLocalMovies: string;
export declare const sharpLocalOffer: string;
export declare const sharpLocalParking: string;
export declare const sharpLocalPharmacy: string;
export declare const sharpLocalPhone: string;
export declare const sharpLocalPizza: string;
export declare const sharpLocalPlay: string;
export declare const sharpLocalPolice: string;
export declare const sharpLocalPostOffice: string;
export declare const sharpLocalPrintshop: string;
export declare const sharpLocalSee: string;
export declare const sharpLocalShipping: string;
export declare const sharpLocalTaxi: string;
export declare const sharpLocationCity: string;
export declare const sharpLocationDisabled: string;
export declare const sharpLocationOff: string;
export declare const sharpLocationOn: string;
export declare const sharpLocationSearching: string;
export declare const sharpLock: string;
export declare const sharpLockClock: string;
export declare const sharpLockOpen: string;
export declare const sharpLockReset: string;
export declare const sharpLogin: string;
export declare const sharpLogoDev: string;
export declare const sharpLogout: string;
export declare const sharpLooks: string;
export declare const sharpLooks3: string;
export declare const sharpLooks4: string;
export declare const sharpLooks5: string;
export declare const sharpLooks6: string;
export declare const sharpLooksOne: string;
export declare const sharpLooksTwo: string;
export declare const sharpLoop: string;
export declare const sharpLoupe: string;
export declare const sharpLowPriority: string;
export declare const sharpLoyalty: string;
export declare const sharpLteMobiledata: string;
export declare const sharpLtePlusMobiledata: string;
export declare const sharpLuggage: string;
export declare const sharpLunchDining: string;
export declare const sharpMail: string;
export declare const sharpMailOutline: string;
export declare const sharpMale: string;
export declare const sharpMan: string;
export declare const sharpManageAccounts: string;
export declare const sharpManageSearch: string;
export declare const sharpMap: string;
export declare const sharpMapsHomeWork: string;
export declare const sharpMapsUgc: string;
export declare const sharpMargin: string;
export declare const sharpMarkAsUnread: string;
export declare const sharpMarkChatRead: string;
export declare const sharpMarkChatUnread: string;
export declare const sharpMarkEmailRead: string;
export declare const sharpMarkEmailUnread: string;
export declare const sharpMarkunread: string;
export declare const sharpMarkunreadMailbox: string;
export declare const sharpMasks: string;
export declare const sharpMaximize: string;
export declare const sharpMediaBluetoothOff: string;
export declare const sharpMediaBluetoothOn: string;
export declare const sharpMediation: string;
export declare const sharpMedicalServices: string;
export declare const sharpMedication: string;
export declare const sharpMeetingRoom: string;
export declare const sharpMemory: string;
export declare const sharpMenu: string;
export declare const sharpMenuBook: string;
export declare const sharpMenuOpen: string;
export declare const sharpMergeType: string;
export declare const sharpMessage: string;
export declare const sharpMic: string;
export declare const sharpMicExternalOff: string;
export declare const sharpMicExternalOn: string;
export declare const sharpMicNone: string;
export declare const sharpMicOff: string;
export declare const sharpMicrowave: string;
export declare const sharpMilitaryTech: string;
export declare const sharpMinimize: string;
export declare const sharpMiscellaneousServices: string;
export declare const sharpMissedVideoCall: string;
export declare const sharpMms: string;
export declare const sharpMobiledataOff: string;
export declare const sharpMobileFriendly: string;
export declare const sharpMobileOff: string;
export declare const sharpMobileScreenShare: string;
export declare const sharpMode: string;
export declare const sharpModeComment: string;
export declare const sharpModeEdit: string;
export declare const sharpModeEditOutline: string;
export declare const sharpModelTraining: string;
export declare const sharpModeNight: string;
export declare const sharpModeOfTravel: string;
export declare const sharpModeStandby: string;
export declare const sharpMonetizationOn: string;
export declare const sharpMoney: string;
export declare const sharpMoneyOff: string;
export declare const sharpMoneyOffCsred: string;
export declare const sharpMonitor: string;
export declare const sharpMonitorWeight: string;
export declare const sharpMonochromePhotos: string;
export declare const sharpMood: string;
export declare const sharpMoodBad: string;
export declare const sharpMoped: string;
export declare const sharpMore: string;
export declare const sharpMoreHoriz: string;
export declare const sharpMoreTime: string;
export declare const sharpMoreVert: string;
export declare const sharpMotionPhotosAuto: string;
export declare const sharpMotionPhotosOff: string;
export declare const sharpMotionPhotosOn: string;
export declare const sharpMotionPhotosPause: string;
export declare const sharpMotionPhotosPaused: string;
export declare const sharpMouse: string;
export declare const sharpMoveToInbox: string;
export declare const sharpMovie: string;
export declare const sharpMovieCreation: string;
export declare const sharpMovieFilter: string;
export declare const sharpMoving: string;
export declare const sharpMp: string;
export declare const sharpMultilineChart: string;
export declare const sharpMultipleStop: string;
export declare const sharpMuseum: string;
export declare const sharpMusicNote: string;
export declare const sharpMusicOff: string;
export declare const sharpMusicVideo: string;
export declare const sharpMyLocation: string;
export declare const sharpNat: string;
export declare const sharpNature: string;
export declare const sharpNaturePeople: string;
export declare const sharpNavigateBefore: string;
export declare const sharpNavigateNext: string;
export declare const sharpNavigation: string;
export declare const sharpNearbyError: string;
export declare const sharpNearbyOff: string;
export declare const sharpNearMe: string;
export declare const sharpNearMeDisabled: string;
export declare const sharpNetworkCell: string;
export declare const sharpNetworkCheck: string;
export declare const sharpNetworkLocked: string;
export declare const sharpNetworkWifi: string;
export declare const sharpNewLabel: string;
export declare const sharpNewReleases: string;
export declare const sharpNextPlan: string;
export declare const sharpNextWeek: string;
export declare const sharpNfc: string;
export declare const sharpNightlife: string;
export declare const sharpNightlight: string;
export declare const sharpNightlightRound: string;
export declare const sharpNightShelter: string;
export declare const sharpNightsStay: string;
export declare const sharpNoAccounts: string;
export declare const sharpNoBackpack: string;
export declare const sharpNoCell: string;
export declare const sharpNoDrinks: string;
export declare const sharpNoEncryption: string;
export declare const sharpNoEncryptionGmailerrorred: string;
export declare const sharpNoFlash: string;
export declare const sharpNoFood: string;
export declare const sharpNoLuggage: string;
export declare const sharpNoMeals: string;
export declare const sharpNoMeetingRoom: string;
export declare const sharpNoPhotography: string;
export declare const sharpNordicWalking: string;
export declare const sharpNorth: string;
export declare const sharpNorthEast: string;
export declare const sharpNorthWest: string;
export declare const sharpNoSim: string;
export declare const sharpNoStroller: string;
export declare const sharpNotAccessible: string;
export declare const sharpNote: string;
export declare const sharpNoteAdd: string;
export declare const sharpNoteAlt: string;
export declare const sharpNotes: string;
export declare const sharpNotificationAdd: string;
export declare const sharpNotificationImportant: string;
export declare const sharpNotifications: string;
export declare const sharpNotificationsActive: string;
export declare const sharpNotificationsNone: string;
export declare const sharpNotificationsOff: string;
export declare const sharpNotificationsPaused: string;
export declare const sharpNotInterested: string;
export declare const sharpNotListedLocation: string;
export declare const sharpNoTransfer: string;
export declare const sharpNotStarted: string;
export declare const sharpNumbers: string;
export declare const sharpOfflineBolt: string;
export declare const sharpOfflinePin: string;
export declare const sharpOfflineShare: string;
export declare const sharpOndemandVideo: string;
export declare const sharpOnlinePrediction: string;
export declare const sharpOpacity: string;
export declare const sharpOpenInBrowser: string;
export declare const sharpOpenInFull: string;
export declare const sharpOpenInNew: string;
export declare const sharpOpenInNewOff: string;
export declare const sharpOpenWith: string;
export declare const sharpOtherHouses: string;
export declare const sharpOutbound: string;
export declare const sharpOutbox: string;
export declare const sharpOutdoorGrill: string;
export declare const sharpOutlet: string;
export declare const sharpOutlinedFlag: string;
export declare const sharpPadding: string;
export declare const sharpPages: string;
export declare const sharpPageview: string;
export declare const sharpPaid: string;
export declare const sharpPalette: string;
export declare const sharpPanorama: string;
export declare const sharpPanoramaFishEye: string;
export declare const sharpPanoramaHorizontal: string;
export declare const sharpPanoramaHorizontalSelect: string;
export declare const sharpPanoramaPhotosphere: string;
export declare const sharpPanoramaPhotosphereSelect: string;
export declare const sharpPanoramaVertical: string;
export declare const sharpPanoramaVerticalSelect: string;
export declare const sharpPanoramaWideAngle: string;
export declare const sharpPanoramaWideAngleSelect: string;
export declare const sharpPanTool: string;
export declare const sharpParagliding: string;
export declare const sharpPark: string;
export declare const sharpPartyMode: string;
export declare const sharpPassword: string;
export declare const sharpPattern: string;
export declare const sharpPause: string;
export declare const sharpPauseCircle: string;
export declare const sharpPauseCircleFilled: string;
export declare const sharpPauseCircleOutline: string;
export declare const sharpPausePresentation: string;
export declare const sharpPayment: string;
export declare const sharpPayments: string;
export declare const sharpPedalBike: string;
export declare const sharpPending: string;
export declare const sharpPendingActions: string;
export declare const sharpPentagon: string;
export declare const sharpPeople: string;
export declare const sharpPeopleAlt: string;
export declare const sharpPeopleOutline: string;
export declare const sharpPercent: string;
export declare const sharpPermCameraMic: string;
export declare const sharpPermContactCalendar: string;
export declare const sharpPermDataSetting: string;
export declare const sharpPermDeviceInformation: string;
export declare const sharpPermIdentity: string;
export declare const sharpPermMedia: string;
export declare const sharpPermPhoneMsg: string;
export declare const sharpPermScanWifi: string;
export declare const sharpPerson: string;
export declare const sharpPersonAdd: string;
export declare const sharpPersonAddAlt: string;
export declare const sharpPersonAddAlt1: string;
export declare const sharpPersonAddDisabled: string;
export declare const sharpPersonalInjury: string;
export declare const sharpPersonalVideo: string;
export declare const sharpPersonOff: string;
export declare const sharpPersonOutline: string;
export declare const sharpPersonPin: string;
export declare const sharpPersonPinCircle: string;
export declare const sharpPersonRemove: string;
export declare const sharpPersonRemoveAlt1: string;
export declare const sharpPersonSearch: string;
export declare const sharpPestControl: string;
export declare const sharpPestControlRodent: string;
export declare const sharpPets: string;
export declare const sharpPhishing: string;
export declare const sharpPhone: string;
export declare const sharpPhoneAndroid: string;
export declare const sharpPhoneBluetoothSpeaker: string;
export declare const sharpPhoneCallback: string;
export declare const sharpPhoneDisabled: string;
export declare const sharpPhoneEnabled: string;
export declare const sharpPhoneForwarded: string;
export declare const sharpPhoneInTalk: string;
export declare const sharpPhoneIphone: string;
export declare const sharpPhonelink: string;
export declare const sharpPhonelinkErase: string;
export declare const sharpPhonelinkLock: string;
export declare const sharpPhonelinkOff: string;
export declare const sharpPhonelinkRing: string;
export declare const sharpPhonelinkSetup: string;
export declare const sharpPhoneLocked: string;
export declare const sharpPhoneMissed: string;
export declare const sharpPhonePaused: string;
export declare const sharpPhoto: string;
export declare const sharpPhotoAlbum: string;
export declare const sharpPhotoCamera: string;
export declare const sharpPhotoCameraBack: string;
export declare const sharpPhotoCameraFront: string;
export declare const sharpPhotoFilter: string;
export declare const sharpPhotoLibrary: string;
export declare const sharpPhotoSizeSelectActual: string;
export declare const sharpPhotoSizeSelectLarge: string;
export declare const sharpPhotoSizeSelectSmall: string;
export declare const sharpPiano: string;
export declare const sharpPianoOff: string;
export declare const sharpPictureAsPdf: string;
export declare const sharpPictureInPicture: string;
export declare const sharpPictureInPictureAlt: string;
export declare const sharpPieChart: string;
export declare const sharpPieChartOutline: string;
export declare const sharpPin: string;
export declare const sharpPinch: string;
export declare const sharpPinDrop: string;
export declare const sharpPinEnd: string;
export declare const sharpPinInvoke: string;
export declare const sharpPivotTableChart: string;
export declare const sharpPlace: string;
export declare const sharpPlagiarism: string;
export declare const sharpPlayArrow: string;
export declare const sharpPlayCircle: string;
export declare const sharpPlayCircleFilled: string;
export declare const sharpPlayCircleOutline: string;
export declare const sharpPlayDisabled: string;
export declare const sharpPlayForWork: string;
export declare const sharpPlayLesson: string;
export declare const sharpPlaylistAdd: string;
export declare const sharpPlaylistAddCheck: string;
export declare const sharpPlaylistPlay: string;
export declare const sharpPlumbing: string;
export declare const sharpPlusOne: string;
export declare const sharpPodcasts: string;
export declare const sharpPointOfSale: string;
export declare const sharpPolicy: string;
export declare const sharpPoll: string;
export declare const sharpPolymer: string;
export declare const sharpPool: string;
export declare const sharpPortableWifiOff: string;
export declare const sharpPortrait: string;
export declare const sharpPostAdd: string;
export declare const sharpPower: string;
export declare const sharpPowerInput: string;
export declare const sharpPowerOff: string;
export declare const sharpPowerSettingsNew: string;
export declare const sharpPrecisionManufacturing: string;
export declare const sharpPregnantWoman: string;
export declare const sharpPresentToAll: string;
export declare const sharpPreview: string;
export declare const sharpPriceChange: string;
export declare const sharpPriceCheck: string;
export declare const sharpPrint: string;
export declare const sharpPrintDisabled: string;
export declare const sharpPriorityHigh: string;
export declare const sharpPrivacyTip: string;
export declare const sharpPrivateConnectivity: string;
export declare const sharpProductionQuantityLimits: string;
export declare const sharpPsychology: string;
export declare const sharpPublic: string;
export declare const sharpPublicOff: string;
export declare const sharpPublish: string;
export declare const sharpPublishedWithChanges: string;
export declare const sharpPushPin: string;
export declare const sharpQrCode: string;
export declare const sharpQrCode2: string;
export declare const sharpQrCodeScanner: string;
export declare const sharpQueryBuilder: string;
export declare const sharpQueryStats: string;
export declare const sharpQuestionAnswer: string;
export declare const sharpQueue: string;
export declare const sharpQueueMusic: string;
export declare const sharpQueuePlayNext: string;
export declare const sharpQuickreply: string;
export declare const sharpQuiz: string;
export declare const sharpRadar: string;
export declare const sharpRadio: string;
export declare const sharpRadioButtonChecked: string;
export declare const sharpRadioButtonUnchecked: string;
export declare const sharpRailwayAlert: string;
export declare const sharpRamenDining: string;
export declare const sharpRateReview: string;
export declare const sharpRawOff: string;
export declare const sharpRawOn: string;
export declare const sharpReadMore: string;
export declare const sharpRealEstateAgent: string;
export declare const sharpReceipt: string;
export declare const sharpReceiptLong: string;
export declare const sharpRecentActors: string;
export declare const sharpRecommend: string;
export declare const sharpRecordVoiceOver: string;
export declare const sharpRectangle: string;
export declare const sharpRecycling: string;
export declare const sharpRedeem: string;
export declare const sharpRedo: string;
export declare const sharpReduceCapacity: string;
export declare const sharpRefresh: string;
export declare const sharpRememberMe: string;
export declare const sharpRemove: string;
export declare const sharpRemoveCircle: string;
export declare const sharpRemoveCircleOutline: string;
export declare const sharpRemoveDone: string;
export declare const sharpRemoveFromQueue: string;
export declare const sharpRemoveModerator: string;
export declare const sharpRemoveRedEye: string;
export declare const sharpRemoveShoppingCart: string;
export declare const sharpReorder: string;
export declare const sharpRepeat: string;
export declare const sharpRepeatOn: string;
export declare const sharpRepeatOne: string;
export declare const sharpRepeatOneOn: string;
export declare const sharpReplay: string;
export declare const sharpReplay10: string;
export declare const sharpReplay30: string;
export declare const sharpReplay5: string;
export declare const sharpReplayCircleFilled: string;
export declare const sharpReply: string;
export declare const sharpReplyAll: string;
export declare const sharpReport: string;
export declare const sharpReportGmailerrorred: string;
export declare const sharpReportOff: string;
export declare const sharpReportProblem: string;
export declare const sharpRequestPage: string;
export declare const sharpRequestQuote: string;
export declare const sharpResetTv: string;
export declare const sharpRestartAlt: string;
export declare const sharpRestaurant: string;
export declare const sharpRestaurantMenu: string;
export declare const sharpRestore: string;
export declare const sharpRestoreFromTrash: string;
export declare const sharpRestorePage: string;
export declare const sharpReviews: string;
export declare const sharpRiceBowl: string;
export declare const sharpRingVolume: string;
export declare const sharpRMobiledata: string;
export declare const sharpRoofing: string;
export declare const sharpRoom: string;
export declare const sharpRoomPreferences: string;
export declare const sharpRoomService: string;
export declare const sharpRotate90DegreesCcw: string;
export declare const sharpRotateLeft: string;
export declare const sharpRotateRight: string;
export declare const sharpRoundedCorner: string;
export declare const sharpRoute: string;
export declare const sharpRouter: string;
export declare const sharpRowing: string;
export declare const sharpRssFeed: string;
export declare const sharpRsvp: string;
export declare const sharpRtt: string;
export declare const sharpRule: string;
export declare const sharpRuleFolder: string;
export declare const sharpRunCircle: string;
export declare const sharpRunningWithErrors: string;
export declare const sharpRvHookup: string;
export declare const sharpSafetyDivider: string;
export declare const sharpSailing: string;
export declare const sharpSanitizer: string;
export declare const sharpSatellite: string;
export declare const sharpSatelliteAlt: string;
export declare const sharpSave: string;
export declare const sharpSaveAlt: string;
export declare const sharpSavedSearch: string;
export declare const sharpSavings: string;
export declare const sharpScanner: string;
export declare const sharpScatterPlot: string;
export declare const sharpSchedule: string;
export declare const sharpScheduleSend: string;
export declare const sharpSchema: string;
export declare const sharpSchool: string;
export declare const sharpScience: string;
export declare const sharpScore: string;
export declare const sharpScreenLockLandscape: string;
export declare const sharpScreenLockPortrait: string;
export declare const sharpScreenLockRotation: string;
export declare const sharpScreenRotation: string;
export declare const sharpScreenSearchDesktop: string;
export declare const sharpScreenShare: string;
export declare const sharpScreenshot: string;
export declare const sharpSd: string;
export declare const sharpSdCard: string;
export declare const sharpSdCardAlert: string;
export declare const sharpSdStorage: string;
export declare const sharpSearch: string;
export declare const sharpSearchOff: string;
export declare const sharpSecurity: string;
export declare const sharpSecurityUpdate: string;
export declare const sharpSecurityUpdateGood: string;
export declare const sharpSecurityUpdateWarning: string;
export declare const sharpSegment: string;
export declare const sharpSelectAll: string;
export declare const sharpSelfImprovement: string;
export declare const sharpSell: string;
export declare const sharpSend: string;
export declare const sharpSendAndArchive: string;
export declare const sharpSendTimeExtension: string;
export declare const sharpSendToMobile: string;
export declare const sharpSensorDoor: string;
export declare const sharpSensors: string;
export declare const sharpSensorsOff: string;
export declare const sharpSensorWindow: string;
export declare const sharpSentimentDissatisfied: string;
export declare const sharpSentimentNeutral: string;
export declare const sharpSentimentSatisfied: string;
export declare const sharpSentimentSatisfiedAlt: string;
export declare const sharpSentimentVeryDissatisfied: string;
export declare const sharpSentimentVerySatisfied: string;
export declare const sharpSetMeal: string;
export declare const sharpSettings: string;
export declare const sharpSettingsAccessibility: string;
export declare const sharpSettingsApplications: string;
export declare const sharpSettingsBackupRestore: string;
export declare const sharpSettingsBluetooth: string;
export declare const sharpSettingsBrightness: string;
export declare const sharpSettingsCell: string;
export declare const sharpSettingsEthernet: string;
export declare const sharpSettingsInputAntenna: string;
export declare const sharpSettingsInputComponent: string;
export declare const sharpSettingsInputComposite: string;
export declare const sharpSettingsInputHdmi: string;
export declare const sharpSettingsInputSvideo: string;
export declare const sharpSettingsOverscan: string;
export declare const sharpSettingsPhone: string;
export declare const sharpSettingsPower: string;
export declare const sharpSettingsRemote: string;
export declare const sharpSettingsSuggest: string;
export declare const sharpSettingsSystemDaydream: string;
export declare const sharpSettingsVoice: string;
export declare const sharpShare: string;
export declare const sharpShareLocation: string;
export declare const sharpShield: string;
export declare const sharpShop: string;
export declare const sharpShop2: string;
export declare const sharpShoppingBag: string;
export declare const sharpShoppingBasket: string;
export declare const sharpShoppingCart: string;
export declare const sharpShopTwo: string;
export declare const sharpShortcut: string;
export declare const sharpShortText: string;
export declare const sharpShowChart: string;
export declare const sharpShower: string;
export declare const sharpShuffle: string;
export declare const sharpShuffleOn: string;
export declare const sharpShutterSpeed: string;
export declare const sharpSick: string;
export declare const sharpSignalCellular0Bar: string;
export declare const sharpSignalCellular4Bar: string;
export declare const sharpSignalCellularAlt: string;
export declare const sharpSignalCellularConnectedNoInternet0Bar: string;
export declare const sharpSignalCellularConnectedNoInternet4Bar: string;
export declare const sharpSignalCellularNodata: string;
export declare const sharpSignalCellularNoSim: string;
export declare const sharpSignalCellularNull: string;
export declare const sharpSignalCellularOff: string;
export declare const sharpSignalWifi0Bar: string;
export declare const sharpSignalWifi4Bar: string;
export declare const sharpSignalWifi4BarLock: string;
export declare const sharpSignalWifiBad: string;
export declare const sharpSignalWifiConnectedNoInternet4: string;
export declare const sharpSignalWifiOff: string;
export declare const sharpSignalWifiStatusbar4Bar: string;
export declare const sharpSignalWifiStatusbarConnectedNoInternet4: string;
export declare const sharpSignalWifiStatusbarNull: string;
export declare const sharpSimCard: string;
export declare const sharpSimCardAlert: string;
export declare const sharpSimCardDownload: string;
export declare const sharpSingleBed: string;
export declare const sharpSip: string;
export declare const sharpSkateboarding: string;
export declare const sharpSkipNext: string;
export declare const sharpSkipPrevious: string;
export declare const sharpSledding: string;
export declare const sharpSlideshow: string;
export declare const sharpSlowMotionVideo: string;
export declare const sharpSmartButton: string;
export declare const sharpSmartDisplay: string;
export declare const sharpSmartphone: string;
export declare const sharpSmartScreen: string;
export declare const sharpSmartToy: string;
export declare const sharpSmokeFree: string;
export declare const sharpSmokingRooms: string;
export declare const sharpSms: string;
export declare const sharpSmsFailed: string;
export declare const sharpSnippetFolder: string;
export declare const sharpSnooze: string;
export declare const sharpSnowboarding: string;
export declare const sharpSnowmobile: string;
export declare const sharpSnowshoeing: string;
export declare const sharpSoap: string;
export declare const sharpSocialDistance: string;
export declare const sharpSort: string;
export declare const sharpSortByAlpha: string;
export declare const sharpSoupKitchen: string;
export declare const sharpSource: string;
export declare const sharpSouth: string;
export declare const sharpSouthEast: string;
export declare const sharpSouthWest: string;
export declare const sharpSpa: string;
export declare const sharpSpaceBar: string;
export declare const sharpSpaceDashboard: string;
export declare const sharpSpeaker: string;
export declare const sharpSpeakerGroup: string;
export declare const sharpSpeakerNotes: string;
export declare const sharpSpeakerNotesOff: string;
export declare const sharpSpeakerPhone: string;
export declare const sharpSpeed: string;
export declare const sharpSpellcheck: string;
export declare const sharpSplitscreen: string;
export declare const sharpSpoke: string;
export declare const sharpSports: string;
export declare const sharpSportsBar: string;
export declare const sharpSportsBaseball: string;
export declare const sharpSportsBasketball: string;
export declare const sharpSportsCricket: string;
export declare const sharpSportsEsports: string;
export declare const sharpSportsFootball: string;
export declare const sharpSportsGolf: string;
export declare const sharpSportsHandball: string;
export declare const sharpSportsHockey: string;
export declare const sharpSportsKabaddi: string;
export declare const sharpSportsMartialArts: string;
export declare const sharpSportsMma: string;
export declare const sharpSportsMotorsports: string;
export declare const sharpSportsRugby: string;
export declare const sharpSportsScore: string;
export declare const sharpSportsSoccer: string;
export declare const sharpSportsTennis: string;
export declare const sharpSportsVolleyball: string;
export declare const sharpSquare: string;
export declare const sharpSquareFoot: string;
export declare const sharpStackedBarChart: string;
export declare const sharpStackedLineChart: string;
export declare const sharpStairs: string;
export declare const sharpStar: string;
export declare const sharpStarBorder: string;
export declare const sharpStarBorderPurple500: string;
export declare const sharpStarHalf: string;
export declare const sharpStarOutline: string;
export declare const sharpStarPurple500: string;
export declare const sharpStarRate: string;
export declare const sharpStars: string;
export declare const sharpStart: string;
export declare const sharpStayCurrentLandscape: string;
export declare const sharpStayCurrentPortrait: string;
export declare const sharpStayPrimaryLandscape: string;
export declare const sharpStayPrimaryPortrait: string;
export declare const sharpStickyNote2: string;
export declare const sharpStop: string;
export declare const sharpStopCircle: string;
export declare const sharpStopScreenShare: string;
export declare const sharpStorage: string;
export declare const sharpStore: string;
export declare const sharpStorefront: string;
export declare const sharpStoreMallDirectory: string;
export declare const sharpStorm: string;
export declare const sharpStraighten: string;
export declare const sharpStream: string;
export declare const sharpStreetview: string;
export declare const sharpStrikethroughS: string;
export declare const sharpStroller: string;
export declare const sharpStyle: string;
export declare const sharpSubdirectoryArrowLeft: string;
export declare const sharpSubdirectoryArrowRight: string;
export declare const sharpSubject: string;
export declare const sharpSubscript: string;
export declare const sharpSubscriptions: string;
export declare const sharpSubtitles: string;
export declare const sharpSubtitlesOff: string;
export declare const sharpSubway: string;
export declare const sharpSummarize: string;
export declare const sharpSuperscript: string;
export declare const sharpSupervisedUserCircle: string;
export declare const sharpSupervisorAccount: string;
export declare const sharpSupport: string;
export declare const sharpSupportAgent: string;
export declare const sharpSurfing: string;
export declare const sharpSurroundSound: string;
export declare const sharpSwapCalls: string;
export declare const sharpSwapHoriz: string;
export declare const sharpSwapHorizontalCircle: string;
export declare const sharpSwapVert: string;
export declare const sharpSwapVerticalCircle: string;
export declare const sharpSwipe: string;
export declare const sharpSwipeDown: string;
export declare const sharpSwipeDownAlt: string;
export declare const sharpSwipeLeft: string;
export declare const sharpSwipeLeftAlt: string;
export declare const sharpSwipeRight: string;
export declare const sharpSwipeRightAlt: string;
export declare const sharpSwipeUp: string;
export declare const sharpSwipeUpAlt: string;
export declare const sharpSwipeVertical: string;
export declare const sharpSwitchAccessShortcut: string;
export declare const sharpSwitchAccessShortcutAdd: string;
export declare const sharpSwitchAccount: string;
export declare const sharpSwitchCamera: string;
export declare const sharpSwitchLeft: string;
export declare const sharpSwitchRight: string;
export declare const sharpSwitchVideo: string;
export declare const sharpSync: string;
export declare const sharpSyncAlt: string;
export declare const sharpSyncDisabled: string;
export declare const sharpSyncLock: string;
export declare const sharpSyncProblem: string;
export declare const sharpSystemSecurityUpdate: string;
export declare const sharpSystemSecurityUpdateGood: string;
export declare const sharpSystemSecurityUpdateWarning: string;
export declare const sharpSystemUpdate: string;
export declare const sharpSystemUpdateAlt: string;
export declare const sharpTab: string;
export declare const sharpTableBar: string;
export declare const sharpTableChart: string;
export declare const sharpTableRestaurant: string;
export declare const sharpTableRows: string;
export declare const sharpTablet: string;
export declare const sharpTabletAndroid: string;
export declare const sharpTabletMac: string;
export declare const sharpTableView: string;
export declare const sharpTabUnselected: string;
export declare const sharpTag: string;
export declare const sharpTagFaces: string;
export declare const sharpTakeoutDining: string;
export declare const sharpTapAndPlay: string;
export declare const sharpTapas: string;
export declare const sharpTask: string;
export declare const sharpTaskAlt: string;
export declare const sharpTaxiAlert: string;
export declare const sharpTempleBuddhist: string;
export declare const sharpTempleHindu: string;
export declare const sharpTerrain: string;
export declare const sharpTextDecrease: string;
export declare const sharpTextFields: string;
export declare const sharpTextFormat: string;
export declare const sharpTextIncrease: string;
export declare const sharpTextRotateUp: string;
export declare const sharpTextRotateVertical: string;
export declare const sharpTextRotationAngledown: string;
export declare const sharpTextRotationAngleup: string;
export declare const sharpTextRotationDown: string;
export declare const sharpTextRotationNone: string;
export declare const sharpTextsms: string;
export declare const sharpTextSnippet: string;
export declare const sharpTexture: string;
export declare const sharpTheaterComedy: string;
export declare const sharpTheaters: string;
export declare const sharpThermostat: string;
export declare const sharpThermostatAuto: string;
export declare const sharpThumbDown: string;
export declare const sharpThumbDownAlt: string;
export declare const sharpThumbDownOffAlt: string;
export declare const sharpThumbsUpDown: string;
export declare const sharpThumbUp: string;
export declare const sharpThumbUpAlt: string;
export declare const sharpThumbUpOffAlt: string;
export declare const sharpTimelapse: string;
export declare const sharpTimeline: string;
export declare const sharpTimer: string;
export declare const sharpTimer10: string;
export declare const sharpTimer10Select: string;
export declare const sharpTimer3: string;
export declare const sharpTimer3Select: string;
export declare const sharpTimerOff: string;
export declare const sharpTimeToLeave: string;
export declare const sharpTipsAndUpdates: string;
export declare const sharpTitle: string;
export declare const sharpToc: string;
export declare const sharpToday: string;
export declare const sharpToggleOff: string;
export declare const sharpToggleOn: string;
export declare const sharpToken: string;
export declare const sharpToll: string;
export declare const sharpTonality: string;
export declare const sharpTopic: string;
export declare const sharpTouchApp: string;
export declare const sharpTour: string;
export declare const sharpToys: string;
export declare const sharpTrackChanges: string;
export declare const sharpTraffic: string;
export declare const sharpTrain: string;
export declare const sharpTram: string;
export declare const sharpTransferWithinAStation: string;
export declare const sharpTransform: string;
export declare const sharpTransgender: string;
export declare const sharpTransitEnterexit: string;
export declare const sharpTranslate: string;
export declare const sharpTravelExplore: string;
export declare const sharpTrendingDown: string;
export declare const sharpTrendingFlat: string;
export declare const sharpTrendingUp: string;
export declare const sharpTripOrigin: string;
export declare const sharpTry: string;
export declare const sharpTty: string;
export declare const sharpTune: string;
export declare const sharpTungsten: string;
export declare const sharpTurnedIn: string;
export declare const sharpTurnedInNot: string;
export declare const sharpTv: string;
export declare const sharpTvOff: string;
export declare const sharpTwoWheeler: string;
export declare const sharpUmbrella: string;
export declare const sharpUnarchive: string;
export declare const sharpUndo: string;
export declare const sharpUnfoldLess: string;
export declare const sharpUnfoldMore: string;
export declare const sharpUnpublished: string;
export declare const sharpUnsubscribe: string;
export declare const sharpUpcoming: string;
export declare const sharpUpdate: string;
export declare const sharpUpdateDisabled: string;
export declare const sharpUpgrade: string;
export declare const sharpUpload: string;
export declare const sharpUploadFile: string;
export declare const sharpUsb: string;
export declare const sharpUsbOff: string;
export declare const sharpVerified: string;
export declare const sharpVerifiedUser: string;
export declare const sharpVerticalAlignBottom: string;
export declare const sharpVerticalAlignCenter: string;
export declare const sharpVerticalAlignTop: string;
export declare const sharpVerticalDistribute: string;
export declare const sharpVerticalSplit: string;
export declare const sharpVibration: string;
export declare const sharpVideoCall: string;
export declare const sharpVideocam: string;
export declare const sharpVideoCameraBack: string;
export declare const sharpVideoCameraFront: string;
export declare const sharpVideocamOff: string;
export declare const sharpVideogameAsset: string;
export declare const sharpVideogameAssetOff: string;
export declare const sharpVideoLabel: string;
export declare const sharpVideoLibrary: string;
export declare const sharpVideoSettings: string;
export declare const sharpVideoStable: string;
export declare const sharpViewAgenda: string;
export declare const sharpViewArray: string;
export declare const sharpViewCarousel: string;
export declare const sharpViewColumn: string;
export declare const sharpViewComfy: string;
export declare const sharpViewCompact: string;
export declare const sharpViewDay: string;
export declare const sharpViewHeadline: string;
export declare const sharpViewInAr: string;
export declare const sharpViewList: string;
export declare const sharpViewModule: string;
export declare const sharpViewQuilt: string;
export declare const sharpViewSidebar: string;
export declare const sharpViewStream: string;
export declare const sharpViewWeek: string;
export declare const sharpVignette: string;
export declare const sharpVilla: string;
export declare const sharpVisibility: string;
export declare const sharpVisibilityOff: string;
export declare const sharpVoiceChat: string;
export declare const sharpVoicemail: string;
export declare const sharpVoiceOverOff: string;
export declare const sharpVolumeDown: string;
export declare const sharpVolumeMute: string;
export declare const sharpVolumeOff: string;
export declare const sharpVolumeUp: string;
export declare const sharpVolunteerActivism: string;
export declare const sharpVpnKey: string;
export declare const sharpVpnLock: string;
export declare const sharpVrpano: string;
export declare const sharpWallpaper: string;
export declare const sharpWarning: string;
export declare const sharpWarningAmber: string;
export declare const sharpWash: string;
export declare const sharpWatch: string;
export declare const sharpWatchLater: string;
export declare const sharpWatchOff: string;
export declare const sharpWater: string;
export declare const sharpWaterDamage: string;
export declare const sharpWaterDrop: string;
export declare const sharpWaterfallChart: string;
export declare const sharpWaves: string;
export declare const sharpWavingHand: string;
export declare const sharpWbAuto: string;
export declare const sharpWbCloudy: string;
export declare const sharpWbIncandescent: string;
export declare const sharpWbIridescent: string;
export declare const sharpWbShade: string;
export declare const sharpWbSunny: string;
export declare const sharpWbTwilight: string;
export declare const sharpWc: string;
export declare const sharpWeb: string;
export declare const sharpWebAsset: string;
export declare const sharpWebAssetOff: string;
export declare const sharpWeekend: string;
export declare const sharpWest: string;
export declare const sharpWhatshot: string;
export declare const sharpWheelchairPickup: string;
export declare const sharpWhereToVote: string;
export declare const sharpWidgets: string;
export declare const sharpWifi: string;
export declare const sharpWifiCalling: string;
export declare const sharpWifiCalling3: string;
export declare const sharpWifiFind: string;
export declare const sharpWifiLock: string;
export declare const sharpWifiOff: string;
export declare const sharpWifiProtectedSetup: string;
export declare const sharpWifiTethering: string;
export declare const sharpWifiTetheringError: string;
export declare const sharpWifiTetheringOff: string;
export declare const sharpWindow: string;
export declare const sharpWineBar: string;
export declare const sharpWoman: string;
export declare const sharpWork: string;
export declare const sharpWorkOff: string;
export declare const sharpWorkOutline: string;
export declare const sharpWorkspacePremium: string;
export declare const sharpWorkspaces: string;
export declare const sharpWrapText: string;
export declare const sharpWrongLocation: string;
export declare const sharpWysiwyg: string;
export declare const sharpYard: string;
export declare const sharpYoutubeSearchedFor: string;
export declare const sharpZoomIn: string;
export declare const sharpZoomInMap: string;
export declare const sharpZoomOut: string;
export declare const sharpZoomOutMap: string; | pdanpdan/quasar | extras/material-icons-sharp/index.d.ts | TypeScript | mit | 88,356 |
import gulp from 'gulp';
import runSequence from 'run-sequence';
gulp.task('dev', ['clean'], function(cb) {
global.isProd = false;
runSequence(['styles', 'images', 'fonts', 'views','vendor'], 'browserify', 'watch', cb);
});
| tungptvn/tungpts-ng-blog | gulp/tasks/development.js | JavaScript | mit | 239 |
export class AddProduct {
public title: string;
public description: string;
public author: number;
public price: number;
public photos: any;
constructor(data) {
this.title = data.title;
this.description = data.description;
this.author = data.author;
this.price = data.price;
this.photos = data.photos;
}
}
| PavelVak/sell-it | src/app/shared/models/add-product.model.ts | TypeScript | mit | 341 |
module QueryStringSearch
class MatcherFactory
def self.build(search_option, build_options)
matcher_to_build = build_options.detect { |m| m.build_me?(search_option) }
if matcher_to_build
matcher = matcher_to_build.new
matcher.attribute = search_option.attribute
matcher.desired_value = search_option.desired_value
matcher.operator = search_option.operator
matcher
end
end
end
end
| umn-asr/query_string_search | lib/query_string_search/matcher_factory.rb | Ruby | mit | 473 |
package formatters
import (
"fmt"
"testing"
)
type str struct{}
func (s str) String() string {
return "test"
}
func TestFormatArray(t *testing.T) {
testCases := []struct {
name string
in interface{}
ret string
}{
{"array string", []string{"value 1", "value 2", "value 3"}, `{"value 1","value 2","value 3"}`},
{"array int", []int{10, 20, 30}, `{10,20,30}`},
{"empty array", []int{}, `{}`},
{"stringer array", []fmt.Stringer{str{}, str{}, str{}}, `{"test","test","test"}`},
{"interface array", nil, `{"value 1","value 2","value 3"}`},
{"nil", nil, ""},
}
// define interface array
values := make([]interface{}, 3)
values[0] = "value 1"
values[1] = "value 2"
values[2] = "value 3"
testCases[4].in = values
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
ret := FormatArray(tc.in)
if ret != tc.ret {
t.Errorf("expected %v, but got %v", tc.ret, ret)
}
})
}
}
| nuveo/prest | adapters/postgres/formatters/formatters_test.go | GO | mit | 931 |
import 'syncfusion-javascript/Scripts/ej/web/ej.radiobutton.min';
import { CommonModule } from '@angular/common';
import { EJComponents } from './core';
import { EventEmitter, Type, Component, ElementRef, ChangeDetectorRef, Input, Output, NgModule, ModuleWithProviders, Directive, forwardRef } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';
const noop = () => {
};
export const RadioButtonValueAccessor: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => RadioButtonComponent),
multi: true
};
@Component({
selector: '[ej-radiobutton]',
template: '',
host: { '(ejchange)': 'onChange($event.value)', '(change)': 'onChange($event.value)', '(focusOut)': 'onTouched()' },
providers: [RadioButtonValueAccessor]
})
export class RadioButtonComponent extends EJComponents<any, any> implements ControlValueAccessor
{
@Input('checked') checked_input: any;
@Input('cssClass') cssClass_input: any;
@Input('enabled') enabled_input: any;
@Input('enablePersistence') enablePersistence_input: any;
@Input('enableRTL') enableRTL_input: any;
@Input('htmlAttributes') htmlAttributes_input: any;
@Input('id') id_input: any;
@Input('idPrefix') idPrefix_input: any;
@Input('name') name_input: any;
@Input('size') size_input: any;
@Input('text') text_input: any;
@Input('validationMessage') validationMessage_input: any;
@Input('validationRules') validationRules_input: any;
@Input('value') value_input: any;
@Output('beforeChange') beforeChange_output = new EventEmitter();
@Output('change') change_output = new EventEmitter();
@Output('ejchange') ejchange_output = new EventEmitter();
@Output('create') create_output = new EventEmitter();
@Output('destroy') destroy_output = new EventEmitter();
constructor(public el: ElementRef, public cdRef: ChangeDetectorRef) {
super('RadioButton', el, cdRef, []);
}
onChange: (_: any) => void = noop;
onTouched: () => void = noop;
writeValue(value: any): void {
if (this.widget) {
this.widget.option('model.value', value);
} else {
this.model.value = value;
}
}
registerOnChange(fn: (_: any) => void): void {
this.onChange = fn;
}
registerOnTouched(fn: () => void): void {
this.onTouched = fn;
}
}
export var EJ_RADIOBUTTON_COMPONENTS: Type<any>[] = [RadioButtonComponent
];
| Dyalog/MiServer | PlugIns/Syncfusion-15.3.0.33/assets/angular2/radiobutton.component.ts | TypeScript | mit | 2,349 |
class HomeController < ApplicationController
def index
# asdsa
end
end
| shamithc/tailf | test/dummy/app/controllers/home_controller.rb | Ruby | mit | 78 |
<?php
require_once 'frontHomeLogin.php';
require_once 'backOpenSession.php';
require_once 'backCloseSession.php';
require_once 'backCheckLogin.php';
manageLogin();
function manageLogin() {
$user = (string) $_POST["username"];
$password = (string) $_POST["password"];
if (checkLogin($user, $password)) {
createSession();
if (checkCookie()) {
header ("Location: frontLogin1.php");
}
else {
closeSession();
}
}
else {
echo 'Username and/or password incorrect. Please try again.';
}
}
?> | martinbosse/exercice_login | middleLogin.php | PHP | mit | 626 |
<?php
/**
* Copyright (c) 2017. Puerto Parrot Booklet. Written by Dimitri Mostrey for www.puertoparrot.com
* Contact me at admin@puertoparrot.com or dmostrey@yahoo.com
*/
namespace App\Listeners\Articles\Comments;
use App\Events\Articles\Comments\Approved;
use App\Mail\Articles\Comments\ApprovedToAdmin;
use App\Models\User;
use Illuminate\Contracts\Queue\ShouldQueue;
use Mail;
/**
* Class ArticleCommentApprovedEmailAdmin
*
* @package App\Listeners
*/
class ApprovedEmailAdmin implements ShouldQueue
{
/**
* @var \Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|null|static|static[]
*/
private $admin;
/**
* Create the event listener.
*
*/
public function __construct()
{
$this->admin = User::find(8);
}
/**
* Handle the event.
*
* @param Approved $event
*
* @return void
*/
public function handle(Approved $event)
{
Mail::to($this->admin)->send(new ApprovedToAdmin($event->user, $event->article, $event->comment));
}
/**
*
*/
public function __destruct()
{
//
}
}
| Dimimo/Booklet | app/Listeners/Articles/Comments/ApprovedEmailAdmin.php | PHP | mit | 1,155 |
/**
*
* @type {*}
* @private
*/
jDoc.Engines.RTF.prototype._specialControlWords = [
"chpgn",
"chftn",
"chdate",
"chtime",
"chatn",
"chftnsep",
"/",
":",
"*",
"~",
"-",
"_",
"'hh",
"page",
"line",
"раr",
"sect",
"tab",
"сеll",
"row",
"colortbl",
"fonttbl",
"stylesheet",
"pict"
]; | pavel-voronin/jDoc | js/engines/RTF/reader/private/_specialControlWords.js | JavaScript | mit | 383 |
//using System;
//using Microsoft.EntityFrameworkCore.Infrastructure;
//using Discord.Commands;
//using Microsoft.Extensions.DependencyInjection;
//using System.Collections.Generic;
//namespace Discord.Addons.SimplePermissions
//{
// /// <summary> </summary>
// public sealed class EFCommandServiceExtension : IDbContextOptionsExtension
// {
// internal CommandService CommandService { get; }
// DbContextOptionsExtensionInfo IDbContextOptionsExtension.Info => _info;
// private readonly DbContextOptionsExtensionInfo _info;
// /// <summary> </summary>
// public EFCommandServiceExtension(CommandService commandService)
// {
// CommandService = commandService;
// _info = new ExtensionInfo(this);
// }
// void IDbContextOptionsExtension.ApplyServices(IServiceCollection services) { }
// //=> services.AddSingleton(CommandService);
// void IDbContextOptionsExtension.Validate(IDbContextOptions options) { }
// private sealed class ExtensionInfo : DbContextOptionsExtensionInfo
// {
// public override bool IsDatabaseProvider { get; } = false;
// public override string LogFragment { get; } = String.Empty;
// public ExtensionInfo(IDbContextOptionsExtension extension)
// : base(extension)
// {
// }
// public override long GetServiceProviderHashCode() => 0L;
// public override void PopulateDebugInfo(IDictionary<string, string> debugInfo) { }
// }
// }
//}
| Joe4evr/Discord.Addons | src/Discord.Addons.SimplePermissions.EFProvider/EFCommandServiceExtension.cs | C# | mit | 1,588 |
export default function album() {
return {
getAlbum: id => this.request(`${this.apiURL}/albums/${id}`),
getAlbums: ids => this.request(`${this.apiURL}/albums/?ids=${ids}`),
getTracks: id => this.request(`${this.apiURL}/albums/${id}/tracks`),
};
}
| dtfialho/js-tdd-course | module-06/src/album.js | JavaScript | mit | 263 |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="sah" version="2.0">
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About NSAcoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+39"/>
<source><b>NSAcoin Core</b> version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+57"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../utilitydialog.cpp" line="+29"/>
<source>Copyright</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The NSAcoin Core developers</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+30"/>
<source>Double-click to edit address or label</source>
<translation>Аадырыскын уларытаргар иккитэ баттаа</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&New</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Copy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>C&lose</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+74"/>
<source>&Copy Address</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="-41"/>
<source>Delete the currently selected address from the list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-27"/>
<source>&Delete</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-30"/>
<source>Choose the address to send coins to</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Choose the address to receive coins with</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>C&hoose</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Sending addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Receiving addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>These are your NSAcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>These are your NSAcoin addresses for receiving payments. It is recommended to use a new receiving address for each transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Copy &Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+194"/>
<source>Export Address List</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Exporting Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>There was an error trying to save the address list to %1.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+168"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+40"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR BITCOINS</b>!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-56"/>
<source>NSAcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your bitcoins from being stolen by malware infecting your computer.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>NSAcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+295"/>
<source>Sign &message...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+335"/>
<source>Synchronizing with network...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-407"/>
<source>&Overview</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-137"/>
<source>Node</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+138"/>
<source>Show general overview of wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>E&xit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show information about NSAcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<location line="+2"/>
<source>About &Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Show information about Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>&Encrypt Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>&Sending addresses...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Receiving addresses...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Open &URI...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+325"/>
<source>Importing blocks from disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-405"/>
<source>Send coins to a NSAcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for NSAcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Backup wallet to another location</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+430"/>
<source>NSAcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-643"/>
<source>Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+146"/>
<source>&Send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<location line="+2"/>
<source>&Show / Hide</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your NSAcoin addresses to prove you own them</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified NSAcoin addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+48"/>
<source>&File</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Settings</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>&Help</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Tabs toolbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-284"/>
<location line="+376"/>
<source>[testnet]</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-401"/>
<source>NSAcoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+163"/>
<source>Request payments (generates QR codes and bitcoin: URIs)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<location line="+2"/>
<source>&About NSAcoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Show the list of used sending addresses and labels</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Show the list of used receiving addresses and labels</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Open a bitcoin: URI or payment request</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show the NSAcoin Core help message to get a list with possible NSAcoin command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+159"/>
<location line="+5"/>
<source>NSAcoin client</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+142"/>
<source>%n active connection(s) to NSAcoin network</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+23"/>
<source>%n hour(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Last received block was generated %1 ago.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-85"/>
<source>Up to date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>Catching up...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+130"/>
<source>Sent transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+69"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoin.cpp" line="+438"/>
<source>A fatal error occurred. NSAcoin can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+119"/>
<source>Network Alert</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<location filename="../forms/coincontroldialog.ui" line="+14"/>
<source>Coin Control Address Selection</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>Quantity:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Bytes:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+45"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Priority:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+45"/>
<source>Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Low Output:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+48"/>
<source>After Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Change:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+63"/>
<source>(un)select all</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Tree mode</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>List mode</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirmations</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Confirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Priority</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="+42"/>
<source>Copy address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+26"/>
<source>Copy amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-25"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Lock unspent</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Unlock unspent</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Copy quantity</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Copy fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+323"/>
<source>highest</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>higher</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>high</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>medium-high</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>low-medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>low</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>lower</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>lowest</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>(%1 locked)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>none</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+140"/>
<source>Dust</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>yes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>no</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>This label turns red, if the transaction size is greater than 1000 bytes.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+5"/>
<source>This means a fee of at least %1 per kB is required.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-4"/>
<source>Can vary +/- 1 byte per input.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transactions with higher priority are more likely to get included into a block.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if the priority is smaller than "medium".</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>This label turns red, if any recipient receives an amount smaller than %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+4"/>
<source>This means a fee of at least %1 is required.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-3"/>
<source>Amounts below 0.546 times the minimum relay fee are shown as dust.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>This label turns red, if the change is smaller than %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+43"/>
<location line="+66"/>
<source>(no label)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<source>change from %1 (%2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>(change)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address list entry</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>The address associated with this address list entry. This can only be modified for sending addresses.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-10"/>
<source>&Address</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+28"/>
<source>New receiving address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid NSAcoin address.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>FreespaceChecker</name>
<message>
<location filename="../intro.cpp" line="+65"/>
<source>A new data directory will be created.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>name</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Directory already exists. Add %1 if you intend to create a new directory here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Path already exists, and is not a directory.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Cannot create data directory here.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>HelpMessageDialog</name>
<message>
<location filename="../forms/helpmessagedialog.ui" line="+19"/>
<source>NSAcoin Core - Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../utilitydialog.cpp" line="+38"/>
<source>NSAcoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Choose data directory on startup (default: 0)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>Intro</name>
<message>
<location filename="../forms/intro.ui" line="+14"/>
<source>Welcome</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Welcome to NSAcoin Core.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+26"/>
<source>As this is the first time the program is launched, you can choose where NSAcoin Core will store its data.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>NSAcoin Core will download and store a copy of the NSAcoin block chain. At least %1GB of data will be stored in this directory, and it will grow over time. The wallet will also be stored in this directory.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Use the default data directory</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Use a custom data directory:</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../intro.cpp" line="+85"/>
<source>NSAcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: Specified data directory "%1" can not be created.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>GB of free space available</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>(of %1GB needed)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OpenURIDialog</name>
<message>
<location filename="../forms/openuridialog.ui" line="+14"/>
<source>Open URI</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Open payment request from URI or file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>URI:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Select payment request file</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../openuridialog.cpp" line="+47"/>
<source>Select payment request file to open</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Main</source>
<translation type="unfinished"/>
</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.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Automatically start NSAcoin after logging in to the system.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Start NSAcoin on system login</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Size of &database cache</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>MB</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Number of script &verification threads</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+58"/>
<source>Connect to the NSAcoin network through a SOCKS proxy.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy (default proxy):</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>IP address of the proxy (e.g. IPv4: 127.0.0.1 / IPv6: ::1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+224"/>
<source>Active command-line options that override above options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+43"/>
<source>Reset all client options to default.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-323"/>
<source>&Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Automatically open the NSAcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Proxy &IP:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>&Port:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting NSAcoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Whether to show NSAcoin addresses in the transaction list or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Whether to show coin control features or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Display coin &control features (experts only)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+136"/>
<source>&OK</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+67"/>
<source>default</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+57"/>
<source>none</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+75"/>
<source>Confirm options reset</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+29"/>
<source>Client restart required to activate changes.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>Client will be shutdown, do you want to proceed?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+33"/>
<source>This change would require a client restart.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>The supplied proxy address is invalid.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+50"/>
<location line="+231"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the NSAcoin network after a connection is established, but this process has not completed yet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-155"/>
<source>Unconfirmed:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-83"/>
<source>Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Confirmed:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Your current spendable balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the spendable balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Immature:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Total:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Your current total balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source><b>Recent transactions</b></source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../overviewpage.cpp" line="+120"/>
<location line="+1"/>
<source>out of sync</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+403"/>
<location line="+13"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>URI can not be parsed! This can be caused by an invalid NSAcoin address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+96"/>
<source>Requested payment amount of %1 is too small (considered dust).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-221"/>
<location line="+212"/>
<location line="+13"/>
<location line="+95"/>
<location line="+18"/>
<location line="+16"/>
<source>Payment request error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-353"/>
<source>Cannot start bitcoin: click-to-pay handler</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+58"/>
<source>Net manager warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Your active proxy doesn't support SOCKS5, which is required for payment requests via proxy.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>Payment request fetch URL is invalid: %1</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Payment request file handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Payment request file can not be read or processed! This can be caused by an invalid payment request file.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+73"/>
<source>Unverified payment requests to custom payment scripts are unsupported.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>Refund from %1</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+43"/>
<source>Error communicating with %1: %2</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Payment request can not be parsed or processed!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Bad response from server %1</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+33"/>
<source>Payment acknowledged</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-11"/>
<source>Network request error</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QObject</name>
<message>
<location filename="../bitcoin.cpp" line="+71"/>
<location line="+11"/>
<source>NSAcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: Specified data directory "%1" does not exist.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>Error: Invalid combination of -regtest and -testnet.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../guiutil.cpp" line="+82"/>
<source>Enter a NSAcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QRImageWidget</name>
<message>
<location filename="../receiverequestdialog.cpp" line="+36"/>
<source>&Save Image...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Copy Image</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Save QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>PNG Image (*.png)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+23"/>
<location line="+36"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+359"/>
<source>N/A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-223"/>
<source>Client version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-10"/>
<source>Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>General</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+53"/>
<source>Using OpenSSL version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Name</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Number of connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Block chain</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+72"/>
<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="-521"/>
<source>Build date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+206"/>
<source>Debug log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Open the NSAcoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>Clear console</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the NSAcoin RPC console.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+122"/>
<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>ReceiveCoinsDialog</name>
<message>
<location filename="../forms/receivecoinsdialog.ui" line="+107"/>
<source>&Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-16"/>
<source>&Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-37"/>
<source>&Message:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-20"/>
<source>Reuse one of the previously used receiving addresses. Reusing addresses has security and privacy issues. Do not use this unless re-generating a payment request made before.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>R&euse an existing receiving address (not recommended)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<location line="+23"/>
<source>An optional message to attach to the payment request, which will be displayed when the request is opened. Note: The message will not be sent with the payment over the NSAcoin network.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-7"/>
<location line="+21"/>
<source>An optional label to associate with the new receiving address.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-7"/>
<source>Use this form to request payments. All fields are <b>optional</b>.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<location line="+22"/>
<source>An optional amount to request. Leave this empty or zero to not request a specific amount.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Clear all fields of the form.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Clear</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+78"/>
<source>Requested payments history</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-98"/>
<source>&Request payment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+120"/>
<source>Show the selected request (does the same as double clicking an entry)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Show</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Remove the selected entries from the list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Remove</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../receivecoinsdialog.cpp" line="+38"/>
<source>Copy label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ReceiveRequestDialog</name>
<message>
<location filename="../forms/receiverequestdialog.ui" line="+29"/>
<source>QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source>Copy &URI</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Copy &Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Save Image...</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../receiverequestdialog.cpp" line="+56"/>
<source>Request payment to %1</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Payment information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>URI</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error encoding URI into QR Code.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>RecentRequestsTableModel</name>
<message>
<location filename="../recentrequeststablemodel.cpp" line="+24"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+38"/>
<source>(no label)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>(no message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>(no amount)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+380"/>
<location line="+80"/>
<source>Send Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>Coin Control Features</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Inputs...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>automatically selected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Insufficient funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+89"/>
<source>Quantity:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Bytes:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+48"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Priority:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+48"/>
<source>Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Low Output:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+48"/>
<source>After Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Change:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<source>If this is activated, but the change address is empty or invalid, change will be sent to a newly generated address.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Custom change address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+164"/>
<source>Send to multiple recipients at once</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-23"/>
<source>Clear all fields of the form.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>Balance:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-78"/>
<source>Confirm the send action</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-229"/>
<source>Confirm send coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-74"/>
<location line="+5"/>
<location line="+5"/>
<location line="+4"/>
<source>%1 to %2</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-121"/>
<source>Copy quantity</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+170"/>
<source>Total Amount %1 (= %2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>or</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+203"/>
<source>The recipient address is not valid, please recheck.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>The amount to pay must be larger than 0.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>The amount exceeds your balance.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Transaction creation failed!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>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="+113"/>
<source>Warning: Invalid NSAcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>(no label)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-11"/>
<source>Warning: Unknown change address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-367"/>
<source>Are you sure you want to send?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>added as transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+171"/>
<source>Payment request expired</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Invalid payment address %1</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+131"/>
<location line="+521"/>
<location line="+536"/>
<source>A&mount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1152"/>
<source>Pay &To:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+30"/>
<source>Enter a label for this address to add it to your address book</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+57"/>
<source>&Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-50"/>
<source>Choose previously used address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-40"/>
<source>This is a normal payment.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+50"/>
<source>Alt+A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<location line="+524"/>
<location line="+536"/>
<source>Remove this entry</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1008"/>
<source>Message:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+968"/>
<source>This is a verified payment request.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-991"/>
<source>Enter a label for this address to add it to the list of used addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+33"/>
<source>A message that was attached to the bitcoin: URI which will be stored with the transaction for your reference. Note: This message will not be sent over the NSAcoin network.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+426"/>
<source>This is an unverified payment request.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<location line="+532"/>
<source>Pay To:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-498"/>
<location line="+536"/>
<source>Memo:</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ShutdownWindow</name>
<message>
<location filename="../utilitydialog.cpp" line="+48"/>
<source>NSAcoin Core is shutting down...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Do not shut down the computer until this window disappears.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>&Sign Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<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 type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<location line="+210"/>
<source>Choose previously used address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-200"/>
<location line="+210"/>
<source>Alt+A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-200"/>
<source>Paste address from clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this NSAcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<location line="+143"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-84"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<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 type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<source>Verify the message to ensure it was signed with the specified NSAcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+30"/>
<source>Enter a NSAcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Click "Sign Message" to generate signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+84"/>
<location line="+80"/>
<source>The entered address is invalid.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<location line="+8"/>
<location line="+72"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<location line="+80"/>
<source>The entered address does not refer to a key.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-72"/>
<source>Wallet unlock was cancelled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+58"/>
<source>The signature could not be decoded.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+28"/>
<source>NSAcoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>The NSAcoin Core developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TrafficGraphWidget</name>
<message>
<location filename="../trafficgraphwidget.cpp" line="+79"/>
<source>KB/s</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+28"/>
<source>Open until %1</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+53"/>
<source>Credit</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-125"/>
<source>matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+53"/>
<source>Debit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-62"/>
<source>Transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<location line="+9"/>
<source>Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-7"/>
<source>Comment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Merchant</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Generated coins must mature %1 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 type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Debug information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-232"/>
<source>, has not been successfully broadcast yet</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+234"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>Immature (%1 confirmations, will be available after %2)</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+16"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-22"/>
<location line="+25"/>
<source>Confirmed (%1 confirmations)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-22"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+62"/>
<source>Received with</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+57"/>
<location line="+16"/>
<source>All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Enter address or label to search</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Min amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+142"/>
<source>Export Transaction History</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Exporting Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the transaction history to %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Exporting Successful</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The transaction history was successfully saved to %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-22"/>
<source>Comma separated file (*.csv)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Confirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+107"/>
<source>Range:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>WalletFrame</name>
<message>
<location filename="../walletframe.cpp" line="+26"/>
<source>No wallet has been loaded.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+245"/>
<source>Send Coins</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+43"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+181"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Backup Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>The wallet data was successfully saved to %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Backup Successful</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+221"/>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-54"/>
<source>List commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-14"/>
<source>Get help for a command</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+26"/>
<source>Options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Specify configuration file (default: bitcoin.conf)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: bitcoind.pid)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-26"/>
<source>Listen for connections on <port> (default: 8333 or testnet: 18333)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-51"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+84"/>
<source>Specify your own public address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-148"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-36"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>Listen for JSON-RPC connections on <port> (default: 8332 or testnet: 18332)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+45"/>
<source>Accept command line and JSON-RPC commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+80"/>
<source>Run in the background as a daemon and accept commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+39"/>
<source>Use the test network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-118"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-95"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=bitcoinrpc
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 "NSAcoin Alert" admin@foo.com
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Acceptable ciphers (default: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. NSAcoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<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="+4"/>
<source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<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="+4"/>
<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="+6"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<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="+5"/>
<source>Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong NSAcoin will not work properly.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<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 type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source><category> can be:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>NSAcoin Core Daemon</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>NSAcoin RPC client version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Block creation options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Connect through SOCKS proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Connect to JSON-RPC on <port> (default: 8332 or testnet: 18332)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Corrupted block database detected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Do not load the wallet and disable wallet RPC calls</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Fee per kB to add to transactions you send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>If <category> is not supplied, output all debugging information.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Incorrect or no genesis block found. Wrong datadir for network?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Invalid -onion address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Not enough file descriptors available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Prepend debug output with timestamp (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>RPC client options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Select SOCKS version for -proxy (4 or 5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send command to NSAcoin server</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Set maximum block size in bytes (default: %d)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Specify wallet file (within data directory)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Start NSAcoin server</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>This is intended for regression testing tools and app development.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Usage (deprecated, use bitcoin-cli):</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Verifying blocks...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wait for RPC server to start</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wallet %s resides outside data directory %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Wallet options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Warning: Deprecated argument -debugnet ignored, use -debug=net</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>You need to rebuild the database using -reindex to change -txindex</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-79"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-105"/>
<source>Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Output debugging information (default: 0, supplying <category> is optional)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: %d)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+89"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>SSL options: (see the NSAcoin Wiki for SSL setup instructions)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>System error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Transaction amount too small</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-58"/>
<source>Password for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-70"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+80"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-132"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+161"/>
<source>Upgrade wallet to latest format</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-24"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-11"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+38"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-30"/>
<source>Server certificate file (default: server.cert)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>This help message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-107"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<source>Loading addresses...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-37"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of NSAcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+98"/>
<source>Wallet needed to be rewritten: restart NSAcoin to complete</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-100"/>
<source>Error loading wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Invalid -proxy address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-101"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+48"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-62"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-32"/>
<source>Unable to bind to %s on this computer. NSAcoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+95"/>
<source>Loading wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-56"/>
<source>Cannot downgrade wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+67"/>
<source>Rescanning...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-58"/>
<source>Done loading</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+85"/>
<source>To use the %s option</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-77"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-35"/>
<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 type="unfinished"/>
</message>
</context>
</TS> | nsacoin/nsacoin | src/qt/locale/bitcoin_sah.ts | TypeScript | mit | 130,888 |
package ru.sendto.gwt.client.html;
public class Th extends WidgetBase {
public Th() {
super("th");
}
public void setRowspan(String rows){
getElement().setAttribute("rowspan", rows);
}
public void setColspan(String cols){
getElement().setAttribute("colspan", cols);
}
}
| nleva/gwthtml | HtmlGwt/src/main/java/ru/sendto/gwt/client/html/Th.java | Java | mit | 287 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Pascal Triangle")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Hewlett-Packard")]
[assembly: AssemblyProduct("Pascal Triangle")]
[assembly: AssemblyCopyright("Copyright © Hewlett-Packard 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("7b737ca9-278b-4b45-89ae-e695395f1b17")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| spiderbait90/Step-By-Step-In-Coding | C# Fundamentals/C# Advanced/Multidimensional Arrays/Pascal Triangle/Properties/AssemblyInfo.cs | C# | mit | 1,431 |
function airPollution(sofiaMap, forces) {
for (let i = 0; i < sofiaMap.length; i++) {
sofiaMap[i] = sofiaMap[i].split(' ').map(Number)
}
for (let i = 0; i < forces.length; i++) {
forces[i] = forces[i].split(' ')
}
for (let i = 0; i < forces.length; i++) {
for (let k = 0; k < sofiaMap.length; k++) {
for (let l = 0; l < sofiaMap[k].length; l++) {
if (forces[i][0] === 'breeze') {
if (Number(forces[i][1]) === k) {
sofiaMap[k][l] = sofiaMap[k][l] - 15
if (sofiaMap[k][l] < 0) {
sofiaMap[k][l] = 0
}
}
} else if (forces[i][0] === 'gale') {
if (Number(forces[i][1]) === l) {
sofiaMap[k][l] = sofiaMap[k][l] - 20
if (sofiaMap[k][l] < 0) {
sofiaMap[k][l] = 0
}
}
} else if (forces[i][0] === 'smog') {
sofiaMap[k][l] = sofiaMap[k][l] + Number(forces[i][1])
}
}
}
}
let isPolluted = false
let result = []
let k = 0
for (let i = 0; i < sofiaMap.length; i++) {
for (let j = 0; j < sofiaMap[i].length; j++) {
if (sofiaMap[i][j] >= 50) {
if (!isPolluted) {
isPolluted = true
}
result[k++] = `[${i}-${j}]`
}
}
}
if (!isPolluted) {
console.log('No polluted areas')
} else {
console.log('Polluted areas: ' + result.join(', '))
}
}
airPollution([
"5 7 72 14 4",
"41 35 37 27 33",
"23 16 27 42 12",
"2 20 28 39 14",
"16 34 31 10 24",
],
["breeze 1", "gale 2", "smog 25"])
// Polluted areas: [0-2], [1-0], [2-3], [3-3], [4-1]
| b0jko3/SoftUni | JavaScript/Core/Fundamentals/Exams/11_Feb_2018/02._Air_Pollution.js | JavaScript | mit | 1,937 |
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
public class GradientPanel : Panel
{
public Color GradientFirstColor = Color.FromArgb(33, 33, 33);
public Color GradientSecondColor = Color.FromArgb(22, 22, 22);
public GradientPanel()
{
this.ResizeRedraw = true;
}
protected override void OnPaintBackground(PaintEventArgs e)
{
if (ClientRectangle.Width == 0 || ClientRectangle.Height == 0)
return;
using (var brush = new LinearGradientBrush(ClientRectangle,
GradientFirstColor, GradientSecondColor, LinearGradientMode.Vertical))
{
e.Graphics.FillRectangle(brush, this.ClientRectangle);
}
}
protected override void OnScroll(ScrollEventArgs se)
{
this.Invalidate();
base.OnScroll(se);
}
} | mikadev001/SublimeText-Overlay | SublimeOverlay/GradientPanel.cs | C# | mit | 908 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.data.tables.models;
import com.azure.core.annotation.Fluent;
/**
* A model representing configurable metrics settings of the Table service.
*/
@Fluent
public final class TableServiceMetrics {
/*
* The version of Analytics to configure.
*/
private String version;
/*
* Indicates whether metrics are enabled for the Table service.
*/
private boolean enabled;
/*
* Indicates whether metrics should generate summary statistics for called API operations.
*/
private Boolean includeApis;
/*
* The retention policy.
*/
private TableServiceRetentionPolicy retentionPolicy;
/**
* Get the version of Analytics to configure.
*
* @return The {@code version}.
*/
public String getVersion() {
return this.version;
}
/**
* Set the version of Analytics to configure.
*
* @param version The {@code version} to set.
*
* @return The updated {@link TableServiceMetrics} object.
*/
public TableServiceMetrics setVersion(String version) {
this.version = version;
return this;
}
/**
* Get a value that indicates whether metrics are enabled for the Table service.
*
* @return The {@code enabled} value.
*/
public boolean isEnabled() {
return this.enabled;
}
/**
* Set a value that indicates whether metrics are enabled for the Table service.
*
* @param enabled The {@code enabled} value to set.
*
* @return The updated {@link TableServiceMetrics} object.
*/
public TableServiceMetrics setEnabled(boolean enabled) {
this.enabled = enabled;
return this;
}
/**
* Get a value that indicates whether metrics should generate summary statistics for called API operations.
*
* @return The {@code includeApis} value.
*/
public Boolean isIncludeApis() {
return this.includeApis;
}
/**
* Set a value that indicates whether metrics should generate summary statistics for called API operations.
*
* @param includeApis The {@code includeApis} value to set.
*
* @return The updated {@link TableServiceMetrics} object.
*/
public TableServiceMetrics setIncludeApis(Boolean includeApis) {
this.includeApis = includeApis;
return this;
}
/**
* Get the {@link TableServiceRetentionPolicy} for these metrics on the Table service.
*
* @return The {@link TableServiceRetentionPolicy}.
*/
public TableServiceRetentionPolicy getTableServiceRetentionPolicy() {
return this.retentionPolicy;
}
/**
* Set the {@link TableServiceRetentionPolicy} for these metrics on the Table service.
*
* @param retentionPolicy The {@link TableServiceRetentionPolicy} to set.
*
* @return The updated {@link TableServiceMetrics} object.
*/
public TableServiceMetrics setRetentionPolicy(TableServiceRetentionPolicy retentionPolicy) {
this.retentionPolicy = retentionPolicy;
return this;
}
}
| Azure/azure-sdk-for-java | sdk/tables/azure-data-tables/src/main/java/com/azure/data/tables/models/TableServiceMetrics.java | Java | mit | 3,217 |
# frozen_string_literal: true
module Eve
class LocalPlanetsImporter
def import
Eve::Planet.pluck(:planet_id).each do |planet_id|
Eve::UpdatePlanetJob.perform_later(planet_id)
end
end
end
end
| biow0lf/evemonk | app/importers/eve/local_planets_importer.rb | Ruby | mit | 224 |
package com.scut.picturelibrary.manager;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.view.SurfaceHolder;
/**
* 视频播放管理
*
* @author cyc
*
*/
public class VideoManager {
private MediaPlayer mediaPlayer;
public VideoManager(Context context) {
super();
mediaPlayer = new MediaPlayer();
}
// 返回MediaPlayer
public MediaPlayer getMyMediaPlayer() {
return mediaPlayer;
}
// 播放
public void play(String filePath, SurfaceHolder holder,
OnPreparedListener mOnPreparedListener,
OnCompletionListener mOnCompletionListener) {
try {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
// 设置播放源
mediaPlayer.setDataSource(filePath);
mediaPlayer.setDisplay(holder);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(mOnPreparedListener);
mediaPlayer.setOnCompletionListener(mOnCompletionListener);
mediaPlayer.setOnErrorListener(new OnErrorListener() {
@Override
public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
// 发生错误
return false;
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
// 时间显示函数
public String ShowTime(int time) {
time /= 1000;
int minute = time / 60;
int second = time % 60;
minute %= 60;
return String.format("%02d:%02d", minute, second);
}
// 暂停
public void pause() {
mediaPlayer.pause();
}
}
| inexistence/PictureLibrary | src/com/scut/picturelibrary/manager/VideoManager.java | Java | mit | 1,631 |
using System;
using System.Configuration;
using System.Web;
using Portal.Core.Content;
namespace Portal.Web.Helpers
{
public static class CookieHelper
{
private static readonly HttpContext HttpContext;
private static readonly string NameCookieContentType;
private static readonly string NameCookieScreenWidth;
private static readonly string NameCookieSorting;
private static readonly string NameCookieSortingDescending;
private static SortType? _sortType;
private static ContentType? _contentType;
private static bool? _isDescending;
private static int? _screenWidth;
static CookieHelper()
{
HttpContext = HttpContext.Current;
NameCookieContentType = ConfigurationManager.AppSettings["NameCookieContentType"];
NameCookieScreenWidth = ConfigurationManager.AppSettings["NameCookieScreenWidth"];
switch (ContentType)
{
case ContentType.Books:
NameCookieSorting = ConfigurationManager.AppSettings["NameCookieSortingBook"];
NameCookieSortingDescending = ConfigurationManager.AppSettings["NameCookieSortingBookDescending"];
break;
case ContentType.Trainings:
NameCookieSorting = ConfigurationManager.AppSettings["NameCookieSortingTraining"];
NameCookieSortingDescending = ConfigurationManager.AppSettings["NameCookieSortingTrainingDescending"];
break;
default:
throw new ArgumentOutOfRangeException();
}
}
public static SortType SortType
{
get
{
if (_sortType == null)
{
_sortType = GetCookie<SortType>(NameCookieSorting);
}
return _sortType.Value;
}
set
{
SetCookie(value, NameCookieSorting);
_sortType = value;
}
}
public static ContentType ContentType
{
get
{
if (_contentType == null)
{
_contentType = GetCookie<ContentType>(NameCookieContentType);
}
return _contentType.Value;
}
set
{
SetCookie(value, NameCookieContentType);
_contentType = value;
}
}
public static bool OrderIsDescending
{
get
{
if (_isDescending == null)
{
_isDescending = GetCookie<bool>(NameCookieSortingDescending);
}
return _isDescending.Value;
}
set
{
SetCookie(value, NameCookieSortingDescending);
_isDescending = value;
}
}
public static int ScreenWidth
{
get
{
if (_screenWidth == null || _screenWidth == 0)
{
_screenWidth = GetCookie<int>(NameCookieScreenWidth);
}
return _screenWidth.Value;
}
set
{
SetCookie(value, NameCookieScreenWidth);
_screenWidth = value;
}
}
private static T GetCookie<T>(string nameCookie) where T : struct
{
var type = typeof(T);
var cookie = HttpContext.Request.Cookies[nameCookie];
if (string.IsNullOrEmpty(cookie?.Value))
{
return default(T);
}
if (type.IsEnum)
{
return (T)Enum.Parse(type, cookie.Value);
}
if (type == typeof(int) || type == typeof(bool))
{
var changeType = Convert.ChangeType(cookie.Value, type);
if (changeType != null)
{
return (T)changeType;
}
}
throw new ArgumentException();
}
private static void SetCookie<T>(T value, string nameCookie)
{
var cookie = HttpContext.Request.Cookies[nameCookie];
if (cookie == null)
{
HttpContext.Response.Cookies.Add(new HttpCookie(nameCookie, value.ToString()));
}
else
{
cookie.Value = value.ToString();
HttpContext.Response.SetCookie(cookie);
}
}
}
}
| EtwasGE/InformationPortal | Portal.Web/Helpers/CookieHelper.cs | C# | mit | 4,698 |
class RequirementsController < ApplicationController
before_filter :authenticate_user!
before_filter :require_project_involvement
before_filter :find_story
def create
@requirement = @story.pending_requirements.build(params[:requirement])
if @requirement.save
flash[:notice] = 'Requirement added'
else
flash[:requirement] = @requirement
end
redirect_to [current_project, @story]
end
def destroy
@requirement = @story.requirements.find(params[:id])
@requirement.destroy
redirect_to [current_project, @story], notice: 'Requirement removed'
end
private
def find_story
@story = current_project.stories.find(params[:story_id])
end
end
| avdgaag/storyteller | app/controllers/requirements_controller.rb | Ruby | mit | 701 |
<?php
/**
*
* @author dev
* @created 2015-09-17 10:57:04
*/
namespace Application;
use Application\Parse\TodoGrid;
use Bluz;
return
/**
* @return \closure
*/
function () use ($view) {
$view->grid = new TodoGrid();
}; | bashmach/bluz-skeleton-parse | application/modules/parse/controllers/grid.php | PHP | mit | 231 |
require 'spec_helper'
# Specs in this file have access to a helper object that includes
# the ProductsHelper. For example:
#
# describe ProductsHelper do
# describe "string concat" do
# it "concats two strings with spaces" do
# helper.concat_strings("this","that").should == "this that"
# end
# end
# end
describe ProductsHelper do
end
| LRDesign/mizugumo_demo | spec/helpers/products_helper_spec.rb | Ruby | mit | 355 |
<?php
namespace Anetwork\Validation;
use Anetwork\Validation\ValidationMessages;
/**
* @author Shahrokh Niakan <sh.niakan@anetwork.ir>
* @since May 21, 2016
*/
class ValidationRules
{
/**
* @var boolean
*/
protected $status;
/**
* validate persian alphabet and space
* @param $attribute
* @param $value
* @param $parameters
* @param $validator
* @author Shahrokh Niakan <sh.niakan@anetwork.ir>
* @since May 21, 2016
* @return boolean
*/
public function Alpha($attribute, $value, $parameters, $validator)
{
ValidationMessages::setCustomMessages( $validator );
$this->status = (bool) preg_match("/^[\x{600}-\x{6FF}\x{200c}\x{064b}\x{064d}\x{064c}\x{064e}\x{064f}\x{0650}\x{0651}\s]+$/u", $value);
return $this->status ;
}
/**
* validate persian number
* @param $attribute
* @param $value
* @param $parameters
* @param $validator
* @author Shahrokh Niakan <sh.niakan@anetwork.ir>
* @since May 21, 2016
* @return boolean
*/
public function Num($attribute, $value, $parameters, $validator)
{
ValidationMessages::setCustomMessages( $validator );
$this->status = (bool) preg_match('/^[\x{6F0}-\x{6F9}]+$/u', $value);
return $this->status ;
}
/**
* validate persian alphabet, number and space
* @param $attribute
* @param $value
* @param $parameters
* @param $validator
* @author Shahrokh Niakan <sh.niakan@anetwork.ir>
* @since May 21, 2016
* @return boolean
*/
public function AlphaNum($attribute, $value, $parameters, $validator)
{
ValidationMessages::setCustomMessages( $validator );
$this->status = (bool) preg_match('/^[\x{600}-\x{6FF}\x{200c}\x{064b}\x{064d}\x{064c}\x{064e}\x{064f}\x{0650}\x{0651}\s]+$/u', $value);
return $this->status;
}
/**
* validate mobile number
* @param $attribute
* @param $value
* @param $parameters
* @param $validator
* @author Shahrokh Niakan <sh.niakan@anetwork.ir>
* @since May 21, 2016
* @return boolean
*/
public function IranMobile($attribute, $value, $parameters, $validator)
{
ValidationMessages::setCustomMessages( $validator );
if ((bool) preg_match('/^(((98)|(\+98)|(0098)|0)(9){1}[0-9]{9})+$/', $value) || (bool) preg_match('/^(9){1}[0-9]{9}+$/', $value))
return true;
return false;
}
/**
* validate sheba number
* @param $attribute
* @param $value
* @param $parameters
* @param $validator
* @author Shahrokh Niakan <sh.niakan@anetwork.ir>
* @since May 21, 2016
* @return boolean
*/
public function Sheba($attribute, $value, $parameters, $validator)
{
ValidationMessages::setCustomMessages( $validator );
$ibanReplaceValues = array();
if (!empty($value)) {
$value = preg_replace('/[\W_]+/', '', strtoupper($value));
if (( 4 > strlen($value) || strlen($value) > 34 ) || ( is_numeric($value [ 0 ]) || is_numeric($value [ 1 ]) ) || ( ! is_numeric($value [ 2 ]) || ! is_numeric($value [ 3 ]) )) {
return false;
}
$ibanReplaceChars = range('A', 'Z');
foreach (range(10, 35) as $tempvalue) {
$ibanReplaceValues[] = strval($tempvalue);
}
$tmpIBAN = substr($value, 4) . substr($value, 0, 4);
$tmpIBAN = str_replace($ibanReplaceChars, $ibanReplaceValues, $tmpIBAN);
$tmpValue = intval(substr($tmpIBAN, 0, 1));
for ($i = 1; $i < strlen($tmpIBAN); $i++) {
$tmpValue *= 10;
$tmpValue += intval(substr($tmpIBAN, $i, 1));
$tmpValue %= 97;
}
if ($tmpValue != 1) {
return false;
}
return true;
}
return false;
}
/**
* validate meliCode number
* @param $attribute
* @param $value
* @param $parameters
* @param $validator
* @author Shahrokh Niakan <sh.niakan@anetwork.ir>
* @since May 21, 2016
* @return boolean
*/
public function MelliCode($attribute, $value, $parameters, $validator)
{
ValidationMessages::setCustomMessages( $validator );
if (!preg_match('/^\d{8,10}$/', $value) || preg_match('/^[0]{10}|[1]{10}|[2]{10}|[3]{10}|[4]{10}|[5]{10}|[6]{10}|[7]{10}|[8]{10}|[9]{10}$/', $value)) {
return false;
}
$sub = 0;
if (strlen($value) == 8) {
$value = '00' . $value;
} elseif (strlen($value) == 9) {
$value = '0' . $value;
}
for ($i = 0; $i <= 8; $i++) {
$sub = $sub + ( $value[$i] * ( 10 - $i ) );
}
if (( $sub % 11 ) < 2) {
$control = ( $sub % 11 );
} else {
$control = 11 - ( $sub % 11 );
}
if ($value[9] == $control) {
return true;
} else {
return false;
}
}
/**
* validate string that is not contain persian alphabet and number
* @param $attribute
* @param $value
* @param $parameters
* @param $validator
* @author Shahrokh Niakan <sh.niakan@anetwork.ir>
* @since June 13, 2016
* @return boolean
*/
public function IsNotPersian($attribute, $value, $parameters, $validator)
{
ValidationMessages::setCustomMessages( $validator );
if (is_string($value)) {
$this->status = (bool) preg_match("/[\x{600}-\x{6FF}]/u", $value);
return !$this->status;
}
return false;
}
/**
* validate array with custom count of array
* @param $attribute
* @param $value
* @param $parameters
* @param $validator
* @author Shahrokh Niakan <sh.niakan@anetwork.ir>
* @since June 13, 2016
* @return boolean
*/
public function LimitedArray($attribute, $value, $parameters, $validator)
{
ValidationMessages::setCustomMessages( $validator );
if (is_array($value)) {
if (isset($parameters[0])) {
return ( (count($value) <= $parameters[0]) ? true : false );
} else {
return true;
}
}
return false;
}
/**
* validate number to be unsigned
* @param $attribute
* @param $value
* @param $parameters
* @param $validator
* @author Shahrokh Niakan <sh.niakan@anetwork.ir>
* @since July 22, 2016
* @return boolean
*/
public function UnSignedNum($attribute, $value, $parameters, $validator)
{
ValidationMessages::setCustomMessages( $validator );
$this->status = (bool) preg_match('/^\d+$/', $value);
return $this->status;
}
/**
* validate alphabet and spaces
* @param $attribute
* @param $value
* @param $parameters
* @param $validator
* @author Shahrokh Niakan <sh.niakan@anetwork.ir>
* @since Agu 3, 2016
* @return boolean
*/
public function AlphaSpace($attribute, $value, $parameters, $validator)
{
ValidationMessages::setCustomMessages( $validator );
$this->status = (bool) preg_match("/^[\pL\s\x{200c}\x{064b}\x{064d}\x{064c}\x{064e}\x{064f}\x{0650}\x{0651}]+$/u", $value);
return $this->status;
}
/**
* validate Url
* @param $attribute
* @param $value
* @param $parameters
* @param $validator
* @author Shahrokh Niakan <sh.niakan@anetwork.ir>
* @since Agu 17, 2016
* @return boolean
*/
public function Url($attribute, $value, $parameters, $validator)
{
ValidationMessages::setCustomMessages( $validator );
$this->status = (bool) preg_match("/^(HTTP|http(s)?:\/\/(www\.)?[A-Za-z0-9]+([\-\.]{1,2}[A-Za-z0-9]+)*\.[A-Za-z]{2,40}(:[0-9]{1,40})?(\/.*)?)$/", $value);
return $this->status;
}
/**
* validate Domain
* @param $attribute
* @param $value
* @param $parameters
* @param $validator
* @author Shahrokh Niakan <sh.niakan@anetwork.ir>
* @since Agu 17, 2016
* @return boolean
*/
public function Domain($attribute, $value, $parameters, $validator)
{
ValidationMessages::setCustomMessages( $validator );
$this->status = (bool) preg_match("/^((www\.)?(\*\.)?[A-Za-z0-9]+([\-\.]{1,2}[A-Za-z0-9]+)*\.[A-Za-z]{2,40}(:[0-9]{1,40})?(\/.*)?)$/", $value);
return $this->status;
}
/**
* value must be more than parameters
* @param $attribute
* @param $value
* @param $parameters
* @param $validator
* @author Shahrokh Niakan <sh.niakan@anetwork.ir>
* @since Agu 24, 2016
* @return boolean
*/
public function More($attribute, $value, $parameters, $validator)
{
ValidationMessages::setCustomMessages( $validator );
if ( isset( $parameters[0] ) ) {
return ( $value > $parameters[0] ? true : false );
}
return false;
}
/**
* value must be less than parameters
* @param $attribute
* @param $value
* @param $parameters
* @param $validator
* @author Shahrokh Niakan <sh.niakan@anetwork.ir>
* @since Agu 24, 2016
* @return boolean
*/
public function Less($attribute, $value, $parameters, $validator)
{
ValidationMessages::setCustomMessages( $validator );
if ( isset( $parameters[0] ) ) {
return ( $value < $parameters[0] ? true : false );
}
return false;
}
/**
* iran phone number
* @param $attribute
* @param $value
* @param $parameters
* @param $validator
* @author Shahrokh Niakan <sh.niakan@anetwork.ir>
* @since Agu 24, 2016
* @return boolean
*/
public function IranPhone($attribute, $value, $parameters, $validator)
{
ValidationMessages::setCustomMessages( $validator );
$this->status = (bool) preg_match('/^[2-9][0-9]{7}+$/', $value) ;
return $this->status;
}
/**
* iran phone number with area code
* @param $attribute
* @param $value
* @param $parameters
* @param $validator
* @author Amir Hosseini <hosseini.sah95@gmail.com>
* @since Jan 28, 2019
* @return boolean
*/
public function IranPhoneWithAreaCode($attribute, $value, $parameters, $validator)
{
ValidationMessages::setCustomMessages( $validator );
$this->status = (bool) preg_match('/^(0[1-9]{2})[2-9][0-9]{7}+$/', $value) ;
return $this->status;
}
/**
* payment card number validation
* depending on 'http://www.aliarash.com/article/creditcart/credit-debit-cart.htm' article
*
* @param $attribute
* @param $value
* @param $parameters
* @param $validator
* @author Mojtaba Anisi <geevepahlavan@yahoo.com>
* @since Oct 1, 2016
* @return boolean
*/
function CardNumber($attribute, $value, $parameters, $validator)
{
ValidationMessages::setCustomMessages( $validator );
if (!preg_match('/^\d{16}$/', $value)) {
return false;
}
$sum = 0;
for ($position = 1; $position <= 16; $position++){
$temp = $value[$position - 1];
$temp = $position % 2 === 0 ? $temp : $temp * 2;
$temp = $temp > 9 ? $temp - 9 : $temp;
$sum += $temp;
}
return (bool)($sum % 10 === 0);
}
/**
* validate alphabet, number and some special characters
* @param $attribute
* @param $value
* @param $parameters
* @param $validator
* @author Shahrokh Niakan <sh.niakan@anetwork.ir>
* @since Oct 7, 2016
* @return boolean
*/
public function Address($attribute, $value, $parameters, $validator)
{
ValidationMessages::setCustomMessages( $validator );
$this->status = (bool) preg_match("/^[\pL\s\d\-\/\,\،\.\\\\\x{200c}\x{064b}\x{064d}\x{064c}\x{064e}\x{064f}\x{0650}\x{0651}\x{6F0}-\x{6F9}]+$/u", $value);
return $this->status;
}
/**
* validate Iran postal code format
* @param $attribute
* @param $value
* @param $parameters
* @param $validator
* @author Shahrokh Niakan <sh.niakan@anetwork.ir>
* @since Apr 5, 2017
* @return boolean
*/
public function IranPostalCode($attribute, $value, $parameters, $validator)
{
ValidationMessages::setCustomMessages( $validator );
$this->status = (bool) preg_match("/^(\d{5}-?\d{5})$/", $value);
return $this->status;
}
/**
* validate package name of apk
* @param $attribute
* @param $value
* @author Shahrokh Niakan <sh.niakan@anetwork.ir>
* @since May 31, 2017
* @return boolean
*/
public function PackageName($attribute, $value, $parameters, $validator)
{
ValidationMessages::setCustomMessages( $validator );
$this->status = (bool) preg_match("/^([a-zA-Z]{1}[a-zA-Z\d_]*\.)+[a-zA-Z][a-zA-Z\d_]*$/", $value);
return $this->status;
}
}
| anetwork/validation | src/ValidationRules.php | PHP | mit | 13,284 |
<?php
/**
* WPSEO plugin file.
*
* @package WPSEO\Admin\Links
*/
/**
* Represents the link count storage.
*/
class WPSEO_Meta_Storage implements WPSEO_Installable {
const TABLE_NAME = 'yoast_seo_meta';
/**
* @var WPSEO_Database_Proxy
*/
protected $database_proxy;
/**
* @deprecated
*
* @var null|string
*/
protected $table_prefix;
/**
* Initializes the database table.
*
* @param string $table_prefix Optional. Deprecated argument.
*/
public function __construct( $table_prefix = null ) {
if ( $table_prefix !== null ) {
_deprecated_argument( __METHOD__, 'WPSEO 7.4' );
}
$this->database_proxy = new WPSEO_Database_Proxy( $GLOBALS['wpdb'], self::TABLE_NAME, true );
}
/**
* Returns the table name to use.
*
* @return string The table name.
*/
public function get_table_name() {
return $this->database_proxy->get_table_name();
}
/**
* Creates the database table.
*
* @return boolean True if the table was created, false if something went wrong.
*/
public function install() {
return $this->database_proxy->create_table(
array(
'object_id bigint(20) UNSIGNED NOT NULL',
'internal_link_count int(10) UNSIGNED NULL DEFAULT NULL',
'incoming_link_count int(10) UNSIGNED NULL DEFAULT NULL',
),
array(
'UNIQUE KEY object_id (object_id)',
)
);
}
/**
* Saves the link count to the database.
*
* @param int $meta_id The id to save the link count for.
* @param array $meta_data The total amount of links.
*/
public function save_meta_data( $meta_id, array $meta_data ) {
$where = array( 'object_id' => $meta_id );
$saved = $this->database_proxy->upsert(
array_merge( $where, $meta_data ),
$where
);
if ( $saved === false ) {
WPSEO_Meta_Table_Accessible::set_inaccessible();
}
}
/**
* Updates the incoming link count
*
* @param array $post_ids The posts to update the incoming link count for.
* @param WPSEO_Link_Storage $storage The link storage object.
*/
public function update_incoming_link_count( array $post_ids, WPSEO_Link_Storage $storage ) {
global $wpdb;
$query = $wpdb->prepare(
'
SELECT COUNT( id ) AS incoming, target_post_id AS post_id
FROM ' . $storage->get_table_name() . '
WHERE target_post_id IN(' . implode( ',', array_fill( 0, count( $post_ids ), '%d' ) ) . ')
GROUP BY target_post_id',
$post_ids
);
$results = $wpdb->get_results( $query );
$post_ids_non_zero = array();
foreach ( $results as $result ) {
$this->save_meta_data( $result->post_id, array( 'incoming_link_count' => $result->incoming ) );
$post_ids_non_zero[] = $result->post_id;
}
$post_ids_zero = array_diff( $post_ids, $post_ids_non_zero );
foreach ( $post_ids_zero as $post_id ) {
$this->save_meta_data( $post_id, array( 'incoming_link_count' => 0 ) );
}
}
}
| agencja-acclaim/gulp-bower-webapp | wp-content/plugins/wordpress-seo/admin/class-meta-storage.php | PHP | mit | 2,857 |
package net.coding.program.task;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import net.coding.program.R;
import net.coding.program.common.Global;
import net.coding.program.common.base.MDEditFragment;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.FragmentArg;
import org.androidannotations.annotations.OptionsItem;
@EFragment(R.layout.fragment_task_descrip_md)
public class TaskDescripMdFragment extends MDEditFragment {
@FragmentArg
String contentMd;
ActionMode mActionMode;
private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
int id = 0;
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
menu.clear();
mode.getMenu().clear();
mode.getMenuInflater().inflate(R.menu.task_description_edit, menu);
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.action_save:
((TaskDescrip) getActivity()).closeAndSave(edit.getText().toString());
return true;
case R.id.action_preview:
id = R.id.action_preview;
mActionMode.finish();
Global.popSoftkeyboard(getActivity(), edit, false);
return true;
default:
return false;
}
}
@Override
public void onDestroyActionMode(ActionMode mode) {
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
fragmentManager.popBackStack();
if (id == R.id.action_preview) {
Fragment fragment = TaskDescripHtmlFragment_.builder()
.contentMd(edit.getText().toString())
.preview(true)
.build();
fragmentManager
.beginTransaction()
.setCustomAnimations(
R.anim.alpha_in, R.anim.alpha_out,
R.anim.alpha_in, R.anim.alpha_out)
.replace(R.id.container, fragment)
.addToBackStack("pre")
.commit();
} else {
if (fragmentManager.getFragments().size() == 1) {
getActivity().finish();
}
}
}
};
@AfterViews
void init() {
setHasOptionsMenu(true);
if (contentMd != null) {
edit.setText(contentMd);
mActionMode = getActivity().startActionMode(mActionModeCallback);
}
}
@OptionsItem
void action_save() {
((TaskDescrip) getActivity()).closeAndSave(edit.getText().toString());
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_task_description_edit, menu);
}
}
| Coding/Coding-Android | app/src/main/java/net/coding/program/task/TaskDescripMdFragment.java | Java | mit | 3,443 |
"use strict";
exports.default = {
type: "html",
url: "http://www.xnview.com/en/xnviewmp/",
getVersion: function($) {
return $("#downloads p")
.contains("Download")
.find("strong")
.version("XnView MP @version");
}
};
| foxable/app-manager | storage/apps/xnview-mp/versionProvider.js | JavaScript | mit | 277 |
///////////////////////////////////////////////////////////////////////////
// Copyright © Esri. All Rights Reserved.
//
// Licensed under the Apache License Version 2.0 (the 'License');
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 'AS IS' BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///////////////////////////////////////////////////////////////////////////
define({
"_widgetLabel": "Yapı Taslağı Oluşturucu",
"newTraverseButtonLabel": "Yeni Çapraz Çizgi Başlat",
"invalidConfigMsg": "Geçersiz Yapılandırma",
"geometryServiceURLNotFoundMSG": "Geometri Servisi URL’si alınamıyor",
"editTraverseButtonLabel": "Çapraz Çizgiyi Düzenle",
"mapTooltipForStartNewTraverse": "Başlamak için haritada bir nokta seçin veya aşağıya girin",
"mapTooltipForEditNewTraverse": "Düzenlenecek yapıyı seçin",
"mapTooltipForUpdateStartPoint": "Başlangıç noktasını güncellemek için tıklayın",
"mapTooltipForScreenDigitization": "Yapı noktası eklemek için tıklayın",
"mapTooltipForUpdatingRotaionPoint": "Döndürme noktasını güncellemek için tıklayın",
"mapTooltipForRotate": "Döndürmek için sürükleyin",
"mapTooltipForScale": "Ölçeklendirmek için sürükleyin",
"backButtonTooltip": "Geri",
"newTraverseTitle": "Yeni Çapraz Çizgi",
"editTraverseTitle": "Çapraz Çizgiyi Düzenle",
"clearingDataConfirmationMessage": "Değişiklikler atılacak, devam etmek istiyor musunuz?",
"unableToFetchParcelMessage": "Yapı alınamıyor.",
"unableToFetchParcelLinesMessage": "Yapı çizgileri alınamıyor.",
"planSettings": {
"planSettingsTitle": "Ayarlar",
"directionOrAngleTypeLabel": "Yön veya Açı Türü",
"directionOrAngleUnitsLabel": "Yön veya Açı Birimi",
"distanceAndLengthUnitsLabel": "Mesafe ve Uzunluk Birimleri",
"areaUnitsLabel": "Alan Birimleri:",
"circularCurveParameters": "Dairesel Eğri Parametreleri",
"northAzimuth": "Kuzey Azimut",
"southAzimuth": "Güney Azimut",
"quadrantBearing": "Çeyrek Semt Açısı",
"radiusAndChordLength": "Yarıçap ve Kiriş Uzunluğu",
"radiusAndArcLength": "Yarıçap ve Yay Uzunluğu",
"expandGridTooltipText": "Kılavuzu genişlet",
"collapseGridTooltipText": "Kılavuzu daralt",
"zoomToLocationTooltipText": "Konuma yaklaştır",
"onScreenDigitizationTooltipText": "Sayısallaştırma",
"updateRotationPointTooltipText": "Döndürme noktasını güncelle"
},
"traverseSettings": {
"bearingLabel": "Yön",
"lengthLabel": "Uzunluk",
"radiusLabel": "Yarıçap",
"noMiscloseCalculated": "Kapanmama hesaplanamadı",
"traverseMiscloseBearing": "Kapanmama Yönü",
"traverseAccuracy": "Doğruluk",
"accuracyHigh": "Yüksek",
"traverseDistance": "Kapanmama Mesafesi",
"traverseMiscloseRatio": "Kapanmama Oranı",
"traverseStatedArea": "Belirtilen Alan",
"traverseCalculatedArea": "Hesaplanan Alan",
"addButtonTitle": "Ekle",
"deleteButtonTitle": "Kaldır"
},
"parcelTools": {
"rotationToolLabel": "Açı",
"scaleToolLabel": "Ölçek"
},
"newTraverse": {
"invalidBearingMessage": "Geçersiz Yön.",
"invalidLengthMessage": "Geçersiz Uzunluk.",
"invalidRadiusMessage": "Geçersiz Yarıçap.",
"negativeLengthMessage": "Yalnızca eğriler için geçerlidir",
"enterValidValuesMessage": "Geçerli değer girin.",
"enterValidParcelInfoMessage": "Kaydedilecek geçerli yapı bilgisi girin.",
"unableToDrawLineMessage": "Çizgi çizilemiyor.",
"invalidEndPointMessage": "Geçersiz Bitiş Noktası, çizgi çizilemiyor.",
"lineTypeLabel": "Çizgi Tipi"
},
"planInfo": {
"requiredText": "(gerekli)",
"optionalText": "(isteğe bağlı)",
"parcelNamePlaceholderText": "Yapı adı",
"parcelDocumentTypeText": "Belge türü",
"planNamePlaceholderText": "Plan adı",
"cancelButtonLabel": "İptal Et",
"saveButtonLabel": "Kaydet",
"saveNonClosedParcelConfirmationMessage": "Girilen yapı kapatılmamış, yine de devam etmek ve yalnızca yapı çizgilerini kaydetmek istiyor musunuz?",
"unableToCreatePolygonParcel": "Yapı alanı oluşturulamıyor.",
"unableToSavePolygonParcel": "Yapı alanı kaydedilemiyor.",
"unableToSaveParcelLines": "Yapı çizgileri kaydedilemiyor.",
"unableToUpdateParcelLines": "Yapı çizgileri güncellenemiyor.",
"parcelSavedSuccessMessage": "Yapı başarıyla kaydedildi.",
"parcelDeletedSuccessMessage": "Parsel başarıyla silindi.",
"parcelDeleteErrorMessage": "Parselin silinmesinde hata oluştu.",
"enterValidParcelNameMessage": "Geçerli yapı adı girin.",
"enterValidPlanNameMessage": "Geçerli plan adı girin.",
"enterValidDocumentTypeMessage": "Geçersiz belge türü.",
"enterValidStatedAreaNameMessage": "Geçerli belirtilen alan girin."
},
"xyInput": {
"explanation": "Parsel katmanınızın mekansal referansında"
}
}); | tmcgee/cmv-wab-widgets | wab/2.13/widgets/ParcelDrafter/nls/tr/strings.js | JavaScript | mit | 5,323 |
/*globals $:false, _:false, Firebase:false */
'use strict';
var url = 'https://jengaship.firebaseio.com/',
fb = new Firebase(url),
gamesFb = new Firebase(url + 'games'),
games,
avaGames = [],
emptyGames = [],
myGames = [],
myBoardPositions = [],
currentGame,
$playerName = $('#playerName'),
$chosenName,
sunkShips = [];
// booleans to check if ships have been placed
// Tasks Left:
//// 1. Write Jade code which consists of a container for each type of ship,
// directing the user to place that type of ship (i.e. 2-destroyer, 3-cruiser, 3-submarine, 4-battleship, or 5-aircraft carrier)
// there should be a button in the jade to rotate the ship placement 90 degrees carried out in task 2
// unhide each container on clicking the '.myBoard' container, cycling through each
//// 2. Write javascript function that creates a gameboard array every time the user clicks the '.myBoard' container
// it should be a length 100 array of mostly 0's but replacing in the correct position a number corresponding
// to the boat that the user is currently placing (i.e. the ship container that is not hidden)
// it should end with a gameboard array of a user's complete ship placement. Push that to the correct user's gameboard on fb.
// you can use findCurrentGameId() to get the necessary fb info
//// 3. Write a javascript function that compares the gameboard of the other user stored on fb (written in step 2),
// and compares it to the user's '.theirBoard' clicked cell
//// 4. Style each type of ship div (2,3,4,5)
//// 5. Check for hit or miss and update other user's firebase gameboard with X or M.
////
// set .cell height equal to width
$(window).ready(function() {
console.log('resizing window');
var cw = $('.cell').width();
$('.cell').css({'height':cw+'px'});
});
$(window).on('resize', function() {
console.log('resizing window');
var cw = $('.cell').width();
$('.cell').css({'height':cw+'px'});
});
//populate list of available and empty games
function checkGames (callback1, callback2) {
gamesFb.once('value', function (res) {
var data = res.val();
games = _.keys(data);
_.forEach(games, function(g){
if(g !== 'undefined'){
var gUrl = new Firebase(url+'games/'+g+'/');
gUrl.once('value', function(games){
var gameValue = games.val();
if (gameValue.user1 && gameValue.user2 === '') {
avaGames = [];
avaGames.push(g);
} else if(gameValue.user1 === $chosenName){
myGames = [];
myGames.push(g);
}
callback1(avaGames);
})
} else {}
});
});
callback2(avaGames);
}
//find current game id
//this is how we can find which game the curent user is in, at any time
// It returns an array in the callback with the current game id and the current user number (i.e. 1 or 2)
// used in the cell click function
function findCurrentGameId(gamesFb, callback){
var foundGame = [];
gamesFb.once('value', function(n){
var games = n.val(),
currentUser = $chosenName;
_.forEach(games, function(m, key){
if(m.user1===currentUser){
currentGame = key;
foundGame.push([key,1]);
} else if(m.user2 === currentUser){
currentGame = key;
foundGame.push([key,2]);
}
});
callback(foundGame);
});
}
//create empty game with host user
function createEmptyGame (user1) {
var gameBoard1 = [],
gameBoard2 = [],
user1 = user1,
user2 = '';
for (var i = 0;i < 100; i++) {
gameBoard1.push(0);
gameBoard2.push(0);
}
var game = {'gameBoard1': gameBoard1, 'gameBoard2': gameBoard2, 'user1': user1, 'user2': user2, 'userTurn': 1};
return game;
}
//switches the turn of the player
function switchTurn (foundGame) {
var turnUrl = new Firebase(url + 'games/' + foundGame + '/userTurn');
turnUrl.once('value', function(user){
if (user.val() === 1) {
turnUrl.set(2)
} else {turnUrl.set(1)}
});
}
//this gameboard is taken from the local users gameboard layout, just the ship placement
//it needs to run when the user's ship placement is done
function createMyGameBoard(){
var gameboard = [],
$myBoard = $('.myBoard'),
$myBoardCells = $myBoard.find('.cell');
_.forEach($myBoardCells, function(cell){
//key: x = hit, m = miss, 2=2 hole ship, 3=3 hole ship, 4=4 hole ship, 5 = 5 hole ship, 0 = untouched
var $cell = $(cell);
if($cell.hasClass('ship2')){
gameboard.push('2');
} else if($cell.hasClass('ship3')){
gameboard.push('3');
} else if($cell.hasClass('ship4')){
gameboard.push('4');
} else if($cell.hasClass('ship5')){
gameboard.push('5');
} else {gameboard.push(0)};
});
return gameboard;
}
//this gameboard is taken from the remote users computed hitOrMissArray
//this needs to run on cell click
function appendMyGuessesGameboard(gb){
var $theirBoard = $('.theirBoard');
for(var i=0;i<gb.length-1;i++){
var $theirBoardCells = $('.theirBoard .cell:eq('+i+')');
if(gb[i] === 'x'){
$theirBoardCells.addClass('hit');
//$('.theirBoard').effect('shake');
} else if(gb[i] === 'm'){
$theirBoardCells.addClass('miss');
} else {}
}
}
function appendTheirGuessesGameboard(gb){
var $myBoard = $('.myBoard');
for(var i=0;i<gb.length-1;i++){
var $myBoardCells = $('.myBoard .cell:eq('+i+')');
if(gb[i] === 'x'){
$myBoardCells.addClass('hit');
} else if(gb[i] === 'm'){
$myBoardCells.addClass('miss');
} else if(gb[i] === '2'){
$myBoardCells.addClass('ship2');
} else if(gb[i] === '3'){
$myBoardCells.addClass('ship3');
} else if(gb[i] === '4'){
$myBoardCells.addClass('ship4');
} else if(gb[i] === '5'){
$myBoardCells.addClass('ship5');
} else{}
}
}
function createBoardPosition(cell) {
var $cell = $('.myBoard .cell'),
index = $cell.index(cell),
currentShip = $('.current'),
$shipList = $('.ship-list'),
$ship2 = $('.destroyer'),
$ship3a = $('.cruiser'),
$ship3b = $('.submarine'),
$ship4 = $('.battleship'),
$ship5 = $('.aircraft-carrier'),
vertical = $shipList.hasClass('vertical'),
remainingRowCells = cell.nextAll().length,
remainingRows = cell.parent().nextAll().length + 1,
nextShipInRow = cell.nextUntil('.ship'),
shipSize = $('.current').find('li').length;
for (var i=0; i < 100; i++) {
if (myBoardPositions[i] === undefined) {
myBoardPositions[i] = 0;
}
}
// check available cells against ship size before placing
if ((!vertical && (remainingRowCells < shipSize)) || (!vertical && (nextShipInRow < shipSize)) || (vertical && remainingRows < shipSize)) {
console.log('cant place ship here, not enough cells');
} else if ($ship2.hasClass('current') && vertical) {
myBoardPositions[index] = 2;
myBoardPositions[index + 10] = 2;
$ship2.toggleClass('placed');
appendShipToBoard(cell, 2);
console.log('placed destroyer');
} else if ($ship2.hasClass('current')) {
myBoardPositions[index] = 2;
myBoardPositions[index + 1] = 2;
$ship2.toggleClass('placed');
appendShipToBoard(cell, 2);
console.log('placed destroyer');
} else if ($ship3a.hasClass('current') && vertical) {
myBoardPositions[index] = 3;
myBoardPositions[index + 10] = 3;
myBoardPositions[index + 20] = 3;
$ship3a.toggleClass('placed');
appendShipToBoard(cell, 3);
console.log('placed cruiser');
} else if ($ship3a.hasClass('current')) {
myBoardPositions[index] = 3;
myBoardPositions[index + 1] = 3;
myBoardPositions[index + 2] = 3;
$ship3a.toggleClass('placed');
appendShipToBoard(cell, 3);
console.log('placed cruiser');
} else if ($ship3b.hasClass('current') && vertical) {
myBoardPositions[index] = 3;
myBoardPositions[index + 10] = 3;
myBoardPositions[index + 20] = 3;
$ship3b.toggleClass('placed');
appendShipToBoard(cell, 3);
console.log('placed submarine');
} else if ($ship3b.hasClass('current')) {
myBoardPositions[index] = 3;
myBoardPositions[index + 1] = 3;
myBoardPositions[index + 2] = 3;
$ship3b.toggleClass('placed');
appendShipToBoard(cell, 3);
console.log('placed submarine');
} else if ($ship4.hasClass('current') && vertical) {
myBoardPositions[index] = 4;
myBoardPositions[index + 10] = 4;
myBoardPositions[index + 20] = 4;
myBoardPositions[index + 30] = 4;
$ship4.toggleClass('placed');
appendShipToBoard(cell, 4);
console.log('placed battleship');
} else if ($ship4.hasClass('current')) {
myBoardPositions[index] = 4;
myBoardPositions[index + 1] = 4;
myBoardPositions[index + 2] = 4;
myBoardPositions[index + 3] = 4;
$ship4.toggleClass('placed');
appendShipToBoard(cell, 4);
console.log('placed battleship');
} else if ($ship5.hasClass('current') && vertical) {
myBoardPositions[index] = 5;
myBoardPositions[index + 10] = 5;
myBoardPositions[index + 20] = 5;
myBoardPositions[index + 30] = 5;
myBoardPositions[index + 40] = 5;
$ship5.toggleClass('placed');
console.log('placed aircraft carrier');
appendShipToBoard(cell, 5);
} else if ($ship5.hasClass('current')) {
myBoardPositions[index] = 5;
myBoardPositions[index + 1] = 5;
myBoardPositions[index + 2] = 5;
myBoardPositions[index + 3] = 5;
myBoardPositions[index + 4] = 5;
$ship5.toggleClass('placed');
appendShipToBoard(cell, 5);
console.log('placed aircraft carrier');
} else {
console.log('no more ships to play');
}
return myBoardPositions;
}
function sendBoardToFb(user, array) {
findCurrentGameId(gamesFb, function(foundGame){
var thisGame = new Firebase (url + 'games/' + foundGame[0][0]),
myGameBoard = thisGame.child('gameBoard' + user);
myGameBoard.set(array);
});
}
function appendShipToBoard(cell, shipSize) {
var vertical = $('.ship-list').hasClass('vertical'),
shipType = 'ship' + shipSize;
cell.addClass('ship').addClass(shipType);
for (var i=0; i < shipSize - 1; i++) {
if (vertical) {
cell.parent().nextAll().eq(i).find('.cell').eq(cell.index() - 1).addClass('ship').addClass(shipType);
} else {
cell.nextAll('.cell').eq(i).addClass('ship').addClass(shipType);
}
}
}
function checkBoardForShips (theirGameboard) {
function filter3(number){return number === 3};
if ($.inArray(2, theirGameboard) === -1 && $.inArray(2,sunkShips) === -1) {
alert('Ship 2 is sunk!');
sunkShips.push(2);
} else if (theirGameboard.filter(filter3).length === 3 && $.inArray(8,sunkShips) === -1) {
alert('One 3 ship is sunk!');
sunkShips.push(8);
} else if ($.inArray(3, theirGameboard) === -1 && $.inArray(9,sunkShips) === -1) {
alert('Both 3 ships are sunk!');
sunkShips.push(9);
} else if ($.inArray(4, theirGameboard) === -1 && $.inArray(4,sunkShips) === -1) {
alert('Ship 4 is sunk');
sunkShips.push(4);
} else if ($.inArray(5, theirGameboard) === -1 && $.inArray(5,sunkShips) === -1) {
alert('ship 5 is sunk');
sunkShips.push(5);
} else if ($.inArray(2, theirGameboard) === -1 && $.inArray(3, theirGameboard) === -1 && $.inArray(4, theirGameboard) === -1 && $.inArray(5, theirGameboard) === -1) {
alert('All ships are destroyed!');
}
}
///////////////////////////////////////////////////
///////////////// State Listeners /////////////////
///////////////////////////////////////////////////
function listenForUser2(){
findCurrentGameId(gamesFb, function(foundGame){
var thisGameUrl = new Firebase (url + 'games/' + foundGame[0][0]);
var otherPlayer = new Firebase (url + 'games/' + foundGame[0][0] + '/user2');
thisGameUrl.on('child_changed', function(childsnap){
var childvalue = childsnap.val();
thisGameUrl.once('value', function(snap){
var p2 = snap.val().user2;
if(p2 !== ''){
$('.game-status-p').text('player 2 joined');
thisGameUrl.off('child_changed');
listenforShipPlacement();
}
})
});
});
}
function listenforShipPlacement(){
//delete stranded game
checkGames((function(avaGames){
var deleteGame = new Firebase (url + 'games/' + avaGames[0]);
deleteGame.set(null);
}),function(avaGames){
});
//attach event listeners to game
findCurrentGameId(gamesFb, function(foundGame){
var thisGameUrl = new Firebase (url + 'games/' + foundGame[0][0]);
function otherPlayer(){if(foundGame[0][1] === 1){return 2}else{return 1}};
var otherGameboard = new Firebase (url + 'games/' + foundGame[0][0] + '/gameboard'+otherPlayer());
thisGameUrl.on('child_changed', function(childsnap){
var snap = childsnap.val();
if(otherPlayer()===1){
thisGameUrl.once('value', function(g){
if($.inArray(2,g.val().gameBoard1) !== -1){
thisGameUrl.off('child_changed');
listenforMyBoardChange();
listenforTheirBoardChange();
}
})
} else {
thisGameUrl.once('value', function(g){
if($.inArray(2,g.val().gameBoard2) !== -1){
thisGameUrl.off('child_changed');
listenforMyBoardChange();
listenforTheirBoardChange();
}
})
}
});
});
}
function listenforMyBoardChange(){
findCurrentGameId(gamesFb, function(foundGame){
var thisGameUrl = new Firebase (url + 'games/' + foundGame[0][0]);
function otherPlayer(){if(foundGame[0][1] === 1){return 2}else{return 1}};
var otherGameboard = new Firebase (url + 'games/' + foundGame[0][0] + '/gameboard'+otherPlayer());
var myGameboard = new Firebase (url + 'games/' + foundGame[0][0] + '/gameboard'+foundGame[0][1]);
thisGameUrl.on('child_changed', function(childsnap){
var snap = childsnap.val();
if(otherPlayer()===1){
thisGameUrl.once('value', function(g){
var mygb = g.val().gameBoard2;
appendTheirGuessesGameboard(mygb);
checkBoardForShips(mygb);
})
} else {
thisGameUrl.once('value', function(g){
var mygb = g.val().gameBoard1;
appendTheirGuessesGameboard(mygb);
checkBoardForShips(mygb);
})
}
});
});
}
function listenforTheirBoardChange(){
findCurrentGameId(gamesFb, function(foundGame){
var thisGameUrl = new Firebase (url + 'games/' + foundGame[0][0]);
function otherPlayer(){if(foundGame[0][1] === 1){return 2}else{return 1}};
var otherGameboard = new Firebase (url + 'games/' + foundGame[0][0] + '/gameboard'+otherPlayer());
var myGameboard = new Firebase (url + 'games/' + foundGame[0][0] + '/gameboard'+foundGame[0][1]);
thisGameUrl.on('child_changed', function(childsnap){
var snap = childsnap.val();
if(otherPlayer()===1){
thisGameUrl.once('value', function(g){
var mygb = g.val().gameBoard1;
appendMyGuessesGameboard(mygb);
checkBoardForShips(mygb);
})
} else {
thisGameUrl.once('value', function(g){
var mygb = g.val().gameBoard2;
appendMyGuessesGameboard(mygb);
checkBoardForShips(mygb);
})
}
});
});
}
//////////////////////////////////////////////////////
////////////////// Click Events //////////////////////
//////////////////////////////////////////////////////
// get the current player
$playerName.click( function () {
if ($('#playerNameValue').val()) {
$chosenName = $('#playerNameValue').val();
$('#playerName').toggleClass('hidden');
$('#newGame').toggleClass('hidden');
$('#playerNameValue').toggleClass('hidden');
}
});
// send user to an available or empty game
$('#newGame').click(function () {
$('#newGame').toggleClass('hidden');
$('#newGame').toggleClass('unclicked');
$('.ship-controls').toggleClass('hidden');
checkGames((function(avaGames){
if (avaGames[0]) {
var thisGame = new Firebase (url + 'games/' + avaGames[0] + '/user2');
thisGame.set($chosenName);
listenforShipPlacement();
} //else {gamesFb.push(createEmptyGame($chosenName))}
}), function(){
findCurrentGameId(gamesFb, function(foundGame){
if(!foundGame[0]) {
gamesFb.push(createEmptyGame($chosenName));
$('.game-status').toggleClass('hidden');
listenForUser2();
}
});
});
});
function gameBoardClick() {
$('.theirBoard .cell').click(function(){
var $thisCell = $(this);
findCurrentGameId(gamesFb, function(foundGame){
var thisGameUrl = new Firebase (url + 'games/' + foundGame[0][0]),
thisGameUserTurn = new Firebase (url + 'games/' + foundGame[0][0] + '/userTurn');
function otherPlayer(){if(foundGame[0][1] === 1){return 2}else{return 1}};
var theirGameboard = new Firebase (url + 'games/' + foundGame[0][0] + '/gameBoard' + otherPlayer());
//the function to check to see if it is a hit or miss should go here
//it compares the cell clicked to 'theirGameboard'
//it should return a gameboard array of 'x''s,'m''s, and 0's which is passed into the appendYourGuessesGameboard
//append computed guesses array to the right gameboard
//appendYourGuessesGameboard(hitOrMissArray);
var $target = $('.theirBoard .cell').index($thisCell);
thisGameUrl.once('value', function(res){
var val = res.val();
function findUser(){
if(val.userTurn === 2){return val.user2} else {return val.user1}
}
if($chosenName === findUser()){
theirGameboard.once('value', function(gb){
var gbFound = gb.val();
if (gbFound[$target] === 0) {
gbFound.splice($target, 1, 'm');
} else if (gbFound[$target] > 0) {
gbFound.splice($target, 1, 'x');
}
sendBoardToFb(otherPlayer(), gbFound);
});
// theirGameboard.once('value', function(gb){
// var updatedGb = gb.val();
// appendMyGuessesGameboard(updatedGb);
// });
switchTurn(foundGame[0][0]);
} else {}
});
});
});
} // end function gameBoardClick
gameBoardClick();
// Click a cell to place a ship if placement is valid
$('.myBoard .cell').click(function() {
var $cell = $(this);
if ($cell.hasClass('ship')) {
console.log('ship already placed here');
} else if ($('#newGame').hasClass('unclicked')) {
console.log('click New Game before placing ships');
} else {
createBoardPosition($cell);
}
});
// Send player's completed board state array to firebase
$('.myBoard').click(function() {
if ($('.placed').length === 5) {
findCurrentGameId(gamesFb, function(foundGame){
if (foundGame[0]) {
sendBoardToFb(foundGame[0][1], myBoardPositions);
console.log('board sent to firebase');
$('.myBoard').unbind('click');
} else {
console.log('could not find game, create a new game first');
}
});
}
});
// Firebase reset switch for clearing games
$('#resetFirebase').click(function () {
fb.remove();
});
// Rotate ship
$('#rotate').click(function() {
$('.ship-list').toggleClass('vertical');
});
// Cycle through ships during placement
$('.myBoard').click(function() {
var $shipPlaced = $('.ship-controls').find('.current').hasClass('placed');
if ($shipPlaced) {
$('.ship-controls').find('.current').next().toggleClass('hidden current');
$('.ship-controls').find('.current').first().toggleClass('hidden current');
} else {
console.log('cannot place ship here');
}
}); | kylemcco/jengaship | app/scripts/index.js | JavaScript | mit | 19,418 |
require_relative "test_helper"
class TestService < Mailkick::Service
def opt_outs
[
{email: "test@example.com", time: Time.current, reason: "bounce"},
{email: "test2@example.com", time: 1.day.ago, reason: "spam"}
]
end
end
class ServiceTest < Minitest::Test
def setup
super
Mailkick.services = [TestService.new]
end
def teardown
super
Mailkick.services = []
end
def test_process_opt_outs
user = User.create!(email: "test@example.com")
user.subscribe("sales")
user2 = User.create!(email: "test2@example.com")
user2.subscribe("sales")
previous_method = Mailkick.process_opt_outs_method
begin
Mailkick.process_opt_outs_method = lambda do |opt_outs|
emails = opt_outs.map { |v| v[:email] }
subscribers = User.includes(:mailkick_subscriptions).where(email: emails).index_by(&:email)
opt_outs.each do |opt_out|
subscriber = subscribers[opt_out[:email]]
next unless subscriber
subscriber.mailkick_subscriptions.each do |subscription|
subscription.destroy if subscription.created_at < opt_out[:time]
end
end
end
Mailkick.fetch_opt_outs
refute user.subscribed?("sales")
assert user2.subscribed?("sales")
ensure
Mailkick.process_opt_outs_method = previous_method
end
end
def test_not_configured
error = assert_raises do
Mailkick.fetch_opt_outs
end
assert_equal "process_opt_outs_method not defined", error.message
end
end
| ankane/mailkick | test/service_test.rb | Ruby | mit | 1,549 |
<?php
namespace {AppNamespace}Components\{ComponentName};
use Teepluss\Component\BaseComponent;
use Illuminate\Foundation\Application as Application;
use Teepluss\Component\Contracts\BaseComponent as BaseComponentContract;
class {ComponentName} extends BaseComponent implements BaseComponentContract
{
/**
* Application.
*
* @var \Illuminate\Foundation\Application
*/
protected $app;
/**
* Component namespace.
*
* @var string
*/
protected $namespace = '{ComponentNamespace}';
/**
* Component arguments.
*
* @var mixed
*/
protected $arguments;
/**
* Component new instance.
*
* @param \Illuminate\Foundation\Application $app
* @param mixed $arguments
*/
public function __construct(Application $app, $arguments = array())
{
parent::__construct($app, $arguments);
}
/**
* Prepare your code here!
*
* @return void
*/
final public function prepare()
{
// Example add internal assets.
// $this->script('name-1', 'script.js');
// $this->script('name-2', 'script-2.js', ['name-1']);
// Example add external assets.
// $this->script('name-e1', '//code.jquery.com/jquery-2.1.3.min.js');
// $this->style('name-e2', '//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css', ['name-e1']);
$arguments = array_merge($this->arguments, [
'component' => $this->getComponentName()
]);
$this->view('index', $arguments);
return $this;
}
}
| teepluss/laravel-component | src/templates/component/ExampleComponent.php | PHP | mit | 1,609 |
<?php
return array (
'id' => 'alltel_ppc6800_ver1',
'fallback' => 'sprint_ppc6800_ver1_subie711',
'capabilities' =>
array (
'brand_name' => 'HTC',
'model_extra_info' => 'Alltel',
'playback_acodec_amr' => 'nb',
'playback_wmv' => '7',
),
);
| cuckata23/wurfl-data | data/alltel_ppc6800_ver1.php | PHP | mit | 266 |
// Copyright (c) 2017 AB4D d.o.o.
//
// 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.
//
// Based on OculusWrap project created by MortInfinite and licensed as Ms-PL (https://oculuswrap.codeplex.com/)
using System;
namespace Ab3d.OculusWrap
{
/// <summary>
/// Specifies sensor flags.
/// </summary>
/// <see cref="TrackerPose"/>
[Flags]
public enum TrackerFlags
{
/// <summary>
/// No flags.
/// </summary>
None = 0,
/// <summary>
/// The sensor is present, else the sensor is absent or offline.
/// </summary>
Connected = 0x0020,
/// <summary>
/// The sensor has a valid pose, else the pose is unavailable.
/// This will only be set if TrackerFlags.Connected is set.
/// </summary>
PoseTracked = 0x0004,
}
} | ab4d/Ab3d.OculusWrap | Ab3d.OculusWrap/Ab3d.OculusWrap/TrackerFlags.cs | C# | mit | 1,882 |
#include "googletest/googletest/include/gtest/gtest.h"
#include "main.h"
#include "mocks/mtxdb.h"
#include "wallet.h"
// how many times to run all the tests to have a chance to catch errors that only show up with particular
// random shuffles
#define RUN_TESTS 100
// some tests fail 1% of the time due to bad luck.
// we repeat those tests this many times and only complain if all iterations of the test fail
#define RANDOM_REPEATS 5
using namespace std;
typedef set<pair<const CWalletTx*, unsigned int>> CoinSet;
static CWallet wallet;
static vector<COutput> vCoins;
static void add_coin(int64_t nValue, int nAge = 6 * 24, bool fIsFromMe = false, int nInput = 0)
{
static int i;
CTransaction tx;
tx.nLockTime = i++; // so all transactions get different hashes
tx.vout.resize(nInput + 1);
tx.vout[nInput].nValue = nValue;
CWalletTx* wtx = new CWalletTx(&wallet, tx);
if (fIsFromMe) {
// IsFromMe() returns (GetDebit() > 0), and GetDebit() is 0 if vin.empty(),
// so stop vin being empty, and cache a non-zero Debit to fake out IsFromMe()
wtx->vin.resize(1);
wtx->c_DebitCached = 1;
}
COutput output(wtx, nInput, nAge);
vCoins.push_back(output);
}
static void empty_wallet(void)
{
for (COutput output : vCoins)
delete output.tx;
vCoins.clear();
}
static bool equal_sets(CoinSet a, CoinSet b)
{
pair<CoinSet::iterator, CoinSet::iterator> ret = mismatch(a.begin(), a.end(), b.begin());
return ret.first == a.end() && ret.second == b.end();
}
TEST(wallet_tests, coin_selection_tests)
{
boost::shared_ptr<mTxDB> dbMock = boost::make_shared<mTxDB>();
EXPECT_CALL(*dbMock, GetBestChainHeight())
.WillRepeatedly(testing::Return(boost::make_optional<int>(0)));
static CoinSet setCoinsRet, setCoinsRet2;
static int64_t nValueRet;
// test multiple times to allow for differences in the shuffle order
for (int i = 0; i < RUN_TESTS; i++) {
empty_wallet();
// with an empty wallet we can't even pay one cent
EXPECT_TRUE(!wallet.SelectCoinsMinConf(*dbMock, 1 * CENT, GetAdjustedTime(), 1, 6, vCoins,
setCoinsRet, nValueRet));
add_coin(1 * CENT, 4); // add a new 1 cent coin
// with a new 1 cent coin, we still can't find a mature 1 cent
EXPECT_TRUE(!wallet.SelectCoinsMinConf(*dbMock, 1 * CENT, GetAdjustedTime(), 1, 6, vCoins,
setCoinsRet, nValueRet));
// but we can find a new 1 cent
EXPECT_TRUE(wallet.SelectCoinsMinConf(*dbMock, 1 * CENT, GetAdjustedTime(), 1, 1, vCoins,
setCoinsRet, nValueRet));
EXPECT_EQ(nValueRet, 1 * CENT);
add_coin(2 * CENT); // add a mature 2 cent coin
// we can't make 3 cents of mature coins
EXPECT_TRUE(!wallet.SelectCoinsMinConf(*dbMock, 3 * CENT, GetAdjustedTime(), 1, 6, vCoins,
setCoinsRet, nValueRet));
// we can make 3 cents of new coins
EXPECT_TRUE(wallet.SelectCoinsMinConf(*dbMock, 3 * CENT, GetAdjustedTime(), 1, 1, vCoins,
setCoinsRet, nValueRet));
EXPECT_EQ(nValueRet, 3 * CENT);
add_coin(5 * CENT); // add a mature 5 cent coin,
add_coin(10 * CENT, 3, true); // a new 10 cent coin sent from one of our own addresses
add_coin(20 * CENT); // and a mature 20 cent coin
// now we have new: 1+10=11 (of which 10 was self-sent), and mature: 2+5+20=27. total = 38
// we can't make 38 cents only if we disallow new coins:
EXPECT_TRUE(!wallet.SelectCoinsMinConf(*dbMock, 38 * CENT, GetAdjustedTime(), 1, 6, vCoins,
setCoinsRet, nValueRet));
// we can't even make 37 cents if we don't allow new coins even if they're from us
EXPECT_TRUE(!wallet.SelectCoinsMinConf(*dbMock, 38 * CENT, GetAdjustedTime(), 6, 6, vCoins,
setCoinsRet, nValueRet));
// but we can make 37 cents if we accept new coins from ourself
EXPECT_TRUE(wallet.SelectCoinsMinConf(*dbMock, 37 * CENT, GetAdjustedTime(), 1, 6, vCoins,
setCoinsRet, nValueRet));
EXPECT_EQ(nValueRet, 37 * CENT);
// and we can make 38 cents if we accept all new coins
EXPECT_TRUE(wallet.SelectCoinsMinConf(*dbMock, 38 * CENT, GetAdjustedTime(), 1, 1, vCoins,
setCoinsRet, nValueRet));
EXPECT_EQ(nValueRet, 38 * CENT);
// try making 34 cents from 1,2,5,10,20 - we can't do it exactly
EXPECT_TRUE(wallet.SelectCoinsMinConf(*dbMock, 34 * CENT, GetAdjustedTime(), 1, 1, vCoins,
setCoinsRet, nValueRet));
EXPECT_GT(nValueRet, 34 * CENT); // but should get more than 34 cents
EXPECT_EQ(setCoinsRet.size(), (unsigned)3); // the best should be 20+10+5. it's incredibly
// unlikely the 1 or 2 got included (but possible)
// when we try making 7 cents, the smaller coins (1,2,5) are enough. We should see just 2+5
EXPECT_TRUE(wallet.SelectCoinsMinConf(*dbMock, 7 * CENT, GetAdjustedTime(), 1, 1, vCoins,
setCoinsRet, nValueRet));
EXPECT_EQ(nValueRet, 7 * CENT);
EXPECT_EQ(setCoinsRet.size(), (unsigned)2);
// when we try making 8 cents, the smaller coins (1,2,5) are exactly enough.
EXPECT_TRUE(wallet.SelectCoinsMinConf(*dbMock, 8 * CENT, GetAdjustedTime(), 1, 1, vCoins,
setCoinsRet, nValueRet));
EXPECT_TRUE(nValueRet == 8 * CENT);
EXPECT_EQ(setCoinsRet.size(), (unsigned)3);
// when we try making 9 cents, no subset of smaller coins is enough, and we get the next bigger
// coin (10)
EXPECT_TRUE(wallet.SelectCoinsMinConf(*dbMock, 9 * CENT, GetAdjustedTime(), 1, 1, vCoins,
setCoinsRet, nValueRet));
EXPECT_EQ(nValueRet, 10 * CENT);
EXPECT_EQ(setCoinsRet.size(), (unsigned)1);
// now clear out the wallet and start again to test choosing between subsets of smaller coins and
// the next biggest coin
empty_wallet();
add_coin(6 * CENT);
add_coin(7 * CENT);
add_coin(8 * CENT);
add_coin(20 * CENT);
add_coin(30 * CENT); // now we have 6+7+8+20+30 = 71 cents total
// check that we have 71 and not 72
EXPECT_TRUE(wallet.SelectCoinsMinConf(*dbMock, 71 * CENT, GetAdjustedTime(), 1, 1, vCoins,
setCoinsRet, nValueRet));
EXPECT_TRUE(!wallet.SelectCoinsMinConf(*dbMock, 72 * CENT, GetAdjustedTime(), 1, 1, vCoins,
setCoinsRet, nValueRet));
// now try making 16 cents. the best smaller coins can do is 6+7+8 = 21; not as good at the next
// biggest coin, 20
EXPECT_TRUE(wallet.SelectCoinsMinConf(*dbMock, 16 * CENT, GetAdjustedTime(), 1, 1, vCoins,
setCoinsRet, nValueRet));
EXPECT_EQ(nValueRet, 20 * CENT); // we should get 20 in one coin
EXPECT_EQ(setCoinsRet.size(), (unsigned)1);
add_coin(5 * CENT); // now we have 5+6+7+8+20+30 = 75 cents total
// now if we try making 16 cents again, the smaller coins can make 5+6+7 = 18 cents, better than
// the next biggest coin, 20
EXPECT_TRUE(wallet.SelectCoinsMinConf(*dbMock, 16 * CENT, GetAdjustedTime(), 1, 1, vCoins,
setCoinsRet, nValueRet));
EXPECT_EQ(nValueRet, 18 * CENT); // we should get 18 in 3 coins
EXPECT_EQ(setCoinsRet.size(), (unsigned)3);
add_coin(18 * CENT); // now we have 5+6+7+8+18+20+30
// and now if we try making 16 cents again, the smaller coins can make 5+6+7 = 18 cents, the same
// as the next biggest coin, 18
EXPECT_TRUE(wallet.SelectCoinsMinConf(*dbMock, 16 * CENT, GetAdjustedTime(), 1, 1, vCoins,
setCoinsRet, nValueRet));
EXPECT_EQ(nValueRet, 18 * CENT); // we should get 18 in 1 coin
EXPECT_EQ(setCoinsRet.size(),
(unsigned)1); // because in the event of a tie, the biggest coin wins
// now try making 11 cents. we should get 5+6
EXPECT_TRUE(wallet.SelectCoinsMinConf(*dbMock, 11 * CENT, GetAdjustedTime(), 1, 1, vCoins,
setCoinsRet, nValueRet));
EXPECT_EQ(nValueRet, 11 * CENT);
EXPECT_EQ(setCoinsRet.size(), (unsigned)2);
// check that the smallest bigger coin is used
add_coin(1 * COIN);
add_coin(2 * COIN);
add_coin(3 * COIN);
add_coin(4 * COIN); // now we have 5+6+7+8+18+20+30+100+200+300+400 = 1094 cents
EXPECT_TRUE(wallet.SelectCoinsMinConf(*dbMock, 95 * CENT, GetAdjustedTime(), 1, 1, vCoins,
setCoinsRet, nValueRet));
EXPECT_EQ(nValueRet, 1 * COIN); // we should get 1 BTC in 1 coin
EXPECT_EQ(setCoinsRet.size(), (unsigned)1);
EXPECT_TRUE(wallet.SelectCoinsMinConf(*dbMock, 195 * CENT, GetAdjustedTime(), 1, 1, vCoins,
setCoinsRet, nValueRet));
EXPECT_EQ(nValueRet, 2 * COIN); // we should get 2 BTC in 1 coin
EXPECT_EQ(setCoinsRet.size(), (unsigned)1);
// empty the wallet and start again, now with fractions of a cent, to test sub-cent change
// avoidance
empty_wallet();
add_coin(0.1 * CENT);
add_coin(0.2 * CENT);
add_coin(0.3 * CENT);
add_coin(0.4 * CENT);
add_coin(0.5 * CENT);
// try making 1 cent from 0.1 + 0.2 + 0.3 + 0.4 + 0.5 = 1.5 cents
// we'll get sub-cent change whatever happens, so can expect 1.0 exactly
EXPECT_TRUE(wallet.SelectCoinsMinConf(*dbMock, 1 * CENT, GetAdjustedTime(), 1, 1, vCoins,
setCoinsRet, nValueRet));
EXPECT_EQ(nValueRet, 1 * CENT);
// but if we add a bigger coin, making it possible to avoid sub-cent change, things change:
add_coin(1111 * CENT);
// try making 1 cent from 0.1 + 0.2 + 0.3 + 0.4 + 0.5 + 1111 = 1112.5 cents
EXPECT_TRUE(wallet.SelectCoinsMinConf(*dbMock, 1 * CENT, GetAdjustedTime(), 1, 1, vCoins,
setCoinsRet, nValueRet));
EXPECT_EQ(nValueRet, 1 * CENT); // we should get the exact amount
// if we add more sub-cent coins:
add_coin(0.6 * CENT);
add_coin(0.7 * CENT);
// and try again to make 1.0 cents, we can still make 1.0 cents
EXPECT_TRUE(wallet.SelectCoinsMinConf(*dbMock, 1 * CENT, GetAdjustedTime(), 1, 1, vCoins,
setCoinsRet, nValueRet));
EXPECT_EQ(nValueRet, 1 * CENT); // we should get the exact amount
// run the 'mtgox' test (see
// http://blockexplorer.com/tx/29a3efd3ef04f9153d47a990bd7b048a4b2d213daaa5fb8ed670fb85f13bdbcf)
// they tried to consolidate 10 50k coins into one 500k coin, and ended up with 50k in change
empty_wallet();
for (int j = 0; j < 20; j++)
add_coin(50000 * COIN);
EXPECT_TRUE(wallet.SelectCoinsMinConf(*dbMock, 500000 * COIN, GetAdjustedTime(), 1, 1, vCoins,
setCoinsRet, nValueRet));
EXPECT_EQ(nValueRet, 500000 * COIN); // we should get the exact amount
EXPECT_EQ(setCoinsRet.size(), (unsigned)10); // in ten coins
// if there's not enough in the smaller coins to make at least 1 cent change (0.5+0.6+0.7
// < 1.0+1.0), we need to try finding an exact subset anyway
// sometimes it will fail, and so we use the next biggest coin:
empty_wallet();
add_coin(0.5 * CENT);
add_coin(0.6 * CENT);
add_coin(0.7 * CENT);
add_coin(1111 * CENT);
EXPECT_TRUE(wallet.SelectCoinsMinConf(*dbMock, 1 * CENT, GetAdjustedTime(), 1, 1, vCoins,
setCoinsRet, nValueRet));
EXPECT_EQ(nValueRet, 1111 * CENT); // we get the bigger coin
EXPECT_EQ(setCoinsRet.size(), (unsigned)1);
// but sometimes it's possible, and we use an exact subset (0.4 + 0.6 = 1.0)
empty_wallet();
add_coin(0.4 * CENT);
add_coin(0.6 * CENT);
add_coin(0.8 * CENT);
add_coin(1111 * CENT);
EXPECT_TRUE(wallet.SelectCoinsMinConf(*dbMock, 1 * CENT, GetAdjustedTime(), 1, 1, vCoins,
setCoinsRet, nValueRet));
EXPECT_EQ(nValueRet, 1 * CENT); // we should get the exact amount
EXPECT_EQ(setCoinsRet.size(), (unsigned)2); // in two coins 0.4+0.6
// test avoiding sub-cent change
empty_wallet();
add_coin(0.0005 * COIN);
add_coin(0.01 * COIN);
add_coin(1 * COIN);
// trying to make 1.0001 from these three coins
EXPECT_TRUE(wallet.SelectCoinsMinConf(*dbMock, 1.0001 * COIN, GetAdjustedTime(), 1, 1, vCoins,
setCoinsRet, nValueRet));
EXPECT_EQ(nValueRet, 1.0105 * COIN); // we should get all coins
EXPECT_EQ(setCoinsRet.size(), (unsigned)3);
// but if we try to make 0.999, we should take the bigger of the two small coins to avoid
// sub-cent change
EXPECT_TRUE(wallet.SelectCoinsMinConf(*dbMock, 0.999 * COIN, GetAdjustedTime(), 1, 1, vCoins,
setCoinsRet, nValueRet));
EXPECT_EQ(nValueRet, 1.01 * COIN); // we should get 1 + 0.01
EXPECT_EQ(setCoinsRet.size(), (unsigned)2);
// test randomness
{
empty_wallet();
for (int i2 = 0; i2 < 100; i2++)
add_coin(COIN);
// picking 50 from 100 coins doesn't depend on the shuffle,
// but does depend on randomness in the stochastic approximation code
EXPECT_TRUE(wallet.SelectCoinsMinConf(*dbMock, 50 * COIN, GetAdjustedTime(), 1, 6, vCoins,
setCoinsRet, nValueRet));
EXPECT_TRUE(wallet.SelectCoinsMinConf(*dbMock, 50 * COIN, GetAdjustedTime(), 1, 6, vCoins,
setCoinsRet2, nValueRet));
EXPECT_TRUE(!equal_sets(setCoinsRet, setCoinsRet2));
int fails = 0;
for (int j = 0; j < RANDOM_REPEATS; j++) {
// selecting 1 from 100 identical coins depends on the shuffle; this test will fail 1% of
// the time run the test RANDOM_REPEATS times and only complain if all of them fail
EXPECT_TRUE(wallet.SelectCoinsMinConf(*dbMock, COIN, GetAdjustedTime(), 1, 6, vCoins,
setCoinsRet, nValueRet));
EXPECT_TRUE(wallet.SelectCoinsMinConf(*dbMock, COIN, GetAdjustedTime(), 1, 6, vCoins,
setCoinsRet2, nValueRet));
if (equal_sets(setCoinsRet, setCoinsRet2))
fails++;
}
EXPECT_NE(fails, RANDOM_REPEATS);
// add 75 cents in small change. not enough to make 90 cents,
// then try making 90 cents. there are multiple competing "smallest bigger" coins,
// one of which should be picked at random
add_coin(5 * CENT);
add_coin(10 * CENT);
add_coin(15 * CENT);
add_coin(20 * CENT);
add_coin(25 * CENT);
fails = 0;
for (int j = 0; j < RANDOM_REPEATS; j++) {
// selecting 1 from 100 identical coins depends on the shuffle; this test will fail 1% of
// the time run the test RANDOM_REPEATS times and only complain if all of them fail
EXPECT_TRUE(wallet.SelectCoinsMinConf(*dbMock, 90 * CENT, GetAdjustedTime(), 1, 6,
vCoins, setCoinsRet, nValueRet));
EXPECT_TRUE(wallet.SelectCoinsMinConf(*dbMock, 90 * CENT, GetAdjustedTime(), 1, 6,
vCoins, setCoinsRet2, nValueRet));
if (equal_sets(setCoinsRet, setCoinsRet2))
fails++;
}
EXPECT_NE(fails, RANDOM_REPEATS);
}
empty_wallet();
}
}
| NeblioTeam/neblio | wallet/test/wallet_tests.cpp | C++ | mit | 16,924 |
# coding:utf-8
require 'test_helper'
class VacancyTest < ActiveSupport::TestCase
test 'is invalid without a vacancy_id' do
vacancy = Factory.build(:vacancy, :vacancy_id => nil)
assert_equal false, vacancy.valid?
end
test '.to_solr_document' do
vacancy = Factory.build(:vacancy,
:vacancy_id => "TES/1234",
:vacancy_title => "Testing Vacancy",
:soc_code => "1234",
:latitude => 51.0,
:longitude => 1.0,
:location_name => "Testing Town, County",
:is_permanent => true,
:hours => 25,
:hours_display_text => "25 hours, flexible working",
:wage_display_text => "Lots of cash",
:vacancy_description => "Work for us",
:employer_name => "Alphagov",
:how_to_apply => "Send us an email",
:received_on => Date.today
)
document = DelSolr::Document.new
document.add_field 'id', "TES/1234"
document.add_field 'title', "Testing Vacancy", :cdata => true
document.add_field 'soc_code', '1234'
document.add_field 'location', [51.0, 1.0].join(",")
document.add_field 'location_name', "Testing Town, County", :cdata => true
document.add_field 'is_permanent', true
document.add_field 'hours', 25
document.add_field 'hours_display_text', "25 hours, flexible working", :cdata => true
document.add_field 'wage_display_text', "Lots of cash", :cdata => true
document.add_field 'received_on', "#{Date.today.beginning_of_day.iso8601}Z"
document.add_field 'vacancy_description', "Work for us", :cdata => true
document.add_field 'employer_name', "Alphagov", :cdata => true
document.add_field 'how_to_apply', 'Send us an email', :cdata => true
document.add_field 'eligability_criteria', '', :cdata => true
assert_equal document.xml, vacancy.to_solr_document.xml
end
test '.send_to_solr!' do
vacancy = Factory.build(:vacancy)
vacancy.stubs(:to_solr_document).returns(mock())
$solr.expects(:update!).with(vacancy.to_solr_document, :commitWithin => 300000).returns(true)
assert_equal true, vacancy.send_to_solr!
end
test '.delete_from_solr' do
vacancy = Factory.build(:vacancy)
$solr.expects(:delete).with(vacancy.vacancy_id).returns(true)
assert_equal true, vacancy.delete_from_solr
end
test '.import_details_from_hash' do
vacancy_hash = {:currency=>"GBP",
:date_received=>"30082011",
:distance_sort_order_id=>"2396.97008934328",
:es_vacancy=>"Y",
:hours=>"35",
:hours_display_text=>"37.5 HOURS OVER 5 DAYS",
:hours_qualifier=>"per week",
:is_national=>false,
:is_regional=>false,
:location=>{
:distance_from_origin=>"2396.97008934328",
:latitude=>"50.986008297409",
:longitude=>"0.9740371746526",
:origin_latitude=>"51",
:origin_longitude=>"1",
:location_name=>"NEW ROMNEY, KENT"},
:location_display_text=>"NEW ROMNEY, KENT",
:order_id=>"1",
:perm_temp=>"P",
:quality=>"86",
:received_on=> Time.utc(2011, 8, 30, 0, 0, 0),
:soc_code=>"3543",
:vacancy_detail=>{
:hours=>"0",
:soc_code=>"0"},
:vacancy_id=>"FOK/12116",
:vacancy_title=>"CHARITY FUNDRAISER",
:wage=>"See details",
:wage_display_text=>"£255 TO £1000 PER WEEK",
:wage_qualifier=>"NK",
:wage_sort_order_id=>"20"}
vacancy = Vacancy.new
vacancy.import_details_from_hash(vacancy_hash)
assert_equal vacancy.vacancy_title, vacancy_hash[:vacancy_title]
assert_equal vacancy.received_on, vacancy_hash[:received_on]
assert_equal vacancy.soc_code, vacancy_hash[:soc_code]
assert_equal vacancy.wage, vacancy_hash[:wage]
assert_equal vacancy.wage_qualifier, vacancy_hash[:wage_qualifier]
assert_equal vacancy.wage_display_text, vacancy_hash[:wage_display_text]
assert_equal vacancy.currency, vacancy_hash[:currency]
assert_equal vacancy.is_national, vacancy_hash[:is_national]
assert_equal vacancy.is_regional, vacancy_hash[:is_regional]
assert_equal vacancy.hours, vacancy_hash[:hours].to_i
assert_equal vacancy.hours_qualifier, vacancy_hash[:hours_qualifier]
assert_equal vacancy.hours_display_text, vacancy_hash[:hours_display_text]
assert_equal vacancy.location_name, vacancy_hash[:location][:location_name]
assert_equal vacancy.latitude, vacancy_hash[:location][:latitude].to_f
assert_equal vacancy.longitude, vacancy_hash[:location][:longitude].to_f
assert_equal vacancy.is_permanent, true
end
end
| gds-attic/jobs | test/unit/vacancy_test.rb | Ruby | mit | 5,259 |
import { Durations } from '../../Constants.js';
const DrawCard = require('../../drawcard.js');
const AbilityDsl = require('../../abilitydsl.js');
class MatsuKoso extends DrawCard {
setupCardAbilities() {
this.action({
title: 'Lower military skill',
condition: context => context.source.isParticipating(),
gameAction: AbilityDsl.actions.cardLastingEffect(context => ({
target: context.game.currentConflict.getParticipants(),
duration: Durations.UntilEndOfConflict,
effect: AbilityDsl.effects.modifyMilitarySkill(card => isNaN(card.printedPoliticalSkill) ? 0 : -card.printedPoliticalSkill)
})),
effect: 'lower the military skill of {1} by their respective pirnted political skill',
effectArgs: context => [context.game.currentConflict.getParticipants()]
});
}
}
MatsuKoso.id = 'matsu-koso';
module.exports = MatsuKoso;
| gryffon/ringteki | server/game/cards/12-SoW/MastuKoso.js | JavaScript | mit | 964 |
package typhon
import (
"context"
"net/http"
"testing"
"github.com/monzo/terrors"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestExpirationFilter(t *testing.T) {
t.Parallel()
svc := Service(func(req Request) Response {
return req.Response("ok")
})
svc = svc.Filter(ExpirationFilter)
// An unexpired request should be allowed through
req := NewRequest(context.Background(), "GET", "/", nil)
rsp := svc(req)
assert.NoError(t, rsp.Error)
assert.Equal(t, http.StatusOK, rsp.StatusCode)
b, err := rsp.BodyBytes(true)
require.NoError(t, err)
assert.Equal(t, []byte(`"ok"`+"\n"), b)
// An expired request should be rejected
ctx, ccl := context.WithCancel(context.Background())
ccl()
req.Context = ctx
rsp = svc(req)
assert.Error(t, rsp.Error)
terr := terrors.Wrap(rsp.Error, nil).(*terrors.Error)
terrExpect := terrors.BadRequest("expired", "Request has expired", nil)
assert.Equal(t, terrExpect.Message, terr.Message)
assert.Equal(t, terrExpect.Code, terr.Code)
}
| monzo/typhon | expire_test.go | GO | mit | 1,033 |
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <queue>
#include "queue.h"
#include "../test_helpers.h"
template<template<typename T> class ConcreteQueue>
void test_queue(TestHelper& th) {
{
th.message("Default construction");
ConcreteQueue<int> q;
th.tassert();
th.message("Destruction");
}
th.tassert();
{
ConcreteQueue<int> q;
th.tassert(q.empty(), true, "Initially empty");
th.tassert(q.size(), (std::size_t)0, "Initially size is 0");
q.enqueue(7);
th.tassert(q.empty(), false, "Not empty after pushing element 7");
th.tassert(q.size(), (std::size_t)1, "Size is 1");
q.enqueue(8);
th.tassert(q.empty(), false, "Not empty after pushing element 8");
th.tassert(q.size(), (std::size_t)2, "Size is 2");
{
th.message("Copy construction");
ConcreteQueue<int> cq(q);
th.tassert();
th.tassert(q.to_std_queue() == cq.to_std_queue(), true, "Equal queues");
th.message("Destruction");
}
th.tassert();
{
th.message("Operator=");
ConcreteQueue<int> oeq;
oeq = q;
th.tassert();
th.tassert(q.to_std_queue() == oeq.to_std_queue(), true, "Equal queues");
th.message("Destruction");
}
th.tassert();
{
th.message("Move semantics construction");
ConcreteQueue<int> mq(ConcreteQueue<int>{q});
th.tassert();
th.tassert(q.to_std_queue() == mq.to_std_queue(), true, "Equal queues");
th.message("Destruction");
}
th.tassert();
{
th.message("Pop");
int last = q.dequeue();
th.tassert();
th.tassert(last, 7, "popped == 7");
th.tassert(q.empty(), false, "Not empty");
th.tassert(q.size(), (std::size_t)1, "Size is 1");
}
{
th.message("Pop");
int last = q.dequeue();
th.tassert();
th.tassert(last, 8, "popped == 8");
th.tassert(q.empty(), true, "Empty");
th.tassert(q.size(), (std::size_t)0, "Size is 0");
}
}
std::srand((unsigned int)std::time(0));
{
ConcreteQueue<int> q;
std::queue<int> stdq;
th.message("Stress test push");
for(int i = 0; i < 900; ++i) {
th.tassert(q.size(), stdq.size(), "Size", true);
th.tassert(q.empty(), stdq.empty(), "Empty", true);
int r = std::rand();
q.enqueue(r);
stdq.push(r);
th.tassert(q.to_std_queue() == stdq, true, "Equal queues", true);
}
th.tassert();
th.message("Stress test pop");
for(int i = 0; i < 500; ++i) {
th.tassert(q.size(), stdq.size(), "Size", true);
th.tassert(q.empty(), stdq.empty(), "Empty", true);
th.tassert(q.to_std_queue() == stdq, true, "Equal queues", true);
q.dequeue();
stdq.pop();
}
th.tassert();
th.message("Stress test past end");
for(int i = 0; i < 300; ++i) {
th.tassert(q.size(), stdq.size(), "Size", true);
th.tassert(q.empty(), stdq.empty(), "Empty", true);
int r = std::rand();
q.enqueue(r);
stdq.push(r);
th.tassert(q.to_std_queue() == stdq, true, "Equal queues", true);
}
th.tassert();
th.message("Stress test pop");
for(int i = 0; i < 500; ++i) {
th.tassert(q.size(), stdq.size(), "Size", true);
th.tassert(q.empty(), stdq.empty(), "Empty", true);
th.tassert(q.to_std_queue() == stdq, true, "Equal queues", true);
q.dequeue();
stdq.pop();
}
th.tassert();
}
}
int main(int argc, char const *argv[]) {
TestHelper th;
std::cout << "[[ List-based Queue ]]" << std::endl << std::endl;
test_queue<ListQueue>(th);
std::cout << std::endl << "[[ Circular-buffer-based Queue ]]" << std::endl << std::endl;
test_queue<CircularBufferQueue>(th);
th.summary();
return 0;
}
| fcarreiro/crashingthecode | structures/queue.test.cc | C++ | mit | 3,768 |
//
// Copyright (c) 2016 Terry Seyler
//
// Distributed under the MIT License
// See accompanying file LICENSE.md
//
#include <boost/bind.hpp>
#include <core/server/proto_tcp_text_server.hpp>
#include <core/client/proto_tcp_text_client.hpp>
using namespace boost::asio::ip;
namespace proto_net
{
using namespace client;
namespace server
{
proto_tcp_text_server*
proto_tcp_text_server::proto_tcp_text_server_cast(proto_service_ptr ps_ptr)
{
return dynamic_cast<proto_tcp_text_server*>(ps_ptr.get());
}
proto_tcp_text_server::proto_tcp_text_server(unsigned short port_num /* = 80*/)
: proto_tcp_server(port_num)
{}
proto_tcp_text_server::proto_tcp_text_server(proto_net_service_ptr ps_service,
unsigned short port_num /*= 80 */)
: proto_tcp_server(ps_service, port_num)
{}
proto_tcp_text_server::proto_tcp_text_server(proto_tcp_text_server& ps)
: proto_tcp_server(dynamic_cast<proto_tcp_server&>(ps))
{}
void
proto_tcp_text_server::ps_start_accept(proto_net_pipeline& ps_pipeline, size_t buffer_size)
{
proto_tcp_text_session* new_session = new proto_tcp_text_session(ps_service_, ps_pipeline, buffer_size);
acceptor_.async_accept(new_session->ps_socket(),
boost::bind(&proto_tcp_text_server::handle_accept, this, new_session,
boost::asio::placeholders::error));
}
void
proto_tcp_text_server::handle_accept(proto_tcp_text_session* session, const proto_net_error_code& error)
{
if (session)
{
proto_net_pipeline& pipeline = session->ps_pipeline(); // get the session before it gets destroyed below
proto_async_io* ds_io = pipeline.ps_proto_io(); // get the downstream io
if (ds_io)
{
proto_tcp_text_client* tcp_client = dynamic_cast<proto_tcp_text_client*>(ds_io); // we are tcp client?
if (tcp_client)
{
proto_net_pipeline& upstream_pipeline = tcp_client->ps_pipeline();
upstream_pipeline.ps_proto_io(session); // set the upstream io to the session
}
}
size_t buffer_size = session->ps_buffer_size();
notify_server_listeners(session);
if (!error)
session->ps_start();
else
delete session;
ps_start_accept(pipeline, buffer_size);
}
else {} // we will drop out because there is no session and no io
}
}
}
| tseyler/proto-server | proto_server/core/server/proto_tcp_text_server.cpp | C++ | mit | 2,872 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
/*
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Microsoft.Rest.ClientRuntime.E2E.Tests")]
[assembly: AssemblyTrademark("")]
*/
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("4e9aeb40-026f-4ba1-a2db-c8e252305157")]
| JasonYang-MSFT/azure-sdk-for-net | src/SdkCommon/ClientRuntime/Test/ClientRuntime.E2E.Tests/Properties/AssemblyInfo.cs | C# | mit | 856 |
#!/usr/bin/env python
# Copyright (c) 2002-2003 ActiveState Corp.
# Author: Trent Mick (TrentM@ActiveState.com)
"""Test suite for which.py."""
import sys
import os
import re
import tempfile
import unittest
import testsupport
#XXX:TODO
# - def test_registry_success(self): ...App Paths setting
# - def test_registry_noexist(self):
# - test all the other options
# - test on linux
# - test the module API
class WhichTestCase(unittest.TestCase):
def setUp(self):
"""Create a temp directory with a couple test "commands".
The temp dir can be added to the PATH, etc, for testing purposes.
"""
# Find the which.py to call.
whichPy = os.path.join(os.path.dirname(__file__),
os.pardir, "which.py")
self.which = sys.executable + " " + whichPy
# Setup the test environment.
self.tmpdir = tempfile.mktemp()
os.makedirs(self.tmpdir)
if sys.platform.startswith("win"):
self.testapps = ['whichtestapp1.exe',
'whichtestapp2.exe',
'whichtestapp3.wta']
else:
self.testapps = ['whichtestapp1', 'whichtestapp2']
for app in self.testapps:
path = os.path.join(self.tmpdir, app)
f = open(path, 'wb')
f.write('\n'.encode('ascii'))
f.close()
os.chmod(path, 0o755)
def tearDown(self):
testsupport.rmtree(self.tmpdir)
def test_opt_h(self):
output, error, retval = testsupport.run(self.which+' --h')
token = 'Usage:'.encode('ascii')
self.failUnless(output.find(token) != -1,
"'%s' was not found in 'which -h' output: '%s' "\
% (token, output))
self.failUnless(retval == 0,
"'which -h' did not return 0: retval=%d" % retval)
def test_opt_help(self):
output, error, retval = testsupport.run(self.which+' --help')
token = 'Usage:'.encode('ascii')
self.failUnless(output.find(token) != -1,
"'%s' was not found in 'which --help' output: '%s' "\
% (token, output))
self.failUnless(retval == 0,
"'which --help' did not return 0: retval=%d" % retval)
def test_opt_version(self):
output, error, retval = testsupport.run(self.which+' --version')
versionRe = re.compile("^which \d+\.\d+\.\d+$".encode('ascii'))
versionMatch = versionRe.search(output.strip())
self.failUnless(versionMatch,
"Version, '%s', from 'which --version' does not "\
"match pattern, '%s'."\
% (output.strip(), versionRe.pattern))
self.failUnless(retval == 0,
"'which --version' did not return 0: retval=%d"\
% retval)
def test_no_args(self):
output, error, retval = testsupport.run(self.which)
self.failUnless(retval == -1,
"'which' with no args should return -1: retval=%d"\
% retval)
def test_one_failure(self):
output, error, retval = testsupport.run(
self.which+' whichtestapp1')
self.failUnless(retval == 1,
"One failure did not return 1: retval=%d" % retval)
def test_two_failures(self):
output, error, retval = testsupport.run(
self.which+' whichtestapp1 whichtestapp2')
self.failUnless(retval == 2,
"Two failures did not return 2: retval=%d" % retval)
def _match(self, path1, path2):
#print "_match: %r =?= %r" % (path1, path2)
if sys.platform.startswith('win'):
path1 = os.path.normpath(os.path.normcase(path1))
path2 = os.path.normpath(os.path.normcase(path2))
path1 = os.path.splitext(path1)[0]
path2 = os.path.splitext(path2)[0]
return path1 == path2
else:
return os.path.samefile(path1, path2)
def test_one_success(self):
os.environ["PATH"] += os.pathsep + self.tmpdir
output, error, retval = testsupport.run(self.which+' -q whichtestapp1')
expectedOutput = os.path.join(self.tmpdir, "whichtestapp1")
self.failUnless(self._match(output.strip(), expectedOutput),
"Output, %r, and expected output, %r, do not match."\
% (output.strip(), expectedOutput))
self.failUnless(retval == 0,
"'which ...' should have returned 0: retval=%d" % retval)
def test_two_successes(self):
os.environ["PATH"] += os.pathsep + self.tmpdir
apps = ['whichtestapp1', 'whichtestapp2']
output, error, retval = testsupport.run(
self.which + ' -q ' + ' '.join(apps))
lines = output.strip().split("\n".encode('ascii'))
for app, line in zip(apps, lines):
expected = os.path.join(self.tmpdir, app)
self.failUnless(self._match(line, expected),
"Output, %r, and expected output, %r, do not match."\
% (line, expected))
self.failUnless(retval == 0,
"'which ...' should have returned 0: retval=%d" % retval)
if sys.platform.startswith("win"):
def test_PATHEXT_failure(self):
os.environ["PATH"] += os.pathsep + self.tmpdir
output, error, retval = testsupport.run(self.which+' whichtestapp3')
self.failUnless(retval == 1,
"'which ...' should have returned 1: retval=%d" % retval)
def test_PATHEXT_success(self):
os.environ["PATH"] += os.pathsep + self.tmpdir
os.environ["PATHEXT"] += os.pathsep + '.wta'
output, error, retval = testsupport.run(self.which+' whichtestapp3')
expectedOutput = os.path.join(self.tmpdir, "whichtestapp3")
self.failUnless(self._match(output.strip(), expectedOutput),
"Output, %r, and expected output, %r, do not match."\
% (output.strip(), expectedOutput))
self.failUnless(retval == 0,
"'which ...' should have returned 0: retval=%d" % retval)
def test_exts(self):
os.environ["PATH"] += os.pathsep + self.tmpdir
output, error, retval = testsupport.run(self.which+' -e .wta whichtestapp3')
expectedOutput = os.path.join(self.tmpdir, "whichtestapp3")
self.failUnless(self._match(output.strip(), expectedOutput),
"Output, %r, and expected output, %r, do not match."\
% (output.strip(), expectedOutput))
self.failUnless(retval == 0,
"'which ...' should have returned 0: retval=%d" % retval)
def suite():
"""Return a unittest.TestSuite to be used by test.py."""
return unittest.makeSuite(WhichTestCase)
if __name__ == "__main__":
unittest.main()
| fsys/which | test/test_which.py | Python | mit | 6,969 |
// tslint:disable:no-empty
import { Component, Input, OnInit } from '@angular/core';
/**
* Foo doc
*/
@Component({
selector: '[foo]',
template: '<button (click)="forTemplateOnly()">{{buttonTxt}}</button>',
exportAs: 'foo'
})
export class FooComponent implements OnInit {
@Input() buttonTxt;
constructor() {}
/**
* Only used in a template
*
* @internal
*/
forTemplateOnly() {
console.log('I was clicked!');
}
ngOnInit() {}
// tslint:disable-next-line:prefer-function-over-method
private _dontSerialize() {}
}
| valor-software/ng2-handsontable | scripts/docs/api-doc-test-cases/component-with-internal-methods.ts | TypeScript | mit | 553 |
package br.com.digituz.mailer.controller;
import br.com.digituz.mailer.model.Email;
import br.com.digituz.mailer.model.Message;
import br.com.digituz.mailer.service.EmailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* @author daniel
*/
@RestController
@RequestMapping("/api")
public class EmailController {
private static final Logger logger = LoggerFactory.getLogger(EmailController.class);
@Autowired
private EmailService sendEmailService;
@PostMapping("/email")
@ResponseStatus(value = HttpStatus.OK)
public Message sendEmails(@RequestBody EmailTO email) {
this.sendEmailService.sendEmails(email.toEmail());
return new Message("Information successfully received.");
}
@GetMapping("/email")
public List<Email> getEmails() {
logger.info("Emails listed");
return this.sendEmailService.emailsAll();
}
}
| Digituz/mailer | src/main/java/br/com/digituz/mailer/controller/EmailController.java | Java | mit | 1,350 |
require 'spec_helper'
describe Worochi::Helper do
describe '.is_s3_path?', :aws do
it 'recognizes an S3 path' do
expect(Worochi::Helper.is_s3_path?('s3:test/path')).to be_true
end
it 'rejects other paths' do
expect(Worochi::Helper.is_s3_path?('test/path')).to be_false
expect(Worochi::Helper.is_s3_path?('s3/test/path')).to be_false
expect(Worochi::Helper.is_s3_path?('http://a.com/path')).to be_false
end
end
describe '.s3_url', :aws do
it 'returns the right S3 URL' do
Worochi::Config.s3_bucket = 'rspec-test'
uri = Worochi::Helper.s3_url('s3:test/path')
expect(uri.path).to eq('/test/path')
expect(uri.host).to include('rspec-test')
end
it 'parses bucket names' do
uri = Worochi::Helper.s3_url('s3:bucket-name:test/path')
expect(uri.path).to eq('/test/path')
expect(uri.host).to include('bucket-name')
end
it 'rejects invalid URLs' do
expect{Worochi::Helper.s3_url('a/b')}.to raise_error(Worochi::Error)
end
end
end | Pixelapse/worochi | spec/worochi/helper_spec.rb | Ruby | mit | 1,045 |
# frozen_string_literal: true
require 'spec_helper'
describe RubyRabbitmqJanus::Janus::Responses::Admin, type: :responses,
name: :admin do
let(:response) { described_class.new(message) }
describe '#libnice_debug' do
context 'with no libnice_debug' do
let(:message) { {} }
it { expect { response.libnice_debug }.to raise_error(RubyRabbitmqJanus::Errors::Janus::Responses::Admin::LibniceDebug) }
end
context 'with libnice_debug' do
let(:message) { { 'libnice_debug' => true } }
it { expect(response.libnice_debug).to be_kind_of(TrueClass) }
end
end
end
| dazzl-tv/ruby-rabbitmq-janus | spec/ruby_rabbitmq_janus/janus/responses/admin_libnice_debug_spec.rb | Ruby | mit | 656 |
package main
import (
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
"testing"
"github.com/darwinfroese/gowt/mux"
)
const expectedOutput string = "Hello World"
var srv *httptest.Server
func TestMain(m *testing.M) {
setup()
code := m.Run()
shutdown()
os.Exit(code)
}
func setup() {
m := mux.NewMux()
m.RegisterRoute("/hello", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, expectedOutput) })
srv = httptest.NewServer(m)
}
func shutdown() {
srv.Close()
}
func TestRoute(t *testing.T) {
t.Log("Testing Routes")
res, err := http.Get(srv.URL + "/hello")
if err != nil {
t.Errorf(" FAILED - %s", err.Error())
}
msg, err := ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
t.Errorf(" FAILED - %s", err.Error())
}
if string(msg) != expectedOutput {
t.Errorf(" FAILED - Expected \"%s\" but got \"%s\"", expectedOutput, msg)
}
}
| darwinfroese/gowt | tests/mux/main_test.go | GO | mit | 897 |
#!/usr/bin/env ruby
#
# setup.rb
#
# Copyright (c) 2000-2005 Minero Aoki
#
# This program is free software.
# You can distribute/modify this program under the terms of
# the GNU LGPL, Lesser General Public License version 2.1.
#
unless Enumerable.method_defined?(:map) # Ruby 1.4.6
module Enumerable
alias map collect
end
end
unless File.respond_to?(:read) # Ruby 1.6
def File.read(fname)
open(fname) {|f|
return f.read
}
end
end
unless Errno.const_defined?(:ENOTEMPTY) # Windows?
module Errno
class ENOTEMPTY
# We do not raise this exception, implementation is not needed.
end
end
end
def File.binread(fname)
open(fname, 'rb') {|f|
return f.read
}
end
# for corrupted Windows' stat(2)
def File.dir?(path)
File.directory?((path[-1,1] == '/') ? path : path + '/')
end
class ConfigTable
include Enumerable
def initialize(rbconfig)
@rbconfig = rbconfig
@items = []
@table = {}
# options
@install_prefix = nil
@config_opt = nil
@verbose = true
@no_harm = false
@libsrc_pattern = '*.rb'
end
attr_accessor :install_prefix
attr_accessor :config_opt
attr_writer :verbose
def verbose?
@verbose
end
attr_writer :no_harm
def no_harm?
@no_harm
end
attr_accessor :libsrc_pattern
def [](key)
lookup(key).resolve(self)
end
def []=(key, val)
lookup(key).set val
end
def names
@items.map {|i| i.name }
end
def each(&block)
@items.each(&block)
end
def key?(name)
@table.key?(name)
end
def lookup(name)
@table[name] or setup_rb_error "no such config item: #{name}"
end
def add(item)
@items.push item
@table[item.name] = item
end
def remove(name)
item = lookup(name)
@items.delete_if {|i| i.name == name }
@table.delete_if {|name, i| i.name == name }
item
end
def load_script(path, inst = nil)
if File.file?(path)
MetaConfigEnvironment.new(self, inst).instance_eval File.read(path), path
end
end
def savefile
'.config'
end
def load_savefile
begin
File.foreach(savefile()) do |line|
k, v = *line.split(/=/, 2)
self[k] = v.strip
end
rescue Errno::ENOENT
setup_rb_error $!.message + "\n#{File.basename($0)} config first"
end
end
def save
@items.each {|i| i.value }
File.open(savefile(), 'w') {|f|
@items.each do |i|
f.printf "%s=%s\n", i.name, i.value if i.value? and i.value
end
}
end
def load_standard_entries
standard_entries(@rbconfig).each do |ent|
add ent
end
end
def standard_entries(rbconfig)
c = rbconfig
rubypath = c['bindir'] + '/' + c['ruby_install_name']
major = c['MAJOR'].to_i
minor = c['MINOR'].to_i
teeny = c['TEENY'].to_i
version = "#{major}.#{minor}"
# ruby ver. >= 1.4.4?
newpath_p = ((major >= 2) or
((major == 1) and
((minor >= 5) or
((minor == 4) and (teeny >= 4)))))
if c['rubylibdir']
# V > 1.6.3
libruby = "#{c['prefix']}/lib/ruby"
librubyver = c['rubylibdir']
librubyverarch = c['archdir']
siteruby = c['sitedir']
siterubyver = c['sitelibdir']
siterubyverarch = c['sitearchdir']
elsif newpath_p
# 1.4.4 <= V <= 1.6.3
libruby = "#{c['prefix']}/lib/ruby"
librubyver = "#{c['prefix']}/lib/ruby/#{version}"
librubyverarch = "#{c['prefix']}/lib/ruby/#{version}/#{c['arch']}"
siteruby = c['sitedir']
siterubyver = "$siteruby/#{version}"
siterubyverarch = "$siterubyver/#{c['arch']}"
else
# V < 1.4.4
libruby = "#{c['prefix']}/lib/ruby"
librubyver = "#{c['prefix']}/lib/ruby/#{version}"
librubyverarch = "#{c['prefix']}/lib/ruby/#{version}/#{c['arch']}"
siteruby = "#{c['prefix']}/lib/ruby/#{version}/site_ruby"
siterubyver = siteruby
siterubyverarch = "$siterubyver/#{c['arch']}"
end
parameterize = lambda {|path|
path.sub(/\A#{Regexp.quote(c['prefix'])}/, '$prefix')
}
if arg = c['configure_args'].split.detect {|arg| /--with-make-prog=/ =~ arg }
makeprog = arg.sub(/'/, '').split(/=/, 2)[1]
else
makeprog = 'make'
end
[
ExecItem.new('installdirs', 'std/site/home',
'std: install under libruby; site: install under site_ruby; home: install under $HOME')\
{|val, table|
case val
when 'std'
table['rbdir'] = '$librubyver'
table['sodir'] = '$librubyverarch'
when 'site'
table['rbdir'] = '$siterubyver'
table['sodir'] = '$siterubyverarch'
when 'home'
setup_rb_error '$HOME was not set' unless ENV['HOME']
table['prefix'] = ENV['HOME']
table['rbdir'] = '$libdir/ruby'
table['sodir'] = '$libdir/ruby'
end
},
PathItem.new('prefix', 'path', c['prefix'],
'path prefix of target environment'),
PathItem.new('bindir', 'path', parameterize.call(c['bindir']),
'the directory for commands'),
PathItem.new('libdir', 'path', parameterize.call(c['libdir']),
'the directory for libraries'),
PathItem.new('datadir', 'path', parameterize.call(c['datadir']),
'the directory for shared data'),
PathItem.new('mandir', 'path', parameterize.call(c['mandir']),
'the directory for man pages'),
PathItem.new('sysconfdir', 'path', parameterize.call(c['sysconfdir']),
'the directory for system configuration files'),
PathItem.new('localstatedir', 'path', parameterize.call(c['localstatedir']),
'the directory for local state data'),
PathItem.new('libruby', 'path', libruby,
'the directory for ruby libraries'),
PathItem.new('librubyver', 'path', librubyver,
'the directory for standard ruby libraries'),
PathItem.new('librubyverarch', 'path', librubyverarch,
'the directory for standard ruby extensions'),
PathItem.new('siteruby', 'path', siteruby,
'the directory for version-independent aux ruby libraries'),
PathItem.new('siterubyver', 'path', siterubyver,
'the directory for aux ruby libraries'),
PathItem.new('siterubyverarch', 'path', siterubyverarch,
'the directory for aux ruby binaries'),
PathItem.new('rbdir', 'path', '$siterubyver',
'the directory for ruby scripts'),
PathItem.new('sodir', 'path', '$siterubyverarch',
'the directory for ruby extentions'),
PathItem.new('rubypath', 'path', rubypath,
'the path to set to #! line'),
ProgramItem.new('rubyprog', 'name', rubypath,
'the ruby program using for installation'),
ProgramItem.new('makeprog', 'name', makeprog,
'the make program to compile ruby extentions'),
SelectItem.new('shebang', 'all/ruby/never', 'ruby',
'shebang line (#!) editing mode'),
BoolItem.new('without-ext', 'yes/no', 'no',
'does not compile/install ruby extentions')
]
end
private :standard_entries
def load_multipackage_entries
multipackage_entries().each do |ent|
add ent
end
end
def multipackage_entries
[
PackageSelectionItem.new('with', 'name,name...', '', 'ALL',
'package names that you want to install'),
PackageSelectionItem.new('without', 'name,name...', '', 'NONE',
'package names that you do not want to install')
]
end
private :multipackage_entries
ALIASES = {
'std-ruby' => 'librubyver',
'stdruby' => 'librubyver',
'rubylibdir' => 'librubyver',
'archdir' => 'librubyverarch',
'site-ruby-common' => 'siteruby', # For backward compatibility
'site-ruby' => 'siterubyver', # For backward compatibility
'bin-dir' => 'bindir',
'bin-dir' => 'bindir',
'rb-dir' => 'rbdir',
'so-dir' => 'sodir',
'data-dir' => 'datadir',
'ruby-path' => 'rubypath',
'ruby-prog' => 'rubyprog',
'ruby' => 'rubyprog',
'make-prog' => 'makeprog',
'make' => 'makeprog'
}
def fixup
ALIASES.each do |ali, name|
@table[ali] = @table[name]
end
@items.freeze
@table.freeze
@options_re = /\A--(#{@table.keys.join('|')})(?:=(.*))?\z/
end
def parse_opt(opt)
m = @options_re.match(opt) or setup_rb_error "config: unknown option #{opt}"
m.to_a[1,2]
end
def dllext
@rbconfig['DLEXT']
end
def value_config?(name)
lookup(name).value?
end
class Item
def initialize(name, template, default, desc)
@name = name.freeze
@template = template
@value = default
@default = default
@description = desc
end
attr_reader :name
attr_reader :description
attr_accessor :default
alias help_default default
def help_opt
"--#{@name}=#{@template}"
end
def value?
true
end
def value
@value
end
def resolve(table)
@value.gsub(%r<\$([^/]+)>) { table[$1] }
end
def set(val)
@value = check(val)
end
private
def check(val)
setup_rb_error "config: --#{name} requires argument" unless val
val
end
end
class BoolItem < Item
def config_type
'bool'
end
def help_opt
"--#{@name}"
end
private
def check(val)
return 'yes' unless val
unless /\A(y(es)?|n(o)?|t(rue)?|f(alse))\z/i =~ val
setup_rb_error "config: --#{@name} accepts only yes/no for argument"
end
(/\Ay(es)?|\At(rue)/i =~ value) ? 'yes' : 'no'
end
end
class PathItem < Item
def config_type
'path'
end
private
def check(path)
setup_rb_error "config: --#{@name} requires argument" unless path
path[0,1] == '$' ? path : File.expand_path(path)
end
end
class ProgramItem < Item
def config_type
'program'
end
end
class SelectItem < Item
def initialize(name, selection, default, desc)
super
@ok = selection.split('/')
end
def config_type
'select'
end
private
def check(val)
unless @ok.include?(val.strip)
setup_rb_error "config: use --#{@name}=#{@template} (#{val})"
end
val.strip
end
end
class ExecItem < Item
def initialize(name, selection, desc, &block)
super name, selection, nil, desc
@ok = selection.split('/')
@action = block
end
def config_type
'exec'
end
def value?
false
end
def resolve(table)
setup_rb_error "$#{name()} wrongly used as option value"
end
undef set
def evaluate(val, table)
v = val.strip.downcase
unless @ok.include?(v)
setup_rb_error "invalid option --#{@name}=#{val} (use #{@template})"
end
@action.call v, table
end
end
class PackageSelectionItem < Item
def initialize(name, template, default, help_default, desc)
super name, template, default, desc
@help_default = help_default
end
attr_reader :help_default
def config_type
'package'
end
private
def check(val)
unless File.dir?("packages/#{val}")
setup_rb_error "config: no such package: #{val}"
end
val
end
end
class MetaConfigEnvironment
def intiailize(config, installer)
@config = config
@installer = installer
end
def config_names
@config.names
end
def config?(name)
@config.key?(name)
end
def bool_config?(name)
@config.lookup(name).config_type == 'bool'
end
def path_config?(name)
@config.lookup(name).config_type == 'path'
end
def value_config?(name)
@config.lookup(name).config_type != 'exec'
end
def add_config(item)
@config.add item
end
def add_bool_config(name, default, desc)
@config.add BoolItem.new(name, 'yes/no', default ? 'yes' : 'no', desc)
end
def add_path_config(name, default, desc)
@config.add PathItem.new(name, 'path', default, desc)
end
def set_config_default(name, default)
@config.lookup(name).default = default
end
def remove_config(name)
@config.remove(name)
end
# For only multipackage
def packages
raise '[setup.rb fatal] multi-package metaconfig API packages() called for single-package; contact application package vendor' unless @installer
@installer.packages
end
# For only multipackage
def declare_packages(list)
raise '[setup.rb fatal] multi-package metaconfig API declare_packages() called for single-package; contact application package vendor' unless @installer
@installer.packages = list
end
end
end # class ConfigTable
# This module requires: #verbose?, #no_harm?
module FileOperations
def mkdir_p(dirname, prefix = nil)
dirname = prefix + File.expand_path(dirname) if prefix
$stderr.puts "mkdir -p #{dirname}" if verbose?
return if no_harm?
# Does not check '/', it's too abnormal.
dirs = File.expand_path(dirname).split(%r<(?=/)>)
if /\A[a-z]:\z/i =~ dirs[0]
disk = dirs.shift
dirs[0] = disk + dirs[0]
end
dirs.each_index do |idx|
path = dirs[0..idx].join('')
Dir.mkdir path unless File.dir?(path)
end
end
def rm_f(path)
$stderr.puts "rm -f #{path}" if verbose?
return if no_harm?
force_remove_file path
end
def rm_rf(path)
$stderr.puts "rm -rf #{path}" if verbose?
return if no_harm?
remove_tree path
end
def remove_tree(path)
if File.symlink?(path)
remove_file path
elsif File.dir?(path)
remove_tree0 path
else
force_remove_file path
end
end
def remove_tree0(path)
Dir.foreach(path) do |ent|
next if ent == '.'
next if ent == '..'
entpath = "#{path}/#{ent}"
if File.symlink?(entpath)
remove_file entpath
elsif File.dir?(entpath)
remove_tree0 entpath
else
force_remove_file entpath
end
end
begin
Dir.rmdir path
rescue Errno::ENOTEMPTY
# directory may not be empty
end
end
def move_file(src, dest)
force_remove_file dest
begin
File.rename src, dest
rescue
File.open(dest, 'wb') {|f|
f.write File.binread(src)
}
File.chmod File.stat(src).mode, dest
File.unlink src
end
end
def force_remove_file(path)
begin
remove_file path
rescue
end
end
def remove_file(path)
File.chmod 0777, path
File.unlink path
end
def install(from, dest, mode, prefix = nil)
$stderr.puts "install #{from} #{dest}" if verbose?
return if no_harm?
realdest = prefix ? prefix + File.expand_path(dest) : dest
realdest = File.join(realdest, File.basename(from)) if File.dir?(realdest)
str = File.binread(from)
if diff?(str, realdest)
verbose_off {
rm_f realdest if File.exist?(realdest)
}
File.open(realdest, 'wb') {|f|
f.write str
}
File.chmod mode, realdest
File.open("#{objdir_root()}/InstalledFiles", 'a') {|f|
if prefix
f.puts realdest.sub(prefix, '')
else
f.puts realdest
end
}
end
end
def diff?(new_content, path)
return true unless File.exist?(path)
new_content != File.binread(path)
end
def command(*args)
$stderr.puts args.join(' ') if verbose?
system(*args) or raise RuntimeError,
"system(#{args.map{|a| a.inspect }.join(' ')}) failed"
end
def ruby(*args)
command config('rubyprog'), *args
end
def make(task = nil)
command(*[config('makeprog'), task].compact)
end
def extdir?(dir)
File.exist?("#{dir}/MANIFEST") or File.exist?("#{dir}/extconf.rb")
end
def files_of(dir)
Dir.open(dir) {|d|
return d.select {|ent| File.file?("#{dir}/#{ent}") }
}
end
DIR_REJECT = %w( . .. CVS SCCS RCS CVS.adm .svn )
def directories_of(dir)
Dir.open(dir) {|d|
return d.select {|ent| File.dir?("#{dir}/#{ent}") } - DIR_REJECT
}
end
end
# This module requires: #srcdir_root, #objdir_root, #relpath
module HookScriptAPI
def get_config(key)
@config[key]
end
alias config get_config
# obsolete: use metaconfig to change configuration
def set_config(key, val)
@config[key] = val
end
#
# srcdir/objdir (works only in the package directory)
#
def curr_srcdir
"#{srcdir_root()}/#{relpath()}"
end
def curr_objdir
"#{objdir_root()}/#{relpath()}"
end
def srcfile(path)
"#{curr_srcdir()}/#{path}"
end
def srcexist?(path)
File.exist?(srcfile(path))
end
def srcdirectory?(path)
File.dir?(srcfile(path))
end
def srcfile?(path)
File.file?(srcfile(path))
end
def srcentries(path = '.')
Dir.open("#{curr_srcdir()}/#{path}") {|d|
return d.to_a - %w(. ..)
}
end
def srcfiles(path = '.')
srcentries(path).select {|fname|
File.file?(File.join(curr_srcdir(), path, fname))
}
end
def srcdirectories(path = '.')
srcentries(path).select {|fname|
File.dir?(File.join(curr_srcdir(), path, fname))
}
end
end
class ToplevelInstaller
Version = '3.4.0'
Copyright = 'Copyright (c) 2000-2005 Minero Aoki'
TASKS = [
[ 'all', 'do config, setup, then install' ],
[ 'config', 'saves your configurations' ],
[ 'show', 'shows current configuration' ],
[ 'setup', 'compiles ruby extentions and others' ],
[ 'install', 'installs files' ],
[ 'test', 'run all tests in test/' ],
[ 'clean', "does `make clean' for each extention" ],
[ 'distclean',"does `make distclean' for each extention" ]
]
def ToplevelInstaller.invoke
config = ConfigTable.new(load_rbconfig())
config.load_standard_entries
config.load_multipackage_entries if multipackage?
config.fixup
klass = (multipackage?() ? ToplevelInstallerMulti : ToplevelInstaller)
klass.new(File.dirname($0), config).invoke
end
def ToplevelInstaller.multipackage?
File.dir?(File.dirname($0) + '/packages')
end
def ToplevelInstaller.load_rbconfig
if arg = ARGV.detect {|arg| /\A--rbconfig=/ =~ arg }
ARGV.delete(arg)
load File.expand_path(arg.split(/=/, 2)[1])
$".push 'rbconfig.rb'
else
require 'rbconfig'
end
::Config::CONFIG
end
def initialize(ardir_root, config)
@ardir = File.expand_path(ardir_root)
@config = config
# cache
@valid_task_re = nil
end
def config(key)
@config[key]
end
def inspect
"#<#{self.class} #{__id__()}>"
end
def invoke
run_metaconfigs
case task = parsearg_global()
when nil, 'all'
parsearg_config
init_installers
exec_config
exec_setup
exec_install
else
case task
when 'config', 'test'
;
when 'clean', 'distclean'
@config.load_savefile if File.exist?(@config.savefile)
else
@config.load_savefile
end
__send__ "parsearg_#{task}"
init_installers
__send__ "exec_#{task}"
end
end
def run_metaconfigs
@config.load_script "#{@ardir}/metaconfig"
end
def init_installers
@installer = Installer.new(@config, @ardir, File.expand_path('.'))
end
#
# Hook Script API bases
#
def srcdir_root
@ardir
end
def objdir_root
'.'
end
def relpath
'.'
end
#
# Option Parsing
#
def parsearg_global
while arg = ARGV.shift
case arg
when /\A\w+\z/
setup_rb_error "invalid task: #{arg}" unless valid_task?(arg)
return arg
when '-q', '--quiet'
@config.verbose = false
when '--verbose'
@config.verbose = true
when '--help'
print_usage $stdout
exit 0
when '--version'
puts "#{File.basename($0)} version #{Version}"
exit 0
when '--copyright'
puts Copyright
exit 0
else
setup_rb_error "unknown global option '#{arg}'"
end
end
nil
end
def valid_task?(t)
valid_task_re() =~ t
end
def valid_task_re
@valid_task_re ||= /\A(?:#{TASKS.map {|task,desc| task }.join('|')})\z/
end
def parsearg_no_options
unless ARGV.empty?
setup_rb_error "#{task}: unknown options: #{ARGV.join(' ')}"
end
end
alias parsearg_show parsearg_no_options
alias parsearg_setup parsearg_no_options
alias parsearg_test parsearg_no_options
alias parsearg_clean parsearg_no_options
alias parsearg_distclean parsearg_no_options
def parsearg_config
evalopt = []
set = []
@config.config_opt = []
while i = ARGV.shift
if /\A--?\z/ =~ i
@config.config_opt = ARGV.dup
break
end
name, value = *@config.parse_opt(i)
if @config.value_config?(name)
@config[name] = value
else
evalopt.push [name, value]
end
set.push name
end
evalopt.each do |name, value|
@config.lookup(name).evaluate value, @config
end
# Check if configuration is valid
set.each do |n|
@config[n] if @config.value_config?(n)
end
end
def parsearg_install
@config.no_harm = false
@config.install_prefix = ''
while a = ARGV.shift
case a
when '--no-harm'
@config.no_harm = true
when /\A--prefix=/
path = a.split(/=/, 2)[1]
path = File.expand_path(path) unless path[0,1] == '/'
@config.install_prefix = path
else
setup_rb_error "install: unknown option #{a}"
end
end
end
def print_usage(out)
out.puts 'Typical Installation Procedure:'
out.puts " $ ruby #{File.basename $0} config"
out.puts " $ ruby #{File.basename $0} setup"
out.puts " # ruby #{File.basename $0} install (may require root privilege)"
out.puts
out.puts 'Detailed Usage:'
out.puts " ruby #{File.basename $0} <global option>"
out.puts " ruby #{File.basename $0} [<global options>] <task> [<task options>]"
fmt = " %-24s %s\n"
out.puts
out.puts 'Global options:'
out.printf fmt, '-q,--quiet', 'suppress message outputs'
out.printf fmt, ' --verbose', 'output messages verbosely'
out.printf fmt, ' --help', 'print this message'
out.printf fmt, ' --version', 'print version and quit'
out.printf fmt, ' --copyright', 'print copyright and quit'
out.puts
out.puts 'Tasks:'
TASKS.each do |name, desc|
out.printf fmt, name, desc
end
fmt = " %-24s %s [%s]\n"
out.puts
out.puts 'Options for CONFIG or ALL:'
@config.each do |item|
out.printf fmt, item.help_opt, item.description, item.help_default
end
out.printf fmt, '--rbconfig=path', 'rbconfig.rb to load',"running ruby's"
out.puts
out.puts 'Options for INSTALL:'
out.printf fmt, '--no-harm', 'only display what to do if given', 'off'
out.printf fmt, '--prefix=path', 'install path prefix', ''
out.puts
end
#
# Task Handlers
#
def exec_config
@installer.exec_config
@config.save # must be final
end
def exec_setup
@installer.exec_setup
end
def exec_install
@installer.exec_install
end
def exec_test
@installer.exec_test
end
def exec_show
@config.each do |i|
printf "%-20s %s\n", i.name, i.value if i.value?
end
end
def exec_clean
@installer.exec_clean
end
def exec_distclean
@installer.exec_distclean
end
end # class ToplevelInstaller
class ToplevelInstallerMulti < ToplevelInstaller
include FileOperations
def initialize(ardir_root, config)
super
@packages = directories_of("#{@ardir}/packages")
raise 'no package exists' if @packages.empty?
@root_installer = Installer.new(@config, @ardir, File.expand_path('.'))
end
def run_metaconfigs
@config.load_script "#{@ardir}/metaconfig", self
@packages.each do |name|
@config.load_script "#{@ardir}/packages/#{name}/metaconfig"
end
end
attr_reader :packages
def packages=(list)
raise 'package list is empty' if list.empty?
list.each do |name|
raise "directory packages/#{name} does not exist"\
unless File.dir?("#{@ardir}/packages/#{name}")
end
@packages = list
end
def init_installers
@installers = {}
@packages.each do |pack|
@installers[pack] = Installer.new(@config,
"#{@ardir}/packages/#{pack}",
"packages/#{pack}")
end
with = extract_selection(config('with'))
without = extract_selection(config('without'))
@selected = @installers.keys.select {|name|
(with.empty? or with.include?(name)) \
and not without.include?(name)
}
end
def extract_selection(list)
a = list.split(/,/)
a.each do |name|
setup_rb_error "no such package: #{name}" unless @installers.key?(name)
end
a
end
def print_usage(f)
super
f.puts 'Inluded packages:'
f.puts ' ' + @packages.sort.join(' ')
f.puts
end
#
# Task Handlers
#
def exec_config
run_hook 'pre-config'
each_selected_installers {|inst| inst.exec_config }
run_hook 'post-config'
@config.save # must be final
end
def exec_setup
run_hook 'pre-setup'
each_selected_installers {|inst| inst.exec_setup }
run_hook 'post-setup'
end
def exec_install
run_hook 'pre-install'
each_selected_installers {|inst| inst.exec_install }
run_hook 'post-install'
end
def exec_test
run_hook 'pre-test'
each_selected_installers {|inst| inst.exec_test }
run_hook 'post-test'
end
def exec_clean
rm_f @config.savefile
run_hook 'pre-clean'
each_selected_installers {|inst| inst.exec_clean }
run_hook 'post-clean'
end
def exec_distclean
rm_f @config.savefile
run_hook 'pre-distclean'
each_selected_installers {|inst| inst.exec_distclean }
run_hook 'post-distclean'
end
#
# lib
#
def each_selected_installers
Dir.mkdir 'packages' unless File.dir?('packages')
@selected.each do |pack|
$stderr.puts "Processing the package `#{pack}' ..." if verbose?
Dir.mkdir "packages/#{pack}" unless File.dir?("packages/#{pack}")
Dir.chdir "packages/#{pack}"
yield @installers[pack]
Dir.chdir '../..'
end
end
def run_hook(id)
@root_installer.run_hook id
end
# module FileOperations requires this
def verbose?
@config.verbose?
end
# module FileOperations requires this
def no_harm?
@config.no_harm?
end
end # class ToplevelInstallerMulti
class Installer
FILETYPES = %w( bin lib ext data conf man )
include FileOperations
include HookScriptAPI
def initialize(config, srcroot, objroot)
@config = config
@srcdir = File.expand_path(srcroot)
@objdir = File.expand_path(objroot)
@currdir = '.'
end
def inspect
"#<#{self.class} #{File.basename(@srcdir)}>"
end
#
# Hook Script API base methods
#
def srcdir_root
@srcdir
end
def objdir_root
@objdir
end
def relpath
@currdir
end
#
# Config Access
#
# module FileOperations requires this
def verbose?
@config.verbose?
end
# module FileOperations requires this
def no_harm?
@config.no_harm?
end
def verbose_off
begin
save, @config.verbose = @config.verbose?, false
yield
ensure
@config.verbose = save
end
end
#
# TASK config
#
def exec_config
exec_task_traverse 'config'
end
def config_dir_bin(rel)
end
def config_dir_lib(rel)
end
def config_dir_man(rel)
end
def config_dir_ext(rel)
extconf if extdir?(curr_srcdir())
end
def extconf
ruby "#{curr_srcdir()}/extconf.rb", *@config.config_opt
end
def config_dir_data(rel)
end
def config_dir_conf(rel)
end
#
# TASK setup
#
def exec_setup
exec_task_traverse 'setup'
end
def setup_dir_bin(rel)
files_of(curr_srcdir()).each do |fname|
adjust_shebang "#{curr_srcdir()}/#{fname}"
end
end
def adjust_shebang(path)
return if no_harm?
tmpfile = File.basename(path) + '.tmp'
begin
File.open(path, 'rb') {|r|
first = r.gets
return unless File.basename(first.sub(/\A\#!/, '').split[0].to_s) == 'ruby'
$stderr.puts "adjusting shebang: #{File.basename(path)}" if verbose?
File.open(tmpfile, 'wb') {|w|
w.print first.sub(/\A\#!\s*\S+/, '#! ' + config('rubypath'))
w.write r.read
}
}
move_file tmpfile, File.basename(path)
ensure
File.unlink tmpfile if File.exist?(tmpfile)
end
end
def setup_dir_lib(rel)
end
def setup_dir_man(rel)
end
def setup_dir_ext(rel)
make if extdir?(curr_srcdir())
end
def setup_dir_data(rel)
end
def setup_dir_conf(rel)
end
#
# TASK install
#
def exec_install
rm_f 'InstalledFiles'
exec_task_traverse 'install'
end
def install_dir_bin(rel)
install_files targetfiles(), "#{config('bindir')}/#{rel}", 0755
end
def install_dir_lib(rel)
install_files rubyscripts(), "#{config('rbdir')}/#{rel}", 0644
end
def install_dir_ext(rel)
return unless extdir?(curr_srcdir())
install_files rubyextentions('.'),
"#{config('sodir')}/#{File.dirname(rel)}",
0555
end
def install_dir_data(rel)
install_files targetfiles(), "#{config('datadir')}/#{rel}", 0644
end
def install_dir_conf(rel)
# FIXME: should not remove current config files
# (rename previous file to .old/.org)
install_files targetfiles(), "#{config('sysconfdir')}/#{rel}", 0644
end
def install_dir_man(rel)
install_files targetfiles(), "#{config('mandir')}/#{rel}", 0644
end
def install_files(list, dest, mode)
mkdir_p dest, @config.install_prefix
list.each do |fname|
install fname, dest, mode, @config.install_prefix
end
end
def rubyscripts
glob_select(@config.libsrc_pattern, targetfiles())
end
def rubyextentions(dir)
ents = glob_select("*.#{@config.dllext}", targetfiles())
if ents.empty?
setup_rb_error "no ruby extention exists: 'ruby #{$0} setup' first"
end
ents
end
def targetfiles
mapdir(existfiles() - hookfiles())
end
def mapdir(ents)
ents.map {|ent|
if File.exist?(ent)
then ent # objdir
else "#{curr_srcdir()}/#{ent}" # srcdir
end
}
end
# picked up many entries from cvs-1.11.1/src/ignore.c
JUNK_FILES = %w(
core RCSLOG tags TAGS .make.state
.nse_depinfo #* .#* cvslog.* ,* .del-* *.olb
*~ *.old *.bak *.BAK *.orig *.rej _$* *$
*.org *.in .*
)
def existfiles
glob_reject(JUNK_FILES, (files_of(curr_srcdir()) | files_of('.')))
end
def hookfiles
%w( pre-%s post-%s pre-%s.rb post-%s.rb ).map {|fmt|
%w( config setup install clean ).map {|t| sprintf(fmt, t) }
}.flatten
end
def glob_select(pat, ents)
re = globs2re([pat])
ents.select {|ent| re =~ ent }
end
def glob_reject(pats, ents)
re = globs2re(pats)
ents.reject {|ent| re =~ ent }
end
GLOB2REGEX = {
'.' => '\.',
'$' => '\$',
'#' => '\#',
'*' => '.*'
}
def globs2re(pats)
/\A(?:#{
pats.map {|pat| pat.gsub(/[\.\$\#\*]/) {|ch| GLOB2REGEX[ch] } }.join('|')
})\z/
end
#
# TASK test
#
TESTDIR = 'test'
def exec_test
unless File.directory?(TESTDIR)
$stderr.puts 'no test in this package' if verbose?
return
end
$stderr.puts 'Running tests...' if verbose?
require 'test/unit'
runner = Test::Unit::AutoRunner.new(true)
runner.to_run << TESTDIR
runner.run
end
#
# TASK clean
#
def exec_clean
exec_task_traverse 'clean'
rm_f @config.savefile
rm_f 'InstalledFiles'
end
def clean_dir_bin(rel)
end
def clean_dir_lib(rel)
end
def clean_dir_ext(rel)
return unless extdir?(curr_srcdir())
make 'clean' if File.file?('Makefile')
end
def clean_dir_data(rel)
end
def clean_dir_conf(rel)
end
#
# TASK distclean
#
def exec_distclean
exec_task_traverse 'distclean'
rm_f @config.savefile
rm_f 'InstalledFiles'
end
def distclean_dir_bin(rel)
end
def distclean_dir_lib(rel)
end
def distclean_dir_ext(rel)
return unless extdir?(curr_srcdir())
make 'distclean' if File.file?('Makefile')
end
def distclean_dir_data(rel)
end
def distclean_dir_conf(rel)
end
#
# lib
#
def exec_task_traverse(task)
run_hook "pre-#{task}"
FILETYPES.each do |type|
if config('without-ext') == 'yes' and type == 'ext'
$stderr.puts 'skipping ext/* by user option' if verbose?
next
end
traverse task, type, "#{task}_dir_#{type}"
end
run_hook "post-#{task}"
end
def traverse(task, rel, mid)
dive_into(rel) {
run_hook "pre-#{task}"
__send__ mid, rel.sub(%r[\A.*?(?:/|\z)], '')
directories_of(curr_srcdir()).each do |d|
traverse task, "#{rel}/#{d}", mid
end
run_hook "post-#{task}"
}
end
def dive_into(rel)
return unless File.dir?("#{@srcdir}/#{rel}")
dir = File.basename(rel)
Dir.mkdir dir unless File.dir?(dir)
prevdir = Dir.pwd
Dir.chdir dir
$stderr.puts '---> ' + rel if verbose?
@currdir = rel
yield
Dir.chdir prevdir
$stderr.puts '<--- ' + rel if verbose?
@currdir = File.dirname(rel)
end
def run_hook(id)
path = [ "#{curr_srcdir()}/#{id}",
"#{curr_srcdir()}/#{id}.rb" ].detect {|cand| File.file?(cand) }
return unless path
begin
instance_eval File.read(path), path, 1
rescue
raise if $DEBUG
setup_rb_error "hook #{path} failed:\n" + $!.message
end
end
end # class Installer
class SetupError < StandardError; end
def setup_rb_error(msg)
raise SetupError, msg
end
if $0 == __FILE__
begin
ToplevelInstaller.invoke
rescue SetupError
raise if $DEBUG
$stderr.puts $!.message
$stderr.puts "Try 'ruby #{$0} --help' for detailed usage."
exit 1
end
end
| rsms/rhp | install.rb | Ruby | mit | 34,762 |
package main
import (
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"regexp"
"strconv"
"strings"
"github.com/dghubble/go-twitter/twitter"
"github.com/dghubble/oauth1"
)
var (
twitterUsername string
twitterConsumerKey string
twitterConsumerSecret string
twitterAuthToken string
twitterAuthSecret string
twitterAPIClient *twitter.Client
twitterUploadClient *http.Client
tweetURLPattern = regexp.MustCompile("^https?://twitter.com/\\w+/status/(?P<tweet_id>\\d+)$")
)
type twitterPlugin struct{}
func (p twitterPlugin) EnvVariables() []EnvVariable {
return []EnvVariable{
{
Name: "TWITTER_USERNAME",
Variable: &twitterUsername,
},
{
Name: "TWITTER_CONSUMER_KEY",
Variable: &twitterConsumerKey,
},
{
Name: "TWITTER_CONSUMER_SECRET",
Variable: &twitterConsumerSecret,
},
{
Name: "TWITTER_ACCESS_TOKEN",
Variable: &twitterAuthToken,
},
{
Name: "TWITTER_ACCESS_TOKEN_SECRET",
Variable: &twitterAuthSecret,
},
}
}
func (p twitterPlugin) Name() string {
return "twitter"
}
func NewTwitterPlugin() WorkerPlugin {
return twitterPlugin{}
}
func (p twitterPlugin) Start(ch chan<- error) {
defer close(ch)
config := oauth1.NewConfig(twitterConsumerKey, twitterConsumerSecret)
token := oauth1.NewToken(twitterAuthToken, twitterAuthSecret)
httpClient := config.Client(oauth1.NoContext, token)
twitterUploadClient = httpClient
twitterAPIClient = twitter.NewClient(httpClient)
handleOfflineActivity(ch)
stream, err := twitterAPIClient.Streams.User(&twitter.StreamUserParams{
With: "user",
StallWarnings: twitter.Bool(true),
})
if err != nil {
ch <- err
return
}
demux := twitter.NewSwitchDemux()
demux.Tweet = func(tweet *twitter.Tweet) {
handleTweet(tweet, ch, true)
}
demux.DM = func(dm *twitter.DirectMessage) {
handleDM(dm, ch)
}
demux.StreamLimit = handleStreamLimit
demux.StreamDisconnect = handleStreamDisconnect
demux.Warning = handleWarning
demux.Other = handleOther
demux.HandleChan(stream.Messages)
}
func logMessage(msg interface{}, desc string) {
if msgJSON, err := json.MarshalIndent(msg, "", " "); err == nil {
log.Printf("Received %s: %s\n", desc, string(msgJSON[:]))
} else {
logMessageStruct(msg, desc)
}
}
func logMessageStruct(msg interface{}, desc string) {
log.Printf("Received %s: %+v\n", desc, msg)
}
func lookupTweet(tweetID int64) (*twitter.Tweet, error) {
params := twitter.StatusShowParams{
TweetMode: "extended",
}
tweet, resp, err := twitterAPIClient.Statuses.Show(tweetID, ¶ms)
if err != nil {
return nil, fmt.Errorf("status lookup error: %s", err)
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return nil, fmt.Errorf("status lookup HTTP status code: %d", resp.StatusCode)
}
if tweet == nil {
return nil, errors.New("number of returned tweets is 0")
}
return tweet, nil
}
func lookupTweetText(tweetID int64) (string, error) {
tweet, err := lookupTweet(tweetID)
if err != nil {
return "", err
}
return extractText(tweet), nil
}
func extractText(tweet *twitter.Tweet) string {
var text string
if tweet.FullText == "" {
text = tweet.Text
} else {
text = tweet.FullText
}
if i := tweet.DisplayTextRange; i.End() > 0 {
return string([]rune(text)[i.Start():i.End()])
}
return text
}
func handleTweet(tweet *twitter.Tweet, ch chan<- error, followQuoteRetweet bool) (*twitter.Tweet, error) {
switch {
case tweet.User.ScreenName == twitterUsername:
return nil, errors.New("cannot mock my own tweet")
case tweet.RetweetedStatus != nil:
return nil, errors.New("cannot mock a retweet")
}
logMessageStruct(tweet, "Tweet")
mentions := []string{"@" + tweet.User.ScreenName}
text := extractText(tweet)
var err error
if tweet.InReplyToStatusIDStr == "" ||
!strings.Contains(text, "@"+twitterUsername) {
// remove twitter username mention
if strings.HasPrefix(text, "@"+twitterUsername+" ") {
text = text[len(twitterUsername)+2:]
}
if followQuoteRetweet && tweet.QuotedStatus != nil {
// quote retweets should mock the retweeted person if followQuoteRetweet is true
text = extractText(tweet.QuotedStatus)
mentions = append(mentions, "@"+tweet.QuotedStatus.User.ScreenName)
}
} else {
// mock the text the user replied to
text, err = lookupTweetText(tweet.InReplyToStatusID)
if err != nil {
ch <- err
return nil, err
}
if tweet.InReplyToScreenName != twitterUsername {
mentions = append(mentions, "@"+tweet.InReplyToScreenName)
}
}
log.Println("tweet text:", text)
finalTweets := finalizeTweet(mentions, text)
if DEBUG {
for _, finalTweet := range finalTweets {
log.Println("tweeting:", finalTweet)
}
return nil, errors.New("cannot send a tweet in DEBUG mode")
} else {
mediaID, mediaIDStr, cached, err := uploadImage()
if err != nil {
err = fmt.Errorf("upload image error: %s", err)
ch <- err
return nil, err
}
if !cached {
if err = uploadMetadata(mediaIDStr, text); err != nil {
// we can continue from a metadata upload error
// because it is not essential
ch <- fmt.Errorf("metadata upload error: %s", err)
}
}
params := twitter.StatusUpdateParams{
InReplyToStatusID: tweet.ID,
TrimUser: twitter.Bool(true),
MediaIds: []int64{mediaID},
}
var res *twitter.Tweet
for i, finalTweet := range finalTweets {
sentTweet, resp, err := twitterAPIClient.Statuses.Update(finalTweet, ¶ms)
if err != nil {
err = fmt.Errorf("status update error: %s", err)
ch <- err
return nil, err
}
resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
err = fmt.Errorf("response tweet status code: %d", resp.StatusCode)
ch <- err
return nil, err
}
params.InReplyToStatusID = sentTweet.ID
if i == 0 {
res = sentTweet
}
}
return res, nil
}
}
func extractTweetFromDM(dm *twitter.DirectMessage) (*twitter.Tweet, error) {
// Is this a link to a tweet?
if dm.Entities != nil {
for _, urlEntity := range dm.Entities.Urls {
if r := tweetURLPattern.FindStringSubmatch(urlEntity.ExpandedURL); r != nil {
if tweetID, err := strconv.ParseInt(r[1], 10, 64); err == nil {
// we don't need to check for errors at this point since it cannot be any other kind of message
return lookupTweet(tweetID)
} else {
panic(fmt.Errorf("tweetURLPattern regexp matched a tweet %s with an unparseable tweet ID %d", urlEntity.ExpandedURL, r[1]))
}
}
}
}
// is this a tweet ID?
if tweetID, err := strconv.ParseInt(dm.Text, 10, 64); err == nil {
if tweet, err := lookupTweet(tweetID); err == nil {
return tweet, nil
}
}
return nil, errors.New("no tweet found in dm")
}
func sendDM(text string, userID int64) (*twitter.DirectMessage, error) {
log.Printf("sending a dm to userID %d: %s\n", userID, text)
dm, resp, err := twitterAPIClient.DirectMessages.New(&twitter.DirectMessageNewParams{
UserID: userID,
Text: text,
})
if err != nil {
return nil, fmt.Errorf("new dm error: %s", err)
}
resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return nil, fmt.Errorf("new dm response status code : %d", resp.StatusCode)
}
return dm, nil
}
func handleDM(dm *twitter.DirectMessage, ch chan<- error) {
logMessageStruct(dm, "DM")
if dm.RecipientScreenName != twitterUsername {
// don't react these events
return
}
if tweet, err := extractTweetFromDM(dm); err != nil {
if dm.SenderScreenName != twitterUsername {
// no tweet found, just mock the user dm'ing the bot
responseText := transformTwitterText(dm.Text)
if DEBUG {
log.Println("dm'ing back:", responseText)
} else {
_, err := sendDM(responseText, dm.SenderID)
if err != nil {
ch <- err
return
}
}
} else {
log.Println("DM'd self with invalid message", dm.Text)
}
} else {
if tweet, err := handleTweet(tweet, ch, false); err != nil {
ch <- fmt.Errorf("error handling tweet from dm: %s", err)
_, err := sendDM(transformTwitterText("An error occurred. Please try again"), dm.SenderID)
if err != nil {
ch <- err
return
}
} else {
_, err := sendDM(fmt.Sprintf("https://twitter.com/%s/status/%s", twitterUsername, tweet.IDStr), dm.SenderID)
if err != nil {
ch <- err
return
}
}
}
}
func handleStreamLimit(sl *twitter.StreamLimit) {
logMessage(sl, "stream limit message")
}
func handleStreamDisconnect(sd *twitter.StreamDisconnect) {
logMessage(sd, "stream disconnect message")
}
func handleWarning(w *twitter.StallWarning) {
logMessage(w, "stall warning")
}
func handleOther(message interface{}) {
logMessage(message, `"other" message type`)
}
| rjchee/spongemock | cmd/worker/twitter.go | GO | mit | 8,721 |
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: google/ads/googleads/v1/common/tag_snippet.proto
package common
import (
fmt "fmt"
math "math"
proto "github.com/golang/protobuf/proto"
wrappers "github.com/golang/protobuf/ptypes/wrappers"
enums "google.golang.org/genproto/googleapis/ads/googleads/v1/enums"
_ "google.golang.org/genproto/googleapis/api/annotations"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
// The site tag and event snippet pair for a TrackingCodeType.
type TagSnippet struct {
// The type of the generated tag snippets for tracking conversions.
Type enums.TrackingCodeTypeEnum_TrackingCodeType `protobuf:"varint,1,opt,name=type,proto3,enum=google.ads.googleads.v1.enums.TrackingCodeTypeEnum_TrackingCodeType" json:"type,omitempty"`
// The format of the web page where the tracking tag and snippet will be
// installed, e.g. HTML.
PageFormat enums.TrackingCodePageFormatEnum_TrackingCodePageFormat `protobuf:"varint,2,opt,name=page_format,json=pageFormat,proto3,enum=google.ads.googleads.v1.enums.TrackingCodePageFormatEnum_TrackingCodePageFormat" json:"page_format,omitempty"`
// The site tag that adds visitors to your basic remarketing lists and sets
// new cookies on your domain.
GlobalSiteTag *wrappers.StringValue `protobuf:"bytes,3,opt,name=global_site_tag,json=globalSiteTag,proto3" json:"global_site_tag,omitempty"`
// The event snippet that works with the site tag to track actions that
// should be counted as conversions.
EventSnippet *wrappers.StringValue `protobuf:"bytes,4,opt,name=event_snippet,json=eventSnippet,proto3" json:"event_snippet,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *TagSnippet) Reset() { *m = TagSnippet{} }
func (m *TagSnippet) String() string { return proto.CompactTextString(m) }
func (*TagSnippet) ProtoMessage() {}
func (*TagSnippet) Descriptor() ([]byte, []int) {
return fileDescriptor_24cd5966e9dfdab2, []int{0}
}
func (m *TagSnippet) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_TagSnippet.Unmarshal(m, b)
}
func (m *TagSnippet) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_TagSnippet.Marshal(b, m, deterministic)
}
func (m *TagSnippet) XXX_Merge(src proto.Message) {
xxx_messageInfo_TagSnippet.Merge(m, src)
}
func (m *TagSnippet) XXX_Size() int {
return xxx_messageInfo_TagSnippet.Size(m)
}
func (m *TagSnippet) XXX_DiscardUnknown() {
xxx_messageInfo_TagSnippet.DiscardUnknown(m)
}
var xxx_messageInfo_TagSnippet proto.InternalMessageInfo
func (m *TagSnippet) GetType() enums.TrackingCodeTypeEnum_TrackingCodeType {
if m != nil {
return m.Type
}
return enums.TrackingCodeTypeEnum_UNSPECIFIED
}
func (m *TagSnippet) GetPageFormat() enums.TrackingCodePageFormatEnum_TrackingCodePageFormat {
if m != nil {
return m.PageFormat
}
return enums.TrackingCodePageFormatEnum_UNSPECIFIED
}
func (m *TagSnippet) GetGlobalSiteTag() *wrappers.StringValue {
if m != nil {
return m.GlobalSiteTag
}
return nil
}
func (m *TagSnippet) GetEventSnippet() *wrappers.StringValue {
if m != nil {
return m.EventSnippet
}
return nil
}
func init() {
proto.RegisterType((*TagSnippet)(nil), "google.ads.googleads.v1.common.TagSnippet")
}
func init() {
proto.RegisterFile("google/ads/googleads/v1/common/tag_snippet.proto", fileDescriptor_24cd5966e9dfdab2)
}
var fileDescriptor_24cd5966e9dfdab2 = []byte{
// 421 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x52, 0x4f, 0x6b, 0xdb, 0x30,
0x14, 0xc7, 0x6e, 0xd9, 0x41, 0x5d, 0x57, 0xf0, 0x29, 0x94, 0x52, 0x4a, 0x4e, 0x3d, 0x49, 0x73,
0x07, 0x3b, 0x68, 0xec, 0xe0, 0x36, 0x5b, 0xaf, 0x21, 0x09, 0x61, 0x8c, 0x80, 0x79, 0x89, 0x5f,
0x85, 0x98, 0x2d, 0x69, 0x96, 0x92, 0xd1, 0xaf, 0xb3, 0xe3, 0x3e, 0xca, 0x3e, 0xc6, 0x8e, 0xfd,
0x14, 0xc3, 0x92, 0xec, 0x0e, 0x4a, 0x46, 0x7b, 0xf2, 0xcf, 0x7a, 0xbf, 0x3f, 0xef, 0x49, 0x8f,
0xbc, 0x15, 0x5a, 0x8b, 0x1a, 0x19, 0x54, 0x96, 0x05, 0xd8, 0xa1, 0x5d, 0xce, 0x36, 0xba, 0x69,
0xb4, 0x62, 0x0e, 0x44, 0x69, 0x95, 0x34, 0x06, 0x1d, 0x35, 0xad, 0x76, 0x3a, 0x3b, 0x0f, 0x34,
0x0a, 0x95, 0xa5, 0x83, 0x82, 0xee, 0x72, 0x1a, 0x14, 0xa7, 0x1f, 0xf7, 0x39, 0xa2, 0xda, 0x36,
0x96, 0xb9, 0x16, 0x36, 0xdf, 0xa4, 0x12, 0xe5, 0x46, 0x57, 0x58, 0x1a, 0x10, 0x58, 0xde, 0xe9,
0xb6, 0x81, 0x68, 0x7f, 0xfa, 0xfe, 0x25, 0x72, 0x77, 0x6f, 0x30, 0xea, 0xce, 0x7a, 0x9d, 0x91,
0x0c, 0x94, 0xd2, 0x0e, 0x9c, 0xd4, 0xca, 0xc6, 0x6a, 0x6c, 0x9a, 0xf9, 0xbf, 0xf5, 0xf6, 0x8e,
0xfd, 0x68, 0xc1, 0x18, 0x6c, 0x63, 0x7d, 0xfc, 0x27, 0x25, 0x64, 0x01, 0x62, 0x1e, 0x26, 0xcd,
0xbe, 0x90, 0xc3, 0xce, 0x7a, 0x94, 0x5c, 0x24, 0x97, 0x6f, 0xae, 0x26, 0x74, 0xdf, 0xc8, 0xbe,
0x27, 0xba, 0x88, 0x3d, 0xdd, 0xe8, 0x0a, 0x17, 0xf7, 0x06, 0x3f, 0xa9, 0x6d, 0xf3, 0xe4, 0x70,
0xe6, 0x1d, 0xb3, 0xef, 0xe4, 0xe8, 0x9f, 0x99, 0x47, 0xa9, 0x0f, 0x98, 0xbe, 0x20, 0x60, 0x0a,
0x02, 0x3f, 0x7b, 0xf1, 0x93, 0x98, 0xc7, 0xd2, 0x8c, 0x98, 0x01, 0x67, 0x13, 0x72, 0x22, 0x6a,
0xbd, 0x86, 0xba, 0xb4, 0xd2, 0x61, 0xe9, 0x40, 0x8c, 0x0e, 0x2e, 0x92, 0xcb, 0xa3, 0xab, 0xb3,
0x3e, 0xb6, 0xbf, 0x15, 0x3a, 0x77, 0xad, 0x54, 0x62, 0x09, 0xf5, 0x16, 0x67, 0xc7, 0x41, 0x34,
0x97, 0x0e, 0x17, 0x20, 0xb2, 0x82, 0x1c, 0xe3, 0x0e, 0x95, 0xeb, 0xb7, 0x61, 0x74, 0xf8, 0x0c,
0x8f, 0xd7, 0x5e, 0x12, 0x6f, 0xf5, 0xfa, 0x21, 0x21, 0xe3, 0x8d, 0x6e, 0xe8, 0xff, 0x17, 0xe8,
0xfa, 0xe4, 0xf1, 0x21, 0xa6, 0x9d, 0xe9, 0x34, 0xf9, 0x3a, 0x89, 0x12, 0xa1, 0x6b, 0x50, 0x82,
0xea, 0x56, 0x30, 0x81, 0xca, 0x47, 0xf6, 0x4b, 0x62, 0xa4, 0xdd, 0xb7, 0xc4, 0x1f, 0xc2, 0xe7,
0x67, 0x7a, 0x70, 0x5b, 0x14, 0xbf, 0xd2, 0xf3, 0xdb, 0x60, 0x56, 0x54, 0x96, 0x06, 0xd8, 0xa1,
0x65, 0x4e, 0x6f, 0x3c, 0xed, 0x77, 0x4f, 0x58, 0x15, 0x95, 0x5d, 0x0d, 0x84, 0xd5, 0x32, 0x5f,
0x05, 0xc2, 0x43, 0x3a, 0x0e, 0xa7, 0x9c, 0x17, 0x95, 0xe5, 0x7c, 0xa0, 0x70, 0xbe, 0xcc, 0x39,
0x0f, 0xa4, 0xf5, 0x2b, 0xdf, 0xdd, 0xbb, 0xbf, 0x01, 0x00, 0x00, 0xff, 0xff, 0x1c, 0x5f, 0xe8,
0x51, 0x61, 0x03, 0x00, 0x00,
}
| pushbullet/engineer | vendor/google.golang.org/genproto/googleapis/ads/googleads/v1/common/tag_snippet.pb.go | GO | mit | 6,534 |
'use strict';
require('../../../TestHelper');
/* global bootstrapDiagram, inject */
var modelingModule = require('../../../../lib/features/modeling'),
bendpointsModule = require('../../../../lib/features/bendpoints'),
rulesModule = require('./rules'),
interactionModule = require('../../../../lib/features/interaction-events'),
canvasEvent = require('../../../util/MockEvents').createCanvasEvent;
describe('features/bendpoints', function() {
beforeEach(bootstrapDiagram({ modules: [ modelingModule, bendpointsModule, interactionModule, rulesModule ] }));
beforeEach(inject(function(dragging) {
dragging.setOptions({ manual: true });
}));
var rootShape, shape1, shape2, shape3, connection, connection2;
beforeEach(inject(function(elementFactory, canvas) {
rootShape = elementFactory.createRoot({
id: 'root'
});
canvas.setRootElement(rootShape);
shape1 = elementFactory.createShape({
id: 'shape1',
type: 'A',
x: 100, y: 100, width: 300, height: 300
});
canvas.addShape(shape1, rootShape);
shape2 = elementFactory.createShape({
id: 'shape2',
type: 'A',
x: 500, y: 100, width: 100, height: 100
});
canvas.addShape(shape2, rootShape);
shape3 = elementFactory.createShape({
id: 'shape3',
type: 'B',
x: 500, y: 400, width: 100, height: 100
});
canvas.addShape(shape3, rootShape);
connection = elementFactory.createConnection({
id: 'connection',
waypoints: [ { x: 250, y: 250 }, { x: 550, y: 250 }, { x: 550, y: 150 } ],
source: shape1,
target: shape2
});
canvas.addConnection(connection, rootShape);
connection2 = elementFactory.createConnection({
id: 'connection2',
waypoints: [ { x: 250, y: 250 }, { x: 550, y: 450 } ],
source: shape1,
target: shape2
});
canvas.addConnection(connection2, rootShape);
}));
describe('activation', function() {
it('should show on hover', inject(function(eventBus, canvas, elementRegistry) {
// given
var layer = canvas.getLayer('overlays');
// when
eventBus.fire('element.hover', { element: connection, gfx: elementRegistry.getGraphics(connection) });
// then
// 3 visible + 1 invisible bendpoint are shown
expect(layer.node.querySelectorAll('.djs-bendpoint').length).to.equal(4);
expect(layer.node.querySelectorAll('.djs-segment-dragger').length).to.equal(2);
}));
it('should show on select', inject(function(selection, canvas, elementRegistry) {
// given
var layer = canvas.getLayer('overlays');
// when
selection.select(connection);
// then
// 3 visible + 1 invisible bendpoint are shown
expect(layer.node.querySelectorAll('.djs-bendpoint').length).to.equal(4);
expect(layer.node.querySelectorAll('.djs-segment-dragger').length).to.equal(2);
}));
it('should activate bendpoint move', inject(function(dragging, eventBus, elementRegistry, bendpoints) {
// when
eventBus.fire('element.hover', { element: connection, gfx: elementRegistry.getGraphics(connection) });
eventBus.fire('element.mousemove', {
element: connection,
originalEvent: canvasEvent({ x: 500, y: 250 })
});
eventBus.fire('element.mousedown', {
element: connection,
originalEvent: canvasEvent({ x: 500, y: 250 })
});
var draggingContext = dragging.active();
// then
expect(draggingContext).to.exist;
expect(draggingContext.prefix).to.eql('bendpoint.move');
}));
it('should activate parallel move', inject(function(dragging, eventBus, elementRegistry, bendpoints) {
// precondition
var intersectionStart = connection.waypoints[0].x,
intersectionEnd = connection.waypoints[1].x,
intersectionMid = intersectionEnd - (intersectionEnd - intersectionStart) / 2;
// when
eventBus.fire('element.hover', { element: connection, gfx: elementRegistry.getGraphics(connection) });
eventBus.fire('element.mousemove', {
element: connection,
originalEvent: canvasEvent({ x: intersectionMid, y: 250 })
});
eventBus.fire('element.mousedown', {
element: connection,
originalEvent: canvasEvent({ x: intersectionMid, y: 250 })
});
var draggingContext = dragging.active();
// then
expect(draggingContext).to.exist;
expect(draggingContext.prefix).to.eql('connectionSegment.move');
}));
});
});
| camunda-internal/bpmn-quiz | node_modules/diagram-js/test/spec/features/bendpoints/BendpointsSpec.js | JavaScript | mit | 4,569 |
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import Landing from './../Landing'
import * as UserActions from './../actions/User'
function mapStateToProps(state) {
return {
user: state.userStore.user
}
}
const mapDispatchToProps = (dispatch) => {
return bindActionCreators(UserActions, dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps)(Landing) | Briseus/Kape | src/containers/Landing.js | JavaScript | mit | 425 |
# Made by Christian Oliveros on 04/10/2017 for MMKF15
# Imports Used
import decimal as d
try:
from .constants import VL, EPSILON, STEP_MAX
except SystemError as e:
from constants import VL, EPSILON, STEP_MAX
class Vector3(object):
"""Class that represents a Vector with 3 coordinates"""
def __init__(self, x=0.0, y=0.0, z=0.0):
super(Vector3, self).__init__()
self.x = d.Decimal(x)
self.y = d.Decimal(y)
self.z = d.Decimal(z)
"""Class Representation"""
def __repr__(self):
return "Vector3(x=%r,y=%r,z=%r)" % (self.x, self.y, self.z)
"""Class String Representation"""
def __str__(self):
return "(%s, %s, %s)" % (str(self.x), str(self.y), str(self.z))
"""Copy this vector in new instance"""
def copy(self):
return Vector3(self.x, self.y, self.z)
"""Get Square Magnitude of vector"""
def sqrMagnitude(self):
dec2 = d.Decimal(2.0)
return self.x**dec2 + self.y**dec2 + self.z**dec2
"""Get Magnitude of vector"""
def magnitude(self):
return self.sqrMagnitude().sqrt()
"""Unary minus"""
def __neg__(self):
return self * -1
"""Unary addition"""
def __pos__(self):
return self
"""Absolute Value, Equivalent to Magnitude"""
def __abs__(self):
return self.magnitude()
"""In place addition"""
def __iadd__(self, other):
if not isinstance(other, Vector3):
raise TypeError("Expected Vector3 but got '%s'" % str(type(other).__name__))
self.x += other.x
self.y += other.y
self.z += other.z
return self
"""Addition"""
def __add__(self, other):
v = Vector3()
v += other
v += self
return v
"""Reverse Addition"""
def __radd__(self, other):
return self + other
"""In place Scalar Multiplication"""
def __imul__(self, other):
rhs = d.Decimal(other)
self.x *= rhs
self.y *= rhs
self.z *= rhs
return self
"""Scalar Multiplication"""
def __mul__(self, other):
v = self.copy()
v *= other
return v
"""Reverse Addition"""
def __rmul__(self, other):
return self * other
"""In place Substraction"""
def __isub__(self, other):
if not isinstance(other, Vector3):
msg = "Expected Vector3 but got '%s'" % str(type(other).__name__)
raise TypeError(msg)
self += (other * -1)
return self
"""Substraction"""
def __sub__(self, other):
v = self.copy()
v -= other
return v
"""Normalize this vector"""
def normalize(self):
length = self.magnitude()
if length < EPSILON:
self *= 0
return
self *= d.Decimal(1) / length
"""Return this vector normalized"""
def normalized(self):
v = self.copy()
v.normalize()
return v
# Set constant start position
def _setConstants():
try:
from .constants import __name__ as constants_module_name
from .constants import START_POSITION_HEIGHT_OFFSET
except SystemError as e:
from constants import __name__ as constants_module_name
from constants import START_POSITION_HEIGHT_OFFSET
import sys
module = sys.modules[constants_module_name]
setattr(module, 'START_POSITION', Vector3(0, 0, VL - START_POSITION_HEIGHT_OFFSET))
_setConstants()
"""
Generates Lineary Interpolated points from p0 to p1 with steps of size maxStep or less.
If step lesser than EPSILON then no step is done
"""
def interpolatePoints(p0, p1, maxStep=STEP_MAX):
direction = p1 - p0
length_sqr = direction.sqrMagnitude()
if length_sqr < EPSILON**2:
yield p0
return
dist = d.Decimal(0)
one = d.Decimal(1)
segments = int(length_sqr.sqrt() / maxStep)
if segments <= 1:
yield p0
yield p1
return
step = one / d.Decimal(segments)
while True:
yield p0 + (direction * dist)
dist += step
if dist > one:
break
if __name__ == '__main__':
print("Init test")
v = Vector3()
print(v)
v2 = Vector3(1,2,3.3)
print(v2)
print("Square Magnitude test")
print(v.sqrMagnitude())
print(v2.sqrMagnitude())
print("Magnitude test")
print(v.magnitude())
print(v2.magnitude())
print("In place Addition Tests")
try:
v += 1
except Exception as e:
print(e.args)
try:
v3 = Vector3(1,1,1)
v3 += v2
print(v3)
except Exception as e:
print(e.args)
print("Addition Tests")
try:
a = v + 1
except Exception as e:
print(e.args)
try:
v3 = Vector3(1,1,1)
a = v3 + v2
print(a)
except Exception as e:
print(e.args)
print("In place Scalar Multiplication Tests")
try:
v *= Vector3()
except Exception as e:
print(e.args)
try:
v3 = Vector3(1,1,1)
v3 *= 2
print(v3)
except Exception as e:
print(e.args)
print("Scalar Multiplication Tests")
try:
a = v * Vector3()
except Exception as e:
print(e.args)
try:
v3 = Vector3(1,1,1)
a = v3 * 4
print(a)
print("v3=%s" % str(v3))
except Exception as e:
print(e.args)
print("Unary minus test")
v3 = Vector3(1,2,3)
print("v=%s" % str(v3))
print("-v=%s" % str(-v3))
print("Substraction test")
v2 = Vector3(1,0,1)
v3 = Vector3(1,1,0)
print("v2=%s" % str(v2))
print("v3=%s" % str(v3))
print("v3-v2=%s" % str(v3 - v2))
print("v3=%s" % str(v3))
v3 -= v2
print("(v3-=v2)=%s" % str(v3))
print("Normalization Tests")
v3 = Vector3(1,1,1)
print(v3.normalized())
print(v3)
v3.normalize()
print(v3)
v3 = Vector3(0,0,0)
v3.normalize()
print(v3)
print("Interpolation Tests")
p0 = Vector3(0, 0, 0)
p1 = Vector3(1, 1, 1)
a = [v for v in interpolatePoints(p0, p1)]
print("Too long to print but it is here, uncomment if want you to see")
#print(a)
print("Interpolation test for points too close")
print([v for v in interpolatePoints(p0, Vector3(0, EPSILON / d.Decimal(2), 0))])
print("Interpolation test for points really close")
print([v for v in interpolatePoints(p0, Vector3(0, EPSILON, 0))])
print("Interpolation test for points almost really close")
print([v for v in interpolatePoints(p0, Vector3(0, EPSILON * d.Decimal(2), 0))])
| maniatic0/rasppi-printer | Utilities/vector.py | Python | mit | 5,714 |
import Resolver from 'ember/resolver';
import loadInitializers from 'ember/load-initializers';
Ember.MODEL_FACTORY_INJECTIONS = true;
var App = Ember.Application.extend({
modulePrefix: 'tvdb', // TODO: loaded via config
Resolver: Resolver
});
loadInitializers(App, 'tvdb');
export default App;
| bolotyuh/ember-symfony-starterkit | web/ember/foo/app/app.js | JavaScript | mit | 302 |
YUI.add('dataschema-array', function (Y, NAME) {
/**
* Provides a DataSchema implementation which can be used to work with data
* stored in arrays.
*
* @module dataschema
* @submodule dataschema-array
*/
/**
Provides a DataSchema implementation which can be used to work with data
stored in arrays.
See the `apply` method below for usage.
@class DataSchema.Array
@extends DataSchema.Base
@static
**/
var LANG = Y.Lang,
SchemaArray = {
////////////////////////////////////////////////////////////////////////
//
// DataSchema.Array static methods
//
////////////////////////////////////////////////////////////////////////
/**
Applies a schema to an array of data, returning a normalized object
with results in the `results` property. The `meta` property of the
response object is present for consistency, but is assigned an empty
object. If the input data is absent or not an array, an `error`
property will be added.
The input array is expected to contain objects, arrays, or strings.
If _schema_ is not specified or _schema.resultFields_ is not an array,
`response.results` will be assigned the input array unchanged.
When a _schema_ is specified, the following will occur:
If the input array contains strings, they will be copied as-is into the
`response.results` array.
If the input array contains arrays, `response.results` will contain an
array of objects with key:value pairs assuming the fields in
_schema.resultFields_ are ordered in accordance with the data array
values.
If the input array contains objects, the identified
_schema.resultFields_ will be used to extract a value from those
objects for the output result.
_schema.resultFields_ field identifiers are objects with the following properties:
* `key` : <strong>(required)</strong> The locator name (String)
* `parser`: A function or the name of a function on `Y.Parsers` used
to convert the input value into a normalized type. Parser
functions are passed the value as input and are expected to
return a value.
If no value parsing is needed, you can use strings as identifiers
instead of objects (see example below).
@example
// Process array of arrays
var schema = { resultFields: [ 'fruit', 'color' ] },
data = [
[ 'Banana', 'yellow' ],
[ 'Orange', 'orange' ],
[ 'Eggplant', 'purple' ]
];
var response = Y.DataSchema.Array.apply(schema, data);
// response.results[0] is { fruit: "Banana", color: "yellow" }
// Process array of objects
data = [
{ fruit: 'Banana', color: 'yellow', price: '1.96' },
{ fruit: 'Orange', color: 'orange', price: '2.04' },
{ fruit: 'Eggplant', color: 'purple', price: '4.31' }
];
response = Y.DataSchema.Array.apply(schema, data);
// response.results[0] is { fruit: "Banana", color: "yellow" }
// Use parsers
schema.resultFields = [
{
key: 'fruit',
parser: function (val) { return val.toUpperCase(); }
},
{
key: 'price',
parser: 'number' // Uses Y.Parsers.number
}
];
response = Y.DataSchema.Array.apply(schema, data);
// Note price was converted from a numeric string to a number
// response.results[0] looks like { fruit: "BANANA", price: 1.96 }
@method apply
@param {Object} [schema] Schema to apply. Supported configuration
properties are:
@param {Array} [schema.resultFields] Field identifiers to
locate/assign values in the response records. See above for
details.
@param {Array} data Array data.
@return {Object} An Object with properties `results` and `meta`
@static
**/
apply: function(schema, data) {
var data_in = data,
data_out = {results:[],meta:{}};
if(LANG.isArray(data_in)) {
if(schema && LANG.isArray(schema.resultFields)) {
// Parse results data
data_out = SchemaArray._parseResults.call(this, schema.resultFields, data_in, data_out);
}
else {
data_out.results = data_in;
}
}
else {
data_out.error = new Error("Array schema parse failure");
}
return data_out;
},
/**
* Schema-parsed list of results from full data
*
* @method _parseResults
* @param fields {Array} Schema to parse against.
* @param array_in {Array} Array to parse.
* @param data_out {Object} In-progress parsed data to update.
* @return {Object} Parsed data object.
* @static
* @protected
*/
_parseResults: function(fields, array_in, data_out) {
var results = [],
result, item, type, field, key, value, i, j;
for(i=array_in.length-1; i>-1; i--) {
result = {};
item = array_in[i];
type = (LANG.isObject(item) && !LANG.isFunction(item)) ? 2 : (LANG.isArray(item)) ? 1 : (LANG.isString(item)) ? 0 : -1;
if(type > 0) {
for(j=fields.length-1; j>-1; j--) {
field = fields[j];
key = (!LANG.isUndefined(field.key)) ? field.key : field;
value = (!LANG.isUndefined(item[key])) ? item[key] : item[j];
result[key] = Y.DataSchema.Base.parse.call(this, value, field);
}
}
else if(type === 0) {
result = item;
}
else {
//TODO: null or {}?
result = null;
}
results[i] = result;
}
data_out.results = results;
return data_out;
}
};
Y.DataSchema.Array = Y.mix(SchemaArray, Y.DataSchema.Base);
}, '3.10.3', {"requires": ["dataschema-base"]});
| braz/mojito-helloworld | node_modules/mojito/node_modules/yui/dataschema-array/dataschema-array.js | JavaScript | mit | 6,625 |
using Reactive.Bindings;
namespace LiveLinq.Tests
{
public class SelectObservableCollectionViewModel
{
public SelectObservableCollectionViewModel(string name)
{
Name = new ReactiveProperty<string>(name);
}
public ReactiveProperty<string> Name { get; private set; }
}
}
| ApocalypticOctopus/Apocalyptic.Utilities.Net | LiveLinq.Tests/SelectObservableCollectionViewModel.cs | C# | mit | 327 |
import { hash as calculateHash } from '@collectable/core';
import { getHash } from '../internals/primitives';
import { HashMapStructure } from '../internals/HashMap';
import { NOTHING } from '../internals/nodes';
export function has<K, V> (key: K, map: HashMapStructure<K, V>): boolean;
export function has<K, V> (key: K, map: HashMapStructure<K, V>): boolean {
const hash = calculateHash(key);
return getHash(NOTHING, hash, key, map) !== NOTHING;
} | frptools/collectable | packages/map/src/functions/has.ts | TypeScript | mit | 454 |
/*
Licensed under MIT license
(c) 2017 Reeleezee BV
*/
package misc
import (
"crypto/rand"
"fmt"
)
func MaxString(data interface{}, length int) string {
if data != nil {
data := data.(string)
if len(data) > length {
return data[:length]
}
return data
}
return ""
}
// NO REAL UUID!
// Consider a better library:
// https://github.com/satori/go.uuid
// https://github.com/pborman/uuid
func PseudoUuidV4() (uuid string) {
b := make([]byte, 16)
_, err := rand.Read(b)
if err != nil {
panic(err)
}
b[6] = (b[6] & 0x0f) | 0x40 // Version 4
b[8] = (b[8] & 0xbf) | 0x80 // Variant is 10
uuid = fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
return
}
| reeleezee/reeleezee-api-go | misc/string.go | GO | mit | 696 |
module.exports = (function () {
var moduleName = 'cut-media-queries';
var lolArrayDiff = function(array1, array2) {
var diff1 = array1.filter(function(elem){
return array2.indexOf(elem) === -1;
});
var diff2 = array2.filter(function(elem){
return array1.indexOf(elem) === -1;
});
return diff1.concat(diff2);
}
return {
/**
* Option's name as it should be used in config.
*/
name: moduleName,
/**
* List of syntaxes that this options supports.
* This depends on Gonzales PE possibilities.
* Currently the following work fine: css, less, sass, scss.
*/
syntax: ['css'],
/**
* List patterns for option's acceptable value.
* You can play with following:
* - boolean: [true, false]
* - string: /^panda$/
* - number: true
*/
accepts: {
string: /.*/
},
/**
* If `accepts` is not enough for you, replace it with custom `setValue`
* function.
*
* @param {Object} value Value that a user sets in configuration
* @return {Object} Value that you would like to use in `process` method
*
* setValue: function(value) {
* // Do something with initial value.
* var final = value * 4;
*
* // Return final value you will use in `process` method.
* return final;
* },
*/
/**
* Fun part.
* Do something with AST.
* For example, replace all comments with flipping tables.
*
* @param {String} nodeType Type of current node
* @param {Array} node Node's content
*/
process: function (nodeType, node) {
if (nodeType === 'stylesheet') {
var length = node.length;
var options = this.getValue(moduleName).split(',');
while (length--) {
if (node[length][0] == 'atruler') {
var removeNode = false;
//Gather media query info
node[length].forEach(function (innerNode) {
if (removeNode == true) return;
if (innerNode[0] == 'atrulerq') {
var queries = [];
innerNode.forEach(function (query) {
if (query[0] == 'braces') {
var ident = query.filter(function (elem) {
return elem[0] == 'ident';
});
var dimensions = query.filter(function (elem) {
return elem[0] == 'dimension';
});
if (ident.length != 0) {
queries.push(ident[0][1] + ":" + dimensions[0][1][1] + dimensions[0][2][1]);
}
}
});
if (lolArrayDiff(queries, options).length == 0) {
removeNode = true;
}
}
});
if (removeNode) {
node.splice(length, 1);
}
}
}
}
}
};
})();
| iVariable/csscomb-cut-media-queries | options/cut-media-queries.js | JavaScript | mit | 2,636 |
<?php
/**
* Copyright (c) 2017 - 2019 - Bas Milius <bas@mili.us>
*
* This file is part of the Cappuccino package.
*
* For the full copyright and license information, please view the
* LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Cappuccino\Loader;
use Cappuccino\Error\LoaderError;
use Cappuccino\Source;
use function get_class;
use function implode;
use function sprintf;
/**
* Class ChainLoader
*
* @author Bas Milius <bas@mili.us>
* @package Cappuccino\Loader
* @since 1.0.0
*/
final class ChainLoader implements LoaderInterface
{
/**
* @var bool[]
*/
private $hasSourceCache = [];
/**
* @var LoaderInterface[]
*/
private $loaders = [];
/**
* ChainLoader constructor.
*
* @param array $loaders
*
* @author Bas Milius <bas@mili.us>
* @since 1.0.0
*/
public function __construct(array $loaders = [])
{
foreach ($loaders as $loader)
$this->addLoader($loader);
}
/**
* Adds a new loader.
*
* @param LoaderInterface $loader
*
* @author Bas Milius <bas@mili.us>
* @since 1.0.0
*/
public function addLoader(LoaderInterface $loader): void
{
$this->loaders[] = $loader;
$this->hasSourceCache = [];
}
/**
* Gets all loaders attached to this chain.
*
* @return LoaderInterface[]
* @author Bas Milius <bas@mili.us>
* @since 1.0.0
*/
public function getLoaders(): array
{
return $this->loaders;
}
/**
* {@inheritdoc}
* @author Bas Milius <bas@mili.us>
* @since 1.0.0
*/
public function getSourceContext(string $name): Source
{
$exceptions = [];
foreach ($this->loaders as $loader)
{
if (!$loader->exists($name))
continue;
try
{
return $loader->getSourceContext($name);
}
catch (LoaderError $e)
{
$exceptions[] = $e->getMessage();
}
}
throw new LoaderError(sprintf('Template "%s" is not defined%s.', $name, $exceptions ? ' (' . implode(', ', $exceptions) . ')' : ''));
}
/**
* {@inheritdoc}
* @author Bas Milius <bas@mili.us>
* @since 1.0.0
*/
public function exists(string $name): bool
{
if (isset($this->hasSourceCache[$name]))
return $this->hasSourceCache[$name];
foreach ($this->loaders as $loader)
if ($loader->exists($name))
return $this->hasSourceCache[$name] = true;
return $this->hasSourceCache[$name] = false;
}
/**
* {@inheritdoc}
* @author Bas Milius <bas@mili.us>
* @since 1.0.0
*/
public function getCacheKey(string $name): string
{
$exceptions = [];
foreach ($this->loaders as $loader)
{
if (!$loader->exists($name))
continue;
try
{
return $loader->getCacheKey($name);
}
catch (LoaderError $e)
{
$exceptions[] = get_class($loader) . ': ' . $e->getMessage();
}
}
throw new LoaderError(sprintf('Template "%s" is not defined%s.', $name, $exceptions ? ' (' . implode(', ', $exceptions) . ')' : ''));
}
/**
* {@inheritdoc}
* @author Bas Milius <bas@mili.us>
* @since 1.0.0
*/
public function isFresh(string $name, int $time): bool
{
$exceptions = [];
foreach ($this->loaders as $loader)
{
if (!$loader->exists($name))
continue;
try
{
return $loader->isFresh($name, $time);
}
catch (LoaderError $e)
{
$exceptions[] = get_class($loader) . ': ' . $e->getMessage();
}
}
throw new LoaderError(sprintf('Template "%s" is not defined%s.', $name, $exceptions ? ' (' . implode(', ', $exceptions) . ')' : ''));
}
}
| basmilius/Cappuccino | src/Cappuccino/Loader/ChainLoader.php | PHP | mit | 3,459 |
# This file is NOT licensed under the GPLv3, which is the license for the rest
# of YouCompleteMe.
#
# Here's the license text for this file:
#
# This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or
# distribute this software, either in source code form or as a compiled
# binary, for any purpose, commercial or non-commercial, and by any
# means.
#
# In jurisdictions that recognize copyright laws, the author or authors
# of this software dedicate any and all copyright interest in the
# software to the public domain. We make this dedication for the benefit
# of the public at large and to the detriment of our heirs and
# successors. We intend this dedication to be an overt act of
# relinquishment in perpetuity of all present and future rights to this
# software under copyright law.
#
# 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 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.
#
# For more information, please refer to <http://unlicense.org/>
import os
import ycm_core
from sys import platform as _platform
# These are the compilation flags that will be used in case there's no
# compilation database set (by default, one is not set).
# CHANGE THIS LIST OF FLAGS. YES, THIS IS THE DROID YOU HAVE BEEN LOOKING FOR.
flags = [
'-Wall',
'-Wextra',
'-Werror',
'-Wno-long-long',
'-Wno-variadic-macros',
'-fexceptions',
'-DNDEBUG',
# THIS IS IMPORTANT! Without a "-std=<something>" flag, clang won't know which
# language to use when compiling headers. So it will guess. Badly. So C++
# headers will be compiled as C headers. You don't want that so ALWAYS specify
# a "-std=<something>".
# For a C project, you would set this to something like 'c99' instead of
# 'c++11'.
'-std=c++0x',
# ...and the same thing goes for the magic -x option which specifies the
# language that the files to be compiled are written in. This is mostly
# relevant for c++ headers.
# For a C project, you would set this to 'c' instead of 'c++'.
'-x',
'c++',
'-I./',
'-I../common/',
]
# Xcode for std stuff on OS X
if _platform == "darwin":
flags.append('-isystem/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1')
# Set this to the absolute path to the folder (NOT the file!) containing the
# compile_commands.json file to use that instead of 'flags'. See here for
# more details: http://clang.llvm.org/docs/JSONCompilationDatabase.html
#
# You can get CMake to generate this file for you by adding:
# set( CMAKE_EXPORT_COMPILE_COMMANDS 1 )
# to your CMakeLists.txt file.
#
# Most projects will NOT need to set this to anything; you can just change the
# 'flags' list of compilation flags. Notice that YCM itself uses that approach.
compilation_database_folder = ''
if os.path.exists( compilation_database_folder ):
database = ycm_core.CompilationDatabase( compilation_database_folder )
else:
database = None
SOURCE_EXTENSIONS = [ '.cpp', '.cxx', '.cc', '.c', '.m', '.mm' ]
def DirectoryOfThisScript():
return os.path.dirname( os.path.abspath( __file__ ) )
def MakeRelativePathsInFlagsAbsolute( flags, working_directory ):
if not working_directory:
return list( flags )
new_flags = []
make_next_absolute = False
path_flags = [ '-isystem', '-I', '-iquote', '--sysroot=' ]
for flag in flags:
new_flag = flag
if make_next_absolute:
make_next_absolute = False
if not flag.startswith( '/' ):
new_flag = os.path.join( working_directory, flag )
for path_flag in path_flags:
if flag == path_flag:
make_next_absolute = True
break
if flag.startswith( path_flag ):
path = flag[ len( path_flag ): ]
new_flag = path_flag + os.path.join( working_directory, path )
break
if new_flag:
new_flags.append( new_flag )
return new_flags
def IsHeaderFile( filename ):
extension = os.path.splitext( filename )[ 1 ]
return extension in [ '.h', '.hxx', '.hpp', '.hh' ]
def GetCompilationInfoForFile( filename ):
# The compilation_commands.json file generated by CMake does not have entries
# for header files. So we do our best by asking the db for flags for a
# corresponding source file, if any. If one exists, the flags for that file
# should be good enough.
if IsHeaderFile( filename ):
basename = os.path.splitext( filename )[ 0 ]
for extension in SOURCE_EXTENSIONS:
replacement_file = basename + extension
if os.path.exists( replacement_file ):
compilation_info = database.GetCompilationInfoForFile(
replacement_file )
if compilation_info.compiler_flags_:
return compilation_info
return None
return database.GetCompilationInfoForFile( filename )
def FlagsForFile( filename, **kwargs ):
if database:
# Bear in mind that compilation_info.compiler_flags_ does NOT return a
# python list, but a "list-like" StringVec object
compilation_info = GetCompilationInfoForFile( filename )
if not compilation_info:
return None
final_flags = MakeRelativePathsInFlagsAbsolute(
compilation_info.compiler_flags_,
compilation_info.compiler_working_dir_ )
else:
relative_to = DirectoryOfThisScript()
final_flags = MakeRelativePathsInFlagsAbsolute( flags, relative_to )
return {
'flags': final_flags,
'do_cache': True
}
| astrellon/cotsb | server/.ycm_extra_conf.py | Python | mit | 5,739 |
using System;
using System.Collections.Generic;
using System.Linq;
using SMLimitless.Interfaces;
using SMLimitless.Physics;
namespace SMLimitless.Extensions
{
/// <summary>
/// Contains extension methods for types implementing the <see
/// cref="IPositionable2" /> interface.
/// </summary>
public static class PositionableExtensions
{
/// <summary>
/// Returns a rectangle that can contain all the given positionables in
/// an enumerable.
/// </summary>
/// <param name="positionables">The enumerable containing the positionables.</param>
/// <returns></returns>
public static BoundingRectangle GetBoundsOfPositionables(this IEnumerable<IPositionable2> positionables)
{
if (!positionables.Any()) { return BoundingRectangle.NaN; }
// so there's really no elegant initial value for result, except the
// bounds of First()...
var first = positionables.First();
BoundingRectangle result = new BoundingRectangle(first.Position, first.Size + first.Position);
foreach (var positionable in positionables.Skip(1)) // ...so we need to treat it specially
{
BoundingRectangle bounds = new BoundingRectangle(positionable.Position, positionable.Size + positionable.Position);
if (bounds.Left < result.Left)
{
result.Width += (bounds.X + result.X);
result.X = bounds.X;
}
else if (bounds.Right > result.Right)
{
result.Width = (bounds.X + bounds.Width);
}
if (bounds.Top < result.Top)
{
result.Height = (bounds.Y + result.Y);
result.Y = bounds.Y;
}
else if (bounds.Bottom > result.Bottom)
{
result.Height = (bounds.Y + bounds.Height);
}
}
return result;
}
}
}
| smldev/smlimitless | MonoGame/SMLimitless/SMLimitless/Extensions/PositionableExtensions.cs | C# | mit | 1,698 |
package com.group.cms.core.dao;
import java.io.Serializable;
import java.util.List;
public interface BaseDao<T, ID extends Serializable> {
/**
* insert
* @param entity
* @return 插入的行数
*/
int insert(T entity);
/**
* update
* @param entity
* @return 修改的行数
*/
int update(T entity);
/**
* delete
* @param id
* @return 删除的行数
*/
int delete(ID id);
/**
*
* @param name
* @param operator
* @param value
* @return
*/
int deleteBy(String name, String operator, String value);
/**
* select
* @param id
* @return
*/
T select(ID id);
/**
*
* @param name
* @param operator
* @param value
* @return
*/
List<T> findBy(String name, String operator, String value);
}
| iyujian/cms | cms-core/src/main/java/com/group/cms/core/dao/BaseDao.java | Java | mit | 762 |
package xyz.gsora.toot;
import MastodonTypes.Status;
import android.app.IntentService;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import io.realm.Realm;
import io.realm.RealmConfiguration;
import retrofit2.Response;
import xyz.gsora.toot.Mastodon.Mastodon;
import java.util.ArrayList;
import java.util.Random;
import static xyz.gsora.toot.Timeline.TIMELINE_MAIN;
/**
* An {@link IntentService} subclass for handling asynchronous toot sending.
* <p>
*/
@SuppressWarnings("WeakerAccess")
public class PostStatus extends IntentService {
public static final String STATUS = "xyz.gsora.toot.extra.status";
public static final String REPLYID = "xyz.gsora.toot.extra.replyid";
public static final String MEDIAIDS = "xyz.gsora.toot.extra.mediaids";
public static final String SENSITIVE = "xyz.gsora.toot.extra.sensitive";
public static final String SPOILERTEXT = "xyz.gsora.toot.extra.spoilertext";
public static final String VISIBILITY = "xyz.gsora.toot.extra.visibility";
private static final String TAG = PostStatus.class.getSimpleName();
private Realm realm;
private NotificationManager nM;
private int notificationId;
public PostStatus() {
super("PostStatus");
}
@Override
protected void onHandleIntent(Intent intent) {
Mastodon m = Mastodon.getInstance();
realm = Realm.getInstance(new RealmConfiguration.Builder().name(TIMELINE_MAIN).build());
nM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Random r = new Random();
notificationId = r.nextInt();
if (intent != null) {
final String status = intent.getStringExtra(STATUS);
final String replyid = intent.getStringExtra(REPLYID);
final ArrayList<String> mediaids = intent.getStringArrayListExtra(MEDIAIDS);
final Boolean sensitive = intent.getBooleanExtra(SENSITIVE, false);
final String spoilertext = intent.getStringExtra(SPOILERTEXT);
final Integer visibility = intent.getIntExtra(VISIBILITY, 0);
Mastodon.StatusVisibility trueVisibility = Mastodon.StatusVisibility.PUBLIC;
switch (visibility) {
case 0:
trueVisibility = Mastodon.StatusVisibility.PUBLIC;
break;
case 1:
trueVisibility = Mastodon.StatusVisibility.DIRECT;
break;
case 2:
trueVisibility = Mastodon.StatusVisibility.UNLISTED;
break;
case 3:
trueVisibility = Mastodon.StatusVisibility.PRIVATE;
break;
}
// create a new "toot sending" notification
NotificationCompat.Builder mBuilder = buildNotification(
"Sending toot",
null,
true
);
nM.notify(notificationId, mBuilder.build());
Observable<Response<Status>> post = m.postPublicStatus(status, replyid, mediaids, sensitive, spoilertext, trueVisibility);
post
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(
this::postSuccessful,
this::postError
);
}
}
private void postSuccessful(Response<Status> response) {
Log.d(TAG, "postSuccessful: post ok!");
// toot sent, remove notification
nM.cancel(notificationId);
}
private void postError(Throwable error) {
Log.d(TAG, "postError: post error! --> " + error.toString());
// cancel "sending" notification id
nM.cancel(notificationId);
// create a new "error" informative notification
NotificationCompat.Builder mBuilder = buildNotification(
"Failed to send toot",
"We had some problems sending your toot, check your internet connection, or maybe the Mastodon instance you're using could be down.",
false
);
nM.notify(notificationId + 1, mBuilder.build());
}
/**
* Builds a {@link NotificationCompat.Builder} with some predefined properties
*
* @param title notification title
* @param text notification body, can be null
* @param hasUndefinedProgress declare if the notification have to contain an undefined progressbar
* @return a {@link NotificationCompat.Builder} with the properties passed as parameter.
*/
private NotificationCompat.Builder buildNotification(String title, String text, Boolean hasUndefinedProgress) {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
mBuilder.setContentTitle(title);
NotificationCompat.BigTextStyle style = new NotificationCompat.BigTextStyle();
if (text != null) {
style.bigText(text);
}
mBuilder.setStyle(style);
mBuilder.setSmallIcon(R.drawable.ic_reply_white_24dp);
if (hasUndefinedProgress) {
mBuilder.setProgress(0, 0, true);
}
return mBuilder;
}
}
| gsora/TootApp | app/src/main/java/xyz/gsora/toot/PostStatus.java | Java | mit | 5,531 |
// Dependencies
const {types} = require('focus').component;
// Components
const ContextualActions = require('../action-contextual').component;
const CheckBox = require('../../common/input/checkbox').component;
// Mixins
const translationMixin = require('../../common/i18n').mixin;
const referenceMixin = require('../../common/mixin/reference-property');
const definitionMixin = require('../../common/mixin/definition');
const builtInComponentsMixin = require('../mixin/built-in-components');
const lineMixin = {
/**
* React component name.
*/
displayName: 'ListLine',
/**
* Mixin dependancies.
*/
mixins: [translationMixin, definitionMixin, referenceMixin, builtInComponentsMixin],
/**
* Get default props
* @return {object} default props
*/
getDefaultProps(){
return {
isSelection: true,
operationList: []
};
},
/**
* line property validation.
* @type {Object}
*/
propTypes: {
data: types('object'),
isSelected: types('bool'),
isSelection: types('bool'),
onLineClick: types('func'),
onSelection: types('func'),
operationList: types('array')
},
/**
* State initialization.
* @return {object} initial state
*/
getInitialState() {
return {
isSelected: this.props.isSelected || false
};
},
/**
* Component will receive props
* @param {object} nextProps new component's props
*/
componentWillReceiveProps({isSelected}) {
if (isSelected !== undefined) {
this.setState({isSelected});
}
},
/**
* Get the line value.
* @return {object} the line value
*/
getValue() {
const {data: item, isSelected} = this.props;
return {item, isSelected};
},
/**
* Selection Click handler.
*/
_handleSelectionClick() {
const isSelected = !this.state.isSelected;
const {data, onSelection} = this.props;
this.setState({isSelected});
if(onSelection){
onSelection(data, isSelected);
}
},
/**
* Line Click handler.
*/
_handleLineClick() {
const {data, onLineClick} = this.props;
if(onLineClick){
onLineClick(data);
}
},
/**
* Render the left box for selection
* @return {XML} the rendered selection box
*/
_renderSelectionBox() {
const {isSelection} = this.props;
const {isSelected} = this.state;
if (isSelection) {
const selectionClass = isSelected ? 'selected' : 'no-selection';
//const image = this.state.isSelected? undefined : <img src={this.state.lineItem[this.props.iconfield]}/>
return (
<div className={`sl-selection ${selectionClass}`}>
<CheckBox onChange={this._handleSelectionClick} value={isSelected}/>
</div>
);
}
return null;
},
/**
* render content for a line.
* @return {XML} the rendered line content
*/
_renderLineContent() {
const {data} = this.props;
const {title, body} = data;
if (this.renderLineContent) {
return this.renderLineContent(data);
} else {
return (
<div>
<div>{title}</div>
<div>{body}</div>
</div>
);
}
},
/**
* Render actions which can be applied on the line
* @return {XML} the rendered actions
*/
_renderActions() {
const props = {operationParam: this.props.data, ...this.props};
if (0 < props.operationList.length) {
return (
<div className='sl-actions'>
<ContextualActions {...props}/>
</div>
);
}
},
/**
* Render line in list.
* @return {XML} the rendered line
*/
render() {
if(this.renderLine){
return this.renderLine();
} else {
return (
<li data-focus='sl-line'>
{this._renderSelectionBox()}
<div className='sl-content' onClick={this._handleLineClick}>
{this._renderLineContent()}
</div>
{this._renderActions()}
</li>
);
}
}
};
module.exports = {mixin: lineMixin};
| JRLK/focus-components | src/list/selection/line.js | JavaScript | mit | 4,528 |
package net.loomchild.maligna.filter.aligner.align;
import static net.loomchild.maligna.util.TestUtil.assertAlignmentEquals;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import net.loomchild.maligna.coretypes.Alignment;
import org.junit.Test;
/**
* Represents {@link AlignAlgorithmMock} unit test.
* @author loomchild
*/
public class AlignAlgorithmMockTest {
/**
* Checks if aligning empty lists returns empty list.
*/
@Test
public void alignEmpty() {
AlignAlgorithm aligner = new AlignAlgorithmMock(2);
List<String> segmentList = Collections.emptyList();
List<Alignment> alignmentList = aligner.align(segmentList, segmentList);
assertEquals(0, alignmentList.size());
}
/**
* Checks whether mock aligner works as described.
*/
@Test
public void align() {
AlignAlgorithm aligner = new AlignAlgorithmMock(2);
String[][] sourceArray = new String[][]{
new String[]{"a", "b"}, new String[]{"c","d"},
new String[]{"e", "f"}
};
String[][] targetArray = new String[][]{
new String[]{"1", "2"}, new String[]{"3"}, new String[]{}
};
assert sourceArray.length == targetArray.length;
int alignmentCount = sourceArray.length;
List<String> sourceList = combine(sourceArray);
List<String> targetList = combine(targetArray);
List<Alignment> alignmentList = aligner.align(sourceList, targetList);
assertEquals(alignmentCount, alignmentList.size());
for (int i = 0; i < alignmentCount; ++i) {
assertAlignmentEquals(sourceArray[i], targetArray[i],
alignmentList.get(i));
}
}
/**
* Creates a list of strings containing all strings from input
* two dimensional array.
* @param array array
* @return list
*/
private List<String> combine(String[][] array) {
List<String> list = new ArrayList<String>();
for (String[] group : array) {
for (String element : group) {
list.add(element);
}
}
return list;
}
}
| loomchild/maligna | maligna/src/test/java/net/loomchild/maligna/filter/aligner/align/AlignAlgorithmMockTest.java | Java | mit | 1,986 |
#include <xpcc/architecture.hpp>
#include <xpcc/communication.hpp>
#include <xpcc/communication/backend/tipc/tipc.hpp>
#include <xpcc/debug/logger.hpp>
// set new log level
#undef XPCC_LOG_LEVEL
#define XPCC_LOG_LEVEL xpcc::log::DEBUG
#include "component_receiver/receiver.hpp"
#include "component_sender/sender.hpp"
#include "communication/postman.hpp"
#include "communication/identifier.hpp"
xpcc::TipcConnector connector;
// create an instance of the generated postman
Postman postman;
xpcc::Dispatcher dispatcher(&connector, &postman);
namespace component
{
Sender sender(robot::component::SENDER, &dispatcher);
Receiver receiver(robot::component::RECEIVER, &dispatcher);
}
int
main(void)
{
connector.addReceiverId(robot::component::SENDER);
connector.addReceiverId(robot::component::RECEIVER);
XPCC_LOG_INFO << "Welcome to the communication test!" << xpcc::endl;
while (1)
{
// deliver received messages
dispatcher.update();
component::receiver.update();
component::sender.update();
xpcc::delay_us(100);
}
}
| jrahlf/3D-Non-Contact-Laser-Profilometer | xpcc/examples/linux/communication/basic/main.cpp | C++ | mit | 1,053 |
class AddUserIdToFriends < ActiveRecord::Migration
def change
add_column :friends, :user_id, :integer
end
end
| suntorytime/project_mate2 | db/migrate/20160422230113_add_user_id_to_friends.rb | Ruby | mit | 118 |
'use strict';
var assert = require('assert');
var extraStep = require('../../../lib/tasks/extra-step');
var MockUI = require('../../helpers/mock-ui');
describe('Extra Step', function() {
var ui;
var dummySteps = [
{ command: 'echo "command number 1"' },
{ command: 'echo "command number 2"' },
{ command: 'echo "command number 3"' }
];
var dummyCommands = [
'echo "command number 1"',
'echo "command number 2"',
'echo "command number 3"'
];
var failingStep = [ { command: 'exit 1', fail: true } ];
var nonFailingStep = [ { command: 'exit 1', fail: false } ];
var singleFailingStep = [ nonFailingStep[0], failingStep[0], nonFailingStep[0] ];
var dummyOptions = {
foo: 'bar',
truthy: true,
falsy: false,
someOption: 'i am a string',
num: 24
};
var dummyStepsWithOptions = [
{
command: 'echo "command number 4"',
includeOptions: ['foo', 'falsy', 'num']
},
{
command: 'echo "command number 5"',
includeOptions: ['truthy', 'someOption', 'nonExistent']
}
];
var dummyCommandsWithOptions = [
"echo \"command number 4\" --foo bar --num 24",
"echo \"command number 5\" --truthy --some-option 'i am a string'",
];
beforeEach(function() {
ui = new MockUI;
});
it('Runs an array of commands passed to it', function() {
return extraStep(dummySteps, dummyOptions, ui).then(function(result) {
assert.deepEqual(result, dummyCommands, 'Correct commands were run.');
}, function(error) {
assert.ok(false, 'An error occurred');
});
});
it('The proper commands are built and run', function() {
return extraStep(dummyStepsWithOptions, dummyOptions, ui).then(function(result) {
assert.deepEqual(result, dummyCommandsWithOptions, 'Correct commands were built and run.');
}, function(error) {
assert.ok(false, 'An error occurred');
});
});
it('Fail-safe command, with non 0 exit code, returns rejected promise', function() {
return extraStep(failingStep, null, ui).then(function(result) {
assert.ok(false, 'steps should have failed.');
}, function(err) {
assert.ok(true, 'steps failed as expected.');
});
});
it('Fail-friendly command, with non 0 exit code, returns resolved promise', function() {
return extraStep(nonFailingStep, null, ui).then(function(result) {
assert.ok(true, 'steps kept running after failed command, as expected.');
}, function(err) {
assert.ok(false, 'Steps did not continue running as expected');
});
});
});
| AReallyGoodName/ember-cli-s3-sync-index-last-no-cache | tests/unit/tasks/extra-step-test.js | JavaScript | mit | 2,577 |
# -*- coding: utf-8 -*-
#
# py-uwerr documentation build configuration file, created by
# sphinx-quickstart on Sat Nov 24 19:07:07 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('..'))
sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.mathjax', 'sphinx.ext.viewcode']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'py-uwerr'
copyright = u'2012, Dirk Hesse'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.1'
# The full version, including alpha/beta/rc tags.
release = '0.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'py-uwerrdoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'py-uwerr.tex', u'py-uwerr Documentation',
u'Dirk Hesse', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'py-uwerr', u'py-uwerr Documentation',
[u'Dirk Hesse'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'py-uwerr', u'py-uwerr Documentation',
u'Dirk Hesse', 'py-uwerr', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
| dhesse/py-uwerr | doc/conf.py | Python | mit | 7,830 |
/*Owner & Copyrights: Vance King Saxbe. A.*//*Copyright (c) <2014> Author Vance King Saxbe. A, and contributors Power Dominion Enterprise, Precieux Consulting and other contributors. Modelled, Architected and designed by Vance King Saxbe. A. with the geeks from GoldSax Consulting and GoldSax Technologies email @vsaxbe@yahoo.com. Development teams from Power Dominion Enterprise, Precieux Consulting. Project sponsored by GoldSax Foundation, GoldSax Group and executed by GoldSax Manager.*/
$quote = file_get_contents('http://finance.google.co.uk/finance/info?client=ig&q=NYSE:WEC');
$avgp = "36.25";
$high = "36.72";
$low = "36.24";
$json = str_replace("\n", "", $quote);
$data = substr($json, 4, strlen($json) -5);
$json_output = json_decode($data, true);
echo "&L=".$json_output['l']."&N=WEC&";
$temp = file_get_contents("WECTEMP.txt", "r");
if ($json_output['l'] != $temp ) {
if ( $json_output['l'] > $temp ) {
if ( ($json_output['l'] > ($avgp + $high)/2) && ($json_output['l'] < $high)) { echo "&sign=au" ; }
if ( ($json_output['l'] < ($avgp + $low)/2) && ($json_output['l'] > $low)) { echo "&sign=ad" ; }
if ( $json_output['l'] < ($low - (($avgp - $low)/2)) ) { echo "&sign=as" ; }
if ( $json_output['l'] > ($high + (($high - $avgp)/2)) ) { echo "&sign=al" ; }
if ( ($json_output['l'] < ($high + (($high - $avgp)/2))) && ($json_output['l'] > $high)) { echo "&sign=auu" ; }
if ( ($json_output['l'] > ($low - (($avgp - $low)/2))) && ($json_output['l'] < $low)) { echo "&sign=add" ; }
//else { echo "&sign=a" ; }
}
if ( $json_output['l'] < $temp ) {
if ( ($json_output['l'] > ($avgp + $high)/2) && ($json_output['l'] < $high)) { echo "&sign=bu" ; }
if ( ($json_output['l'] < ($avgp + $low)/2) && ($json_output['l'] > $low)) { echo "&sign=bd" ; }
if ( $json_output['l'] < ($low - (($avgp - $low)/2)) ) { echo "&sign=bs" ; }
if ( $json_output['l'] > ($high + (($high - $avgp)/2)) ) { echo "&sign=bl" ; }
if ( ($json_output['l'] < ($high + (($high - $avgp)/2))) && ($json_output['l'] > $high)) { echo "&sign=buu" ; }
if ( ($json_output['l'] > ($low - (($avgp - $low)/2))) && ($json_output['l'] < $low)) { echo "&sign=bdd" ; }
// else { echo "&sign=b" ; }
}
$my_time = date('h:i:s',time());
$seconds2add = 19800;
$new_time= strtotime($my_time);
$new_time+=$seconds2add;
$time = date('h:i:s',$new_time);
$filename= 'WEC.txt';
$file = fopen($filename, "a+" );
fwrite( $file, $json_output['l'].":".$time."\r\n" );
fclose( $file );
if (($json_output['l'] > $high ) && ($temp<= $high ))
{$my_time = date('h:i:s',time());
$seconds2add = 19800;
$new_time= strtotime($my_time);
$new_time+=$seconds2add;
$time = date('h:i:s',$new_time);
$risk = ($json_output['l'] - $low) * (200000/$json_output['l']);
$filedash = fopen("alert.txt", "a+");
$wrote = fputs($filedash, "WEC:". "breaking:PHIGH:"."Buy Cost:".$risk."\r\n");
fclose( $filedash );
}
if (($json_output['l'] < $high ) && ($temp>= $high ))
{$my_time = date('h:i:s',time());
$seconds2add = 19800;
$new_time= strtotime($my_time);
$new_time+=$seconds2add;
$time = date('h:i:s',$new_time);
$filedash = fopen("alert.txt", "a+");
$wrote = fputs($filedash, "WEC:". "retracing:PHIGH:"."\r\n");
fclose( $filedash );
}
if (($json_output['l'] < $low ) && ($temp>= $low ))
{$my_time = date('h:i:s',time());
$seconds2add = 19800;
$new_time= strtotime($my_time);
$new_time+=$seconds2add;
$risk = ($high - $json_output['l']) * (200000/$json_output['l']);
$time = date('h:i:s',$new_time);
$filedash = fopen("alert.txt", "a+");
$wrote = fputs($filedash, "WEC:". "breaking:PLOW:"."short Cost:".$risk."\r\n");
fclose( $filedash );
}
if (($json_output['l'] > $low ) && ($temp<= $low ))
{$my_time = date('h:i:s',time());
$seconds2add = 19800;
$new_time= strtotime($my_time);
$new_time+=$seconds2add;
$time = date('h:i:s',$new_time);
$filedash = fopen("alert.txt", "a+");
$wrote = fputs($filedash, "WEC:". "retracing:PLOW:"."\r\n");
fclose( $filedash );
}
if (($json_output['l'] > $avgp ) && ($temp<= $avgp ))
{$my_time = date('h:i:s',time());
$seconds2add = 19800;
$new_time= strtotime($my_time);
$new_time+=$seconds2add;
$risk = ($json_output['l'] - $low) * (200000/$json_output['l']);
$time = date('h:i:s',$new_time);
$filedash = fopen("alert.txt", "a+");
$wrote = fputs($filedash, "WEC:". "sliding up:PAVG:"."Buy Cost:".$risk."\r\n");
fclose( $filedash );
}
if (($json_output['l'] < $avgp ) && ($temp>= $avgp ))
{$my_time = date('h:i:s',time());
$seconds2add = 19800;
$new_time= strtotime($my_time);
$new_time+=$seconds2add;
$risk = ($high - $json_output['l']) * (200000/$json_output['l']);
$time = date('h:i:s',$new_time);
$filedash = fopen("alert.txt", "a+");
$wrote = fputs($filedash, "WEC:". "Sliding down:PAVG:"."Short Cost:".$risk."\r\n");
fclose( $filedash );
}
}
$filedash = fopen("WECTEMP.txt", "w");
$wrote = fputs($filedash, $json_output['l']);
fclose( $filedash );
//echo "&chg=".$json_output['cp']."&";
?>
/*email to provide support at vancekingsaxbe@powerdominionenterprise.com, businessaffairs@powerdominionenterprise.com, For donations please write to fundraising@powerdominionenterprise.com*/ | VanceKingSaxbeA/NYSE-Engine | App/WEC.php | PHP | mit | 5,298 |
// ==========================================================================
// SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2012, Knut Reinert, FU Berlin
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of Knut Reinert or the FU Berlin nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// ==========================================================================
// Author: Manuel Holtgrewe <manuel.holtgrewe@fu-berlin.de>
// ==========================================================================
#include <cstdio>
#include <seqan/basic/basic_debug.h>
#include <seqan/basic/basic_metaprogramming.h>
#include "test_basic_metaprogramming_logic.h"
#include "test_basic_metaprogramming_control.h"
#include "test_basic_metaprogramming_math.h"
#include "test_basic_metaprogramming_type.h"
#include "test_basic_metaprogramming_enable_if.h"
SEQAN_BEGIN_TESTSUITE(test_basic_metaprogramming)
{
// -----------------------------------------------------------------------
// Metaprogramming Logic
// -----------------------------------------------------------------------
SEQAN_CALL_TEST(test_basic_metaprogramming_logic_bool_type);
SEQAN_CALL_TEST(test_basic_metaprogramming_logic_eval);
SEQAN_CALL_TEST(test_basic_metaprogramming_logic_or);
SEQAN_CALL_TEST(test_basic_metaprogramming_logic_or_c);
SEQAN_CALL_TEST(test_basic_metaprogramming_logic_and);
SEQAN_CALL_TEST(test_basic_metaprogramming_logic_and_c);
SEQAN_CALL_TEST(test_basic_metaprogramming_logic_if);
SEQAN_CALL_TEST(test_basic_metaprogramming_logic_if_c);
// -----------------------------------------------------------------------
// Metaprogramming Control Structures
// -----------------------------------------------------------------------
SEQAN_CALL_TEST(test_basic_metaprogramming_control_loop_reverse);
SEQAN_CALL_TEST(test_basic_metaprogramming_control_loop);
SEQAN_CALL_TEST(test_basic_metaprogramming_control_switch);
SEQAN_CALL_TEST(test_basic_metaprogramming_control_if);
// -----------------------------------------------------------------------
// Metaprogramming Math
// -----------------------------------------------------------------------
SEQAN_CALL_TEST(test_basic_metaprogramming_math_log2);
SEQAN_CALL_TEST(test_basic_metaprogramming_math_log2_floor);
SEQAN_CALL_TEST(test_basic_metaprogramming_math_log2_power);
// -----------------------------------------------------------------------
// Metaprogramming Type Queries / Modification
// -----------------------------------------------------------------------
SEQAN_CALL_TEST(test_basic_metaprogramming_type_same_type);
SEQAN_CALL_TEST(test_basic_metaprogramming_type_make_signed);
SEQAN_CALL_TEST(test_basic_metaprogramming_type_make_unsigned);
SEQAN_CALL_TEST(test_basic_metaprogramming_type_remove_reference);
SEQAN_CALL_TEST(test_basic_metaprogramming_type_remove_const);
SEQAN_CALL_TEST(test_basic_metaprogramming_type_is_const);
SEQAN_CALL_TEST(test_basic_metaprogramming_type_class_identifier);
// -----------------------------------------------------------------------
// Metaprogramming Conditional Enabling
// -----------------------------------------------------------------------
SEQAN_CALL_TEST(test_basic_metaprogramming_enable_if_disable_if);
SEQAN_CALL_TEST(test_basic_metaprogramming_enable_if2_disable_if2);
}
SEQAN_END_TESTSUITE
// ==========================================================================
// SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2012, Knut Reinert, FU Berlin
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of Knut Reinert or the FU Berlin nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// ==========================================================================
// Author: Manuel Holtgrewe <manuel.holtgrewe@fu-berlin.de>
// ==========================================================================
#include <cstdio>
#include <seqan/basic/basic_debug.h>
#include <seqan/basic/basic_metaprogramming.h>
#include "test_basic_metaprogramming_logic.h"
#include "test_basic_metaprogramming_control.h"
#include "test_basic_metaprogramming_math.h"
#include "test_basic_metaprogramming_type.h"
#include "test_basic_metaprogramming_enable_if.h"
SEQAN_BEGIN_TESTSUITE(test_basic_metaprogramming)
{
// -----------------------------------------------------------------------
// Metaprogramming Logic
// -----------------------------------------------------------------------
SEQAN_CALL_TEST(test_basic_metaprogramming_logic_bool_type);
SEQAN_CALL_TEST(test_basic_metaprogramming_logic_eval);
SEQAN_CALL_TEST(test_basic_metaprogramming_logic_or);
SEQAN_CALL_TEST(test_basic_metaprogramming_logic_or_c);
SEQAN_CALL_TEST(test_basic_metaprogramming_logic_and);
SEQAN_CALL_TEST(test_basic_metaprogramming_logic_and_c);
SEQAN_CALL_TEST(test_basic_metaprogramming_logic_if);
SEQAN_CALL_TEST(test_basic_metaprogramming_logic_if_c);
// -----------------------------------------------------------------------
// Metaprogramming Control Structures
// -----------------------------------------------------------------------
SEQAN_CALL_TEST(test_basic_metaprogramming_control_loop_reverse);
SEQAN_CALL_TEST(test_basic_metaprogramming_control_loop);
SEQAN_CALL_TEST(test_basic_metaprogramming_control_switch);
SEQAN_CALL_TEST(test_basic_metaprogramming_control_if);
// -----------------------------------------------------------------------
// Metaprogramming Math
// -----------------------------------------------------------------------
SEQAN_CALL_TEST(test_basic_metaprogramming_math_log2);
SEQAN_CALL_TEST(test_basic_metaprogramming_math_log2_floor);
SEQAN_CALL_TEST(test_basic_metaprogramming_math_log2_power);
// -----------------------------------------------------------------------
// Metaprogramming Type Queries / Modification
// -----------------------------------------------------------------------
SEQAN_CALL_TEST(test_basic_metaprogramming_type_same_type);
SEQAN_CALL_TEST(test_basic_metaprogramming_type_make_signed);
SEQAN_CALL_TEST(test_basic_metaprogramming_type_make_unsigned);
SEQAN_CALL_TEST(test_basic_metaprogramming_type_remove_reference);
SEQAN_CALL_TEST(test_basic_metaprogramming_type_remove_const);
SEQAN_CALL_TEST(test_basic_metaprogramming_type_is_const);
SEQAN_CALL_TEST(test_basic_metaprogramming_type_class_identifier);
// -----------------------------------------------------------------------
// Metaprogramming Conditional Enabling
// -----------------------------------------------------------------------
SEQAN_CALL_TEST(test_basic_metaprogramming_enable_if_disable_if);
SEQAN_CALL_TEST(test_basic_metaprogramming_enable_if2_disable_if2);
}
SEQAN_END_TESTSUITE | bkahlert/seqan-research | raw/pmbs12/pmsb13-data-20120615/sources/wtg1fr816tg4hs6w/5/core/tests/basic/test_basic_metaprogramming.cpp | C++ | mit | 10,082 |
package model.neighbors;
import java.util.List;
import model.patches.Patch;
import model.gridrules.GridRules;
public abstract class Neighbors {
//will contain methods to construct neighbor list and check neighbors, etc.
//extended by different type of neighbor functions?
//or perhaps different neighbor functions will all be in this class?
public abstract List<Patch> getCardinalNeighbors(Patch[][] grid, int x,
int y, GridRules rules);
public abstract List<Patch> getDiagonalNeighbors(Patch[][] grid, int x, int y,
GridRules rules);
public abstract List<Patch> getAllNeighbors(Patch[][] grid, int x, int y,
GridRules rules);
public void topRight(Patch[][]grid, int x, int y, GridRules rules,
List<Patch> neighbors){
if(x == grid[0].length-1 || y == 0){
rules.handleEdges(grid, x+1, y-1, neighbors);
} else{
neighbors.add(grid[y-1][x+1]);
}
}
public void topLeft(Patch[][]grid, int x, int y, GridRules rules,
List<Patch> neighbors){
if(x == 0 || y == 0){
rules.handleEdges(grid, x-1, y-1, neighbors);
} else{
neighbors.add(grid[y-1][x-1]);
}
}
public void Right(Patch[][] grid, int x, int y, GridRules rules,
List<Patch> neighbors){
if(x== grid[0].length-1){
rules.handleEdges(grid, x+1, y, neighbors);
} else{
neighbors.add(grid[y][x+1]);
}
}
public void Left(Patch[][] grid, int x, int y, GridRules rules,
List<Patch> neighbors){
if(x==0){
rules.handleEdges(grid, x-1, y, neighbors);
} else{
neighbors.add(grid[y][x-1]);
}
}
public void bottomRight(Patch[][] grid, int x, int y, GridRules rules,
List<Patch> neighbors){
if(x==grid[0].length -1|| y == grid.length-1){
rules.handleEdges(grid, x+1, y+1, neighbors);
}else{
neighbors.add(grid[y+1][x+1]);
}
}
public void bottomLeft(Patch[][] grid, int x, int y, GridRules rules,
List<Patch> neighbors){
if(x==0 || y == grid.length-1){
rules.handleEdges(grid, x-1, y+1, neighbors);
}else{
neighbors.add(grid[y+1][x-1]);
}
}
public void Up(Patch[][] grid, int x, int y, GridRules rules,
List<Patch> neighbors){
if(y==0){
rules.handleEdges(grid, x, y-1, neighbors);
} else{
neighbors.add(grid[y-1][x]);
}
}
public void Down(Patch[][] grid, int x, int y, GridRules rules,
List<Patch> neighbors){
if(y==grid.length-1){
rules.handleEdges(grid, x, y+1, neighbors);
} else{
neighbors.add(grid[y+1][x]);
}
}
}
| jananzhu/cellsociety | src/model/neighbors/Neighbors.java | Java | mit | 3,084 |
// Copyright 2019 Google LLC.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Code generated file. DO NOT EDIT.
// Package datafusion provides access to the Cloud Data Fusion API.
//
// For product documentation, see: https://cloud.google.com/data-fusion/docs
//
// Creating a client
//
// Usage example:
//
// import "google.golang.org/api/datafusion/v1beta1"
// ...
// ctx := context.Background()
// datafusionService, err := datafusion.NewService(ctx)
//
// In this example, Google Application Default Credentials are used for authentication.
//
// For information on how to create and obtain Application Default Credentials, see https://developers.google.com/identity/protocols/application-default-credentials.
//
// Other authentication options
//
// To use an API key for authentication (note: some APIs do not support API keys), use option.WithAPIKey:
//
// datafusionService, err := datafusion.NewService(ctx, option.WithAPIKey("AIza..."))
//
// To use an OAuth token (e.g., a user token obtained via a three-legged OAuth flow), use option.WithTokenSource:
//
// config := &oauth2.Config{...}
// // ...
// token, err := config.Exchange(ctx, ...)
// datafusionService, err := datafusion.NewService(ctx, option.WithTokenSource(config.TokenSource(ctx, token)))
//
// See https://godoc.org/google.golang.org/api/option/ for details on options.
package datafusion // import "google.golang.org/api/datafusion/v1beta1"
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
googleapi "google.golang.org/api/googleapi"
gensupport "google.golang.org/api/internal/gensupport"
option "google.golang.org/api/option"
htransport "google.golang.org/api/transport/http"
)
// Always reference these packages, just in case the auto-generated code
// below doesn't.
var _ = bytes.NewBuffer
var _ = strconv.Itoa
var _ = fmt.Sprintf
var _ = json.NewDecoder
var _ = io.Copy
var _ = url.Parse
var _ = gensupport.MarshalJSON
var _ = googleapi.Version
var _ = errors.New
var _ = strings.Replace
var _ = context.Canceled
const apiId = "datafusion:v1beta1"
const apiName = "datafusion"
const apiVersion = "v1beta1"
const basePath = "https://datafusion.googleapis.com/"
// OAuth2 scopes used by this API.
const (
// View and manage your data across Google Cloud Platform services
CloudPlatformScope = "https://www.googleapis.com/auth/cloud-platform"
)
// NewService creates a new Service.
func NewService(ctx context.Context, opts ...option.ClientOption) (*Service, error) {
scopesOption := option.WithScopes(
"https://www.googleapis.com/auth/cloud-platform",
)
// NOTE: prepend, so we don't override user-specified scopes.
opts = append([]option.ClientOption{scopesOption}, opts...)
client, endpoint, err := htransport.NewClient(ctx, opts...)
if err != nil {
return nil, err
}
s, err := New(client)
if err != nil {
return nil, err
}
if endpoint != "" {
s.BasePath = endpoint
}
return s, nil
}
// New creates a new Service. It uses the provided http.Client for requests.
//
// Deprecated: please use NewService instead.
// To provide a custom HTTP client, use option.WithHTTPClient.
// If you are using google.golang.org/api/googleapis/transport.APIKey, use option.WithAPIKey with NewService instead.
func New(client *http.Client) (*Service, error) {
if client == nil {
return nil, errors.New("client is nil")
}
s := &Service{client: client, BasePath: basePath}
s.Projects = NewProjectsService(s)
return s, nil
}
type Service struct {
client *http.Client
BasePath string // API endpoint base URL
UserAgent string // optional additional User-Agent fragment
Projects *ProjectsService
}
func (s *Service) userAgent() string {
if s.UserAgent == "" {
return googleapi.UserAgent
}
return googleapi.UserAgent + " " + s.UserAgent
}
func NewProjectsService(s *Service) *ProjectsService {
rs := &ProjectsService{s: s}
rs.Locations = NewProjectsLocationsService(s)
return rs
}
type ProjectsService struct {
s *Service
Locations *ProjectsLocationsService
}
func NewProjectsLocationsService(s *Service) *ProjectsLocationsService {
rs := &ProjectsLocationsService{s: s}
rs.Instances = NewProjectsLocationsInstancesService(s)
rs.Operations = NewProjectsLocationsOperationsService(s)
return rs
}
type ProjectsLocationsService struct {
s *Service
Instances *ProjectsLocationsInstancesService
Operations *ProjectsLocationsOperationsService
}
func NewProjectsLocationsInstancesService(s *Service) *ProjectsLocationsInstancesService {
rs := &ProjectsLocationsInstancesService{s: s}
return rs
}
type ProjectsLocationsInstancesService struct {
s *Service
}
func NewProjectsLocationsOperationsService(s *Service) *ProjectsLocationsOperationsService {
rs := &ProjectsLocationsOperationsService{s: s}
return rs
}
type ProjectsLocationsOperationsService struct {
s *Service
}
// AuditConfig: Specifies the audit configuration for a service.
// The configuration determines which permission types are logged, and
// what
// identities, if any, are exempted from logging.
// An AuditConfig must have one or more AuditLogConfigs.
//
// If there are AuditConfigs for both `allServices` and a specific
// service,
// the union of the two AuditConfigs is used for that service: the
// log_types
// specified in each AuditConfig are enabled, and the exempted_members
// in each
// AuditLogConfig are exempted.
//
// Example Policy with multiple AuditConfigs:
//
// {
// "audit_configs": [
// {
// "service": "allServices"
// "audit_log_configs": [
// {
// "log_type": "DATA_READ",
// "exempted_members": [
// "user:foo@gmail.com"
// ]
// },
// {
// "log_type": "DATA_WRITE",
// },
// {
// "log_type": "ADMIN_READ",
// }
// ]
// },
// {
// "service": "fooservice.googleapis.com"
// "audit_log_configs": [
// {
// "log_type": "DATA_READ",
// },
// {
// "log_type": "DATA_WRITE",
// "exempted_members": [
// "user:bar@gmail.com"
// ]
// }
// ]
// }
// ]
// }
//
// For fooservice, this policy enables DATA_READ, DATA_WRITE and
// ADMIN_READ
// logging. It also exempts foo@gmail.com from DATA_READ logging,
// and
// bar@gmail.com from DATA_WRITE logging.
type AuditConfig struct {
// AuditLogConfigs: The configuration for logging of each type of
// permission.
AuditLogConfigs []*AuditLogConfig `json:"auditLogConfigs,omitempty"`
ExemptedMembers []string `json:"exemptedMembers,omitempty"`
// Service: Specifies a service that will be enabled for audit
// logging.
// For example, `storage.googleapis.com`,
// `cloudsql.googleapis.com`.
// `allServices` is a special value that covers all services.
Service string `json:"service,omitempty"`
// ForceSendFields is a list of field names (e.g. "AuditLogConfigs") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "AuditLogConfigs") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *AuditConfig) MarshalJSON() ([]byte, error) {
type NoMethod AuditConfig
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// AuditLogConfig: Provides the configuration for logging a type of
// permissions.
// Example:
//
// {
// "audit_log_configs": [
// {
// "log_type": "DATA_READ",
// "exempted_members": [
// "user:foo@gmail.com"
// ]
// },
// {
// "log_type": "DATA_WRITE",
// }
// ]
// }
//
// This enables 'DATA_READ' and 'DATA_WRITE' logging, while
// exempting
// foo@gmail.com from DATA_READ logging.
type AuditLogConfig struct {
// ExemptedMembers: Specifies the identities that do not cause logging
// for this type of
// permission.
// Follows the same format of Binding.members.
ExemptedMembers []string `json:"exemptedMembers,omitempty"`
// LogType: The log type that this config enables.
//
// Possible values:
// "LOG_TYPE_UNSPECIFIED" - Default case. Should never be this.
// "ADMIN_READ" - Admin reads. Example: CloudIAM getIamPolicy
// "DATA_WRITE" - Data writes. Example: CloudSQL Users create
// "DATA_READ" - Data reads. Example: CloudSQL Users list
LogType string `json:"logType,omitempty"`
// ForceSendFields is a list of field names (e.g. "ExemptedMembers") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ExemptedMembers") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *AuditLogConfig) MarshalJSON() ([]byte, error) {
type NoMethod AuditLogConfig
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// AuthorizationLoggingOptions: Authorization-related information used
// by Cloud Audit Logging.
type AuthorizationLoggingOptions struct {
// PermissionType: The type of the permission that was checked.
//
// Possible values:
// "PERMISSION_TYPE_UNSPECIFIED" - Default. Should not be used.
// "ADMIN_READ" - A read of admin (meta) data.
// "ADMIN_WRITE" - A write of admin (meta) data.
// "DATA_READ" - A read of standard data.
// "DATA_WRITE" - A write of standard data.
PermissionType string `json:"permissionType,omitempty"`
// ForceSendFields is a list of field names (e.g. "PermissionType") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "PermissionType") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *AuthorizationLoggingOptions) MarshalJSON() ([]byte, error) {
type NoMethod AuthorizationLoggingOptions
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Binding: Associates `members` with a `role`.
type Binding struct {
// Condition: The condition that is associated with this binding.
// NOTE: An unsatisfied condition will not allow user access via
// current
// binding. Different bindings, including their conditions, are
// examined
// independently.
Condition *Expr `json:"condition,omitempty"`
// Members: Specifies the identities requesting access for a Cloud
// Platform resource.
// `members` can have the following values:
//
// * `allUsers`: A special identifier that represents anyone who is
// on the internet; with or without a Google account.
//
// * `allAuthenticatedUsers`: A special identifier that represents
// anyone
// who is authenticated with a Google account or a service
// account.
//
// * `user:{emailid}`: An email address that represents a specific
// Google
// account. For example, `alice@gmail.com` .
//
//
// * `serviceAccount:{emailid}`: An email address that represents a
// service
// account. For example,
// `my-other-app@appspot.gserviceaccount.com`.
//
// * `group:{emailid}`: An email address that represents a Google
// group.
// For example, `admins@example.com`.
//
//
// * `domain:{domain}`: The G Suite domain (primary) that represents all
// the
// users of that domain. For example, `google.com` or
// `example.com`.
//
//
Members []string `json:"members,omitempty"`
// Role: Role that is assigned to `members`.
// For example, `roles/viewer`, `roles/editor`, or `roles/owner`.
Role string `json:"role,omitempty"`
// ForceSendFields is a list of field names (e.g. "Condition") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Condition") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Binding) MarshalJSON() ([]byte, error) {
type NoMethod Binding
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// CancelOperationRequest: The request message for
// Operations.CancelOperation.
type CancelOperationRequest struct {
}
// CloudAuditOptions: Write a Cloud Audit log
type CloudAuditOptions struct {
// AuthorizationLoggingOptions: Information used by the Cloud Audit
// Logging pipeline.
AuthorizationLoggingOptions *AuthorizationLoggingOptions `json:"authorizationLoggingOptions,omitempty"`
// LogName: The log_name to populate in the Cloud Audit Record.
//
// Possible values:
// "UNSPECIFIED_LOG_NAME" - Default. Should not be used.
// "ADMIN_ACTIVITY" - Corresponds to
// "cloudaudit.googleapis.com/activity"
// "DATA_ACCESS" - Corresponds to
// "cloudaudit.googleapis.com/data_access"
LogName string `json:"logName,omitempty"`
// ForceSendFields is a list of field names (e.g.
// "AuthorizationLoggingOptions") to unconditionally include in API
// requests. By default, fields with empty values are omitted from API
// requests. However, any non-pointer, non-interface field appearing in
// ForceSendFields will be sent to the server regardless of whether the
// field is empty or not. This may be used to include empty fields in
// Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g.
// "AuthorizationLoggingOptions") to include in API requests with the
// JSON null value. By default, fields with empty values are omitted
// from API requests. However, any field with an empty value appearing
// in NullFields will be sent to the server as null. It is an error if a
// field in this list has a non-empty value. This may be used to include
// null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *CloudAuditOptions) MarshalJSON() ([]byte, error) {
type NoMethod CloudAuditOptions
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Condition: A condition to be met.
type Condition struct {
// Iam: Trusted attributes supplied by the IAM system.
//
// Possible values:
// "NO_ATTR" - Default non-attribute.
// "AUTHORITY" - Either principal or (if present) authority selector.
// "ATTRIBUTION" - The principal (even if an authority selector is
// present), which
// must only be used for attribution, not authorization.
// "SECURITY_REALM" - Any of the security realms in the IAMContext
// (go/security-realms).
// When used with IN, the condition indicates "any of the request's
// realms
// match one of the given values; with NOT_IN, "none of the realms
// match
// any of the given values". Note that a value can be:
// - 'self' (i.e., allow connections from clients that are in the same
// security realm)
// - a realm (e.g., 'campus-abc')
// - a realm group (e.g., 'realms-for-borg-cell-xx', see:
// go/realm-groups)
// A match is determined by a realm group
// membership check performed by a RealmAclRep object
// (go/realm-acl-howto).
// It is not permitted to grant access based on the *absence* of a
// realm, so
// realm conditions can only be used in a "positive" context (e.g.,
// ALLOW/IN
// or DENY/NOT_IN).
// "APPROVER" - An approver (distinct from the requester) that has
// authorized this
// request.
// When used with IN, the condition indicates that one of the
// approvers
// associated with the request matches the specified principal, or is
// a
// member of the specified group. Approvers can only grant
// additional
// access, and are thus only used in a strictly positive context
// (e.g. ALLOW/IN or DENY/NOT_IN).
// "JUSTIFICATION_TYPE" - What types of justifications have been
// supplied with this request.
// String values should match enum names from
// tech.iam.JustificationType,
// e.g. "MANUAL_STRING". It is not permitted to grant access based
// on
// the *absence* of a justification, so justification conditions can
// only
// be used in a "positive" context (e.g., ALLOW/IN or
// DENY/NOT_IN).
//
// Multiple justifications, e.g., a Buganizer ID and a
// manually-entered
// reason, are normal and supported.
// "CREDENTIALS_TYPE" - What type of credentials have been supplied
// with this request.
// String values should match enum names
// from
// security_loas_l2.CredentialsType - currently, only
// CREDS_TYPE_EMERGENCY
// is supported.
// It is not permitted to grant access based on the *absence* of
// a
// credentials type, so the conditions can only be used in a
// "positive"
// context (e.g., ALLOW/IN or DENY/NOT_IN).
Iam string `json:"iam,omitempty"`
// Op: An operator to apply the subject with.
//
// Possible values:
// "NO_OP" - Default no-op.
// "EQUALS" - DEPRECATED. Use IN instead.
// "NOT_EQUALS" - DEPRECATED. Use NOT_IN instead.
// "IN" - The condition is true if the subject (or any element of it
// if it is
// a set) matches any of the supplied values.
// "NOT_IN" - The condition is true if the subject (or every element
// of it if it is
// a set) matches none of the supplied values.
// "DISCHARGED" - Subject is discharged
Op string `json:"op,omitempty"`
// Svc: Trusted attributes discharged by the service.
Svc string `json:"svc,omitempty"`
// Sys: Trusted attributes supplied by any service that owns resources
// and uses
// the IAM system for access control.
//
// Possible values:
// "NO_ATTR" - Default non-attribute type
// "REGION" - Region of the resource
// "SERVICE" - Service name
// "NAME" - Resource name
// "IP" - IP address of the caller
Sys string `json:"sys,omitempty"`
// Values: The objects of the condition.
Values []string `json:"values,omitempty"`
// ForceSendFields is a list of field names (e.g. "Iam") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Iam") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Condition) MarshalJSON() ([]byte, error) {
type NoMethod Condition
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// CounterOptions: Increment a streamz counter with the specified metric
// and field names.
//
// Metric names should start with a '/', generally be
// lowercase-only,
// and end in "_count". Field names should not contain an initial
// slash.
// The actual exported metric names will have "/iam/policy"
// prepended.
//
// Field names correspond to IAM request parameters and field values
// are
// their respective values.
//
// Supported field names:
// - "authority", which is "[token]" if IAMContext.token is present,
// otherwise the value of IAMContext.authority_selector if present,
// and
// otherwise a representation of IAMContext.principal; or
// - "iam_principal", a representation of IAMContext.principal even
// if a
// token or authority selector is present; or
// - "" (empty string), resulting in a counter with no
// fields.
//
// Examples:
// counter { metric: "/debug_access_count" field: "iam_principal" }
// ==> increment counter /iam/policy/backend_debug_access_count
// {iam_principal=[value of
// IAMContext.principal]}
//
// At this time we do not support multiple field names (though this may
// be
// supported in the future).
type CounterOptions struct {
// Field: The field value to attribute.
Field string `json:"field,omitempty"`
// Metric: The metric to update.
Metric string `json:"metric,omitempty"`
// ForceSendFields is a list of field names (e.g. "Field") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Field") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *CounterOptions) MarshalJSON() ([]byte, error) {
type NoMethod CounterOptions
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// DataAccessOptions: Write a Data Access (Gin) log
type DataAccessOptions struct {
// LogMode: Whether Gin logging should happen in a fail-closed manner at
// the caller.
// This is relevant only in the LocalIAM implementation, for now.
//
// Possible values:
// "LOG_MODE_UNSPECIFIED" - Client is not required to write a partial
// Gin log immediately after
// the authorization check. If client chooses to write one and it
// fails,
// client may either fail open (allow the operation to continue) or
// fail closed (handle as a DENY outcome).
// "LOG_FAIL_CLOSED" - The application's operation in the context of
// which this authorization
// check is being made may only be performed if it is successfully
// logged
// to Gin. For instance, the authorization library may satisfy
// this
// obligation by emitting a partial log entry at authorization check
// time
// and only returning ALLOW to the application if it succeeds.
//
// If a matching Rule has this directive, but the client has not
// indicated
// that it will honor such requirements, then the IAM check will result
// in
// authorization failure by setting CheckPolicyResponse.success=false.
LogMode string `json:"logMode,omitempty"`
// ForceSendFields is a list of field names (e.g. "LogMode") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "LogMode") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *DataAccessOptions) MarshalJSON() ([]byte, error) {
type NoMethod DataAccessOptions
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Empty: A generic empty message that you can re-use to avoid defining
// duplicated
// empty messages in your APIs. A typical example is to use it as the
// request
// or the response type of an API method. For instance:
//
// service Foo {
// rpc Bar(google.protobuf.Empty) returns
// (google.protobuf.Empty);
// }
//
// The JSON representation for `Empty` is empty JSON object `{}`.
type Empty struct {
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
}
// Expr: Represents an expression text. Example:
//
// title: "User account presence"
// description: "Determines whether the request has a user account"
// expression: "size(request.user) > 0"
type Expr struct {
// Description: An optional description of the expression. This is a
// longer text which
// describes the expression, e.g. when hovered over it in a UI.
Description string `json:"description,omitempty"`
// Expression: Textual representation of an expression in
// Common Expression Language syntax.
//
// The application context of the containing message determines
// which
// well-known feature set of CEL is supported.
Expression string `json:"expression,omitempty"`
// Location: An optional string indicating the location of the
// expression for error
// reporting, e.g. a file name and a position in the file.
Location string `json:"location,omitempty"`
// Title: An optional title for the expression, i.e. a short string
// describing
// its purpose. This can be used e.g. in UIs which allow to enter
// the
// expression.
Title string `json:"title,omitempty"`
// ForceSendFields is a list of field names (e.g. "Description") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Description") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Expr) MarshalJSON() ([]byte, error) {
type NoMethod Expr
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Instance: Represents a Data Fusion instance.
type Instance struct {
// CreateTime: Output only. The time the instance was created.
CreateTime string `json:"createTime,omitempty"`
// Description: An optional description of this instance.
Description string `json:"description,omitempty"`
// DisplayName: Display name for an instance.
DisplayName string `json:"displayName,omitempty"`
// EnableStackdriverLogging: Option to enable Stackdriver Logging.
EnableStackdriverLogging bool `json:"enableStackdriverLogging,omitempty"`
// EnableStackdriverMonitoring: Option to enable Stackdriver Monitoring.
EnableStackdriverMonitoring bool `json:"enableStackdriverMonitoring,omitempty"`
// Labels: The resource labels for instance to use to annotate any
// related underlying
// resources such as GCE VMs. The character '=' is not allowed to be
// used
// within the labels.
Labels map[string]string `json:"labels,omitempty"`
// Name: Output only. The name of this instance is in the form
// of
// projects/{project}/locations/{location}/instances/{instance}.
Name string `json:"name,omitempty"`
// NetworkConfig: Network configuration options. These are required when
// a private Data
// Fusion instance is to be created.
NetworkConfig *NetworkConfig `json:"networkConfig,omitempty"`
// Options: Map of additional options used to configure the behavior
// of
// Data Fusion instance.
Options map[string]string `json:"options,omitempty"`
// PrivateInstance: Specifies whether the Data Fusion instance should be
// private. If set to
// true, all Data Fusion nodes will have private IP addresses and will
// not be
// able to access the public internet.
PrivateInstance bool `json:"privateInstance,omitempty"`
// ServiceAccount: Output only. Service account which will be used to
// access resources in
// the customer project."
ServiceAccount string `json:"serviceAccount,omitempty"`
// ServiceEndpoint: Output only. Endpoint on which the Data Fusion UI
// and REST APIs are
// accessible.
ServiceEndpoint string `json:"serviceEndpoint,omitempty"`
// State: Output only. The current state of this Data Fusion instance.
//
// Possible values:
// "STATE_UNSPECIFIED" - Instance does not have a state yet
// "CREATING" - Instance is being created
// "RUNNING" - Instance is running and ready for requests
// "FAILED" - Instance creation failed
// "DELETING" - Instance is being deleted
// "UPGRADING" - Instance is being upgraded
// "RESTARTING" - Instance is being restarted
// "UPDATING" - Instance is being updated
State string `json:"state,omitempty"`
// StateMessage: Output only. Additional information about the current
// state of this Data
// Fusion instance if available.
StateMessage string `json:"stateMessage,omitempty"`
// Type: Required. Instance type.
//
// Possible values:
// "TYPE_UNSPECIFIED" - No type specified. The instance creation will
// fail.
// "BASIC" - Basic Data Fusion instance. In Basic type, the user will
// be able to
// create data pipelines using point and click UI. However, there
// are
// certain limitations, such as fewer number of concurrent pipelines,
// no
// support for streaming pipelines, etc.
// "ENTERPRISE" - Enterprise Data Fusion instance. In Enterprise type,
// the user will have
// more features available, such as support for streaming pipelines,
// higher
// number of concurrent pipelines, etc.
Type string `json:"type,omitempty"`
// UpdateTime: Output only. The time the instance was last updated.
UpdateTime string `json:"updateTime,omitempty"`
// Version: Output only. Current version of the Data Fusion.
Version string `json:"version,omitempty"`
// Zone: Name of the zone in which the Data Fusion instance will be
// created.
Zone string `json:"zone,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "CreateTime") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "CreateTime") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Instance) MarshalJSON() ([]byte, error) {
type NoMethod Instance
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ListInstancesResponse: Response message for the list instance
// request.
type ListInstancesResponse struct {
// Instances: Represents a list of Data Fusion instances.
Instances []*Instance `json:"instances,omitempty"`
// NextPageToken: Token to retrieve the next page of results or empty if
// there are no more
// results in the list.
NextPageToken string `json:"nextPageToken,omitempty"`
// Unreachable: Locations that could not be reached.
Unreachable []string `json:"unreachable,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Instances") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Instances") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ListInstancesResponse) MarshalJSON() ([]byte, error) {
type NoMethod ListInstancesResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ListLocationsResponse: The response message for
// Locations.ListLocations.
type ListLocationsResponse struct {
// Locations: A list of locations that matches the specified filter in
// the request.
Locations []*Location `json:"locations,omitempty"`
// NextPageToken: The standard List next-page token.
NextPageToken string `json:"nextPageToken,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Locations") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Locations") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ListLocationsResponse) MarshalJSON() ([]byte, error) {
type NoMethod ListLocationsResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ListOperationsResponse: The response message for
// Operations.ListOperations.
type ListOperationsResponse struct {
// NextPageToken: The standard List next-page token.
NextPageToken string `json:"nextPageToken,omitempty"`
// Operations: A list of operations that matches the specified filter in
// the request.
Operations []*Operation `json:"operations,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "NextPageToken") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "NextPageToken") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ListOperationsResponse) MarshalJSON() ([]byte, error) {
type NoMethod ListOperationsResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Location: A resource that represents Google Cloud Platform location.
type Location struct {
// DisplayName: The friendly name for this location, typically a nearby
// city name.
// For example, "Tokyo".
DisplayName string `json:"displayName,omitempty"`
// Labels: Cross-service attributes for the location. For example
//
// {"cloud.googleapis.com/region": "us-east1"}
Labels map[string]string `json:"labels,omitempty"`
// LocationId: The canonical id for this location. For example:
// "us-east1".
LocationId string `json:"locationId,omitempty"`
// Metadata: Service-specific metadata. For example the available
// capacity at the given
// location.
Metadata googleapi.RawMessage `json:"metadata,omitempty"`
// Name: Resource name for the location, which may vary between
// implementations.
// For example: "projects/example-project/locations/us-east1"
Name string `json:"name,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "DisplayName") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "DisplayName") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Location) MarshalJSON() ([]byte, error) {
type NoMethod Location
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// LogConfig: Specifies what kind of log the caller must write
type LogConfig struct {
// CloudAudit: Cloud audit options.
CloudAudit *CloudAuditOptions `json:"cloudAudit,omitempty"`
// Counter: Counter options.
Counter *CounterOptions `json:"counter,omitempty"`
// DataAccess: Data access options.
DataAccess *DataAccessOptions `json:"dataAccess,omitempty"`
// ForceSendFields is a list of field names (e.g. "CloudAudit") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "CloudAudit") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *LogConfig) MarshalJSON() ([]byte, error) {
type NoMethod LogConfig
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// NetworkConfig: Network configuration for a Data Fusion instance.
// These configurations
// are used for peering with the customer network. Configurations are
// optional
// when a public Data Fusion instance is to be created. However,
// providing
// these configurations allows several benefits, such as reduced network
// latency
// while accessing the customer resources from managed Data Fusion
// instance
// nodes, as well as access to the customer on-prem resources.
type NetworkConfig struct {
// IpAllocation: The IP range in CIDR notation to use for the managed
// Data Fusion instance
// nodes. This range must not overlap with any other ranges used in the
// Data
// Fusion instance network.
IpAllocation string `json:"ipAllocation,omitempty"`
// Network: Name of the network in the customer project with which the
// Tenant Project
// will be peered for executing pipelines.
Network string `json:"network,omitempty"`
// ForceSendFields is a list of field names (e.g. "IpAllocation") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "IpAllocation") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *NetworkConfig) MarshalJSON() ([]byte, error) {
type NoMethod NetworkConfig
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Operation: This resource represents a long-running operation that is
// the result of a
// network API call.
type Operation struct {
// Done: If the value is `false`, it means the operation is still in
// progress.
// If `true`, the operation is completed, and either `error` or
// `response` is
// available.
Done bool `json:"done,omitempty"`
// Error: The error result of the operation in case of failure or
// cancellation.
Error *Status `json:"error,omitempty"`
// Metadata: Service-specific metadata associated with the operation.
// It typically
// contains progress information and common metadata such as create
// time.
// Some services might not provide such metadata. Any method that
// returns a
// long-running operation should document the metadata type, if any.
Metadata googleapi.RawMessage `json:"metadata,omitempty"`
// Name: The server-assigned name, which is only unique within the same
// service that
// originally returns it. If you use the default HTTP mapping,
// the
// `name` should be a resource name ending with
// `operations/{unique_id}`.
Name string `json:"name,omitempty"`
// Response: The normal response of the operation in case of success.
// If the original
// method returns no data on success, such as `Delete`, the response
// is
// `google.protobuf.Empty`. If the original method is
// standard
// `Get`/`Create`/`Update`, the response should be the resource. For
// other
// methods, the response should have the type `XxxResponse`, where
// `Xxx`
// is the original method name. For example, if the original method
// name
// is `TakeSnapshot()`, the inferred response type
// is
// `TakeSnapshotResponse`.
Response googleapi.RawMessage `json:"response,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Done") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Done") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Operation) MarshalJSON() ([]byte, error) {
type NoMethod Operation
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// OperationMetadata: Represents the metadata of a long-running
// operation.
type OperationMetadata struct {
// ApiVersion: API version used to start the operation.
ApiVersion string `json:"apiVersion,omitempty"`
// CreateTime: The time the operation was created.
CreateTime string `json:"createTime,omitempty"`
// EndTime: The time the operation finished running.
EndTime string `json:"endTime,omitempty"`
// RequestedCancellation: Identifies whether the user has requested
// cancellation
// of the operation. Operations that have successfully been
// cancelled
// have Operation.error value with a google.rpc.Status.code of
// 1,
// corresponding to `Code.CANCELLED`.
RequestedCancellation bool `json:"requestedCancellation,omitempty"`
// StatusDetail: Human-readable status of the operation if any.
StatusDetail string `json:"statusDetail,omitempty"`
// Target: Server-defined resource path for the target of the operation.
Target string `json:"target,omitempty"`
// Verb: Name of the verb executed by the operation.
Verb string `json:"verb,omitempty"`
// ForceSendFields is a list of field names (e.g. "ApiVersion") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ApiVersion") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *OperationMetadata) MarshalJSON() ([]byte, error) {
type NoMethod OperationMetadata
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Policy: Defines an Identity and Access Management (IAM) policy. It is
// used to
// specify access control policies for Cloud Platform resources.
//
//
// A `Policy` consists of a list of `bindings`. A `binding` binds a list
// of
// `members` to a `role`, where the members can be user accounts, Google
// groups,
// Google domains, and service accounts. A `role` is a named list of
// permissions
// defined by IAM.
//
// **JSON Example**
//
// {
// "bindings": [
// {
// "role": "roles/owner",
// "members": [
// "user:mike@example.com",
// "group:admins@example.com",
// "domain:google.com",
//
// "serviceAccount:my-other-app@appspot.gserviceaccount.com"
// ]
// },
// {
// "role": "roles/viewer",
// "members": ["user:sean@example.com"]
// }
// ]
// }
//
// **YAML Example**
//
// bindings:
// - members:
// - user:mike@example.com
// - group:admins@example.com
// - domain:google.com
// - serviceAccount:my-other-app@appspot.gserviceaccount.com
// role: roles/owner
// - members:
// - user:sean@example.com
// role: roles/viewer
//
//
// For a description of IAM and its features, see the
// [IAM developer's guide](https://cloud.google.com/iam/docs).
type Policy struct {
// AuditConfigs: Specifies cloud audit logging configuration for this
// policy.
AuditConfigs []*AuditConfig `json:"auditConfigs,omitempty"`
// Bindings: Associates a list of `members` to a `role`.
// `bindings` with no members will result in an error.
Bindings []*Binding `json:"bindings,omitempty"`
// Etag: `etag` is used for optimistic concurrency control as a way to
// help
// prevent simultaneous updates of a policy from overwriting each
// other.
// It is strongly suggested that systems make use of the `etag` in
// the
// read-modify-write cycle to perform policy updates in order to avoid
// race
// conditions: An `etag` is returned in the response to `getIamPolicy`,
// and
// systems are expected to put that etag in the request to
// `setIamPolicy` to
// ensure that their change will be applied to the same version of the
// policy.
//
// If no `etag` is provided in the call to `setIamPolicy`, then the
// existing
// policy is overwritten blindly.
Etag string `json:"etag,omitempty"`
IamOwned bool `json:"iamOwned,omitempty"`
// Rules: If more than one rule is specified, the rules are applied in
// the following
// manner:
// - All matching LOG rules are always applied.
// - If any DENY/DENY_WITH_LOG rule matches, permission is denied.
// Logging will be applied if one or more matching rule requires
// logging.
// - Otherwise, if any ALLOW/ALLOW_WITH_LOG rule matches, permission is
// granted.
// Logging will be applied if one or more matching rule requires
// logging.
// - Otherwise, if no rule applies, permission is denied.
Rules []*Rule `json:"rules,omitempty"`
// Version: Deprecated.
Version int64 `json:"version,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "AuditConfigs") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "AuditConfigs") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Policy) MarshalJSON() ([]byte, error) {
type NoMethod Policy
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// RestartInstanceRequest: Request message for restarting a Data Fusion
// instance.
type RestartInstanceRequest struct {
}
// Rule: A rule to be applied in a Policy.
type Rule struct {
// Action: Required
//
// Possible values:
// "NO_ACTION" - Default no action.
// "ALLOW" - Matching 'Entries' grant access.
// "ALLOW_WITH_LOG" - Matching 'Entries' grant access and the caller
// promises to log
// the request per the returned log_configs.
// "DENY" - Matching 'Entries' deny access.
// "DENY_WITH_LOG" - Matching 'Entries' deny access and the caller
// promises to log
// the request per the returned log_configs.
// "LOG" - Matching 'Entries' tell IAM.Check callers to generate logs.
Action string `json:"action,omitempty"`
// Conditions: Additional restrictions that must be met. All conditions
// must pass for the
// rule to match.
Conditions []*Condition `json:"conditions,omitempty"`
// Description: Human-readable description of the rule.
Description string `json:"description,omitempty"`
// In: If one or more 'in' clauses are specified, the rule matches
// if
// the PRINCIPAL/AUTHORITY_SELECTOR is in at least one of these entries.
In []string `json:"in,omitempty"`
// LogConfig: The config returned to callers of tech.iam.IAM.CheckPolicy
// for any entries
// that match the LOG action.
LogConfig []*LogConfig `json:"logConfig,omitempty"`
// NotIn: If one or more 'not_in' clauses are specified, the rule
// matches
// if the PRINCIPAL/AUTHORITY_SELECTOR is in none of the entries.
// The format for in and not_in entries can be found at in the Local
// IAM
// documentation (see go/local-iam#features).
NotIn []string `json:"notIn,omitempty"`
// Permissions: A permission is a string of form '<service>.<resource
// type>.<verb>'
// (e.g., 'storage.buckets.list'). A value of '*' matches all
// permissions,
// and a verb part of '*' (e.g., 'storage.buckets.*') matches all verbs.
Permissions []string `json:"permissions,omitempty"`
// ForceSendFields is a list of field names (e.g. "Action") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Action") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Rule) MarshalJSON() ([]byte, error) {
type NoMethod Rule
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// SetIamPolicyRequest: Request message for `SetIamPolicy` method.
type SetIamPolicyRequest struct {
// Policy: REQUIRED: The complete policy to be applied to the
// `resource`. The size of
// the policy is limited to a few 10s of KB. An empty policy is a
// valid policy but certain Cloud Platform services (such as
// Projects)
// might reject them.
Policy *Policy `json:"policy,omitempty"`
// UpdateMask: OPTIONAL: A FieldMask specifying which fields of the
// policy to modify. Only
// the fields in the mask will be modified. If no mask is provided,
// the
// following default mask is used:
// paths: "bindings, etag"
// This field is only used by Cloud IAM.
UpdateMask string `json:"updateMask,omitempty"`
// ForceSendFields is a list of field names (e.g. "Policy") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Policy") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *SetIamPolicyRequest) MarshalJSON() ([]byte, error) {
type NoMethod SetIamPolicyRequest
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Status: The `Status` type defines a logical error model that is
// suitable for
// different programming environments, including REST APIs and RPC APIs.
// It is
// used by [gRPC](https://github.com/grpc). Each `Status` message
// contains
// three pieces of data: error code, error message, and error
// details.
//
// You can find out more about this error model and how to work with it
// in the
// [API Design Guide](https://cloud.google.com/apis/design/errors).
type Status struct {
// Code: The status code, which should be an enum value of
// google.rpc.Code.
Code int64 `json:"code,omitempty"`
// Details: A list of messages that carry the error details. There is a
// common set of
// message types for APIs to use.
Details []googleapi.RawMessage `json:"details,omitempty"`
// Message: A developer-facing error message, which should be in
// English. Any
// user-facing error message should be localized and sent in
// the
// google.rpc.Status.details field, or localized by the client.
Message string `json:"message,omitempty"`
// ForceSendFields is a list of field names (e.g. "Code") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Code") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Status) MarshalJSON() ([]byte, error) {
type NoMethod Status
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// TestIamPermissionsRequest: Request message for `TestIamPermissions`
// method.
type TestIamPermissionsRequest struct {
// Permissions: The set of permissions to check for the `resource`.
// Permissions with
// wildcards (such as '*' or 'storage.*') are not allowed. For
// more
// information see
// [IAM
// Overview](https://cloud.google.com/iam/docs/overview#permissions).
Permissions []string `json:"permissions,omitempty"`
// ForceSendFields is a list of field names (e.g. "Permissions") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Permissions") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *TestIamPermissionsRequest) MarshalJSON() ([]byte, error) {
type NoMethod TestIamPermissionsRequest
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// TestIamPermissionsResponse: Response message for `TestIamPermissions`
// method.
type TestIamPermissionsResponse struct {
// Permissions: A subset of `TestPermissionsRequest.permissions` that
// the caller is
// allowed.
Permissions []string `json:"permissions,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Permissions") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Permissions") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *TestIamPermissionsResponse) MarshalJSON() ([]byte, error) {
type NoMethod TestIamPermissionsResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// UpgradeInstanceRequest: Request message for upgrading a Data Fusion
// instance.
// To change the instance properties, instance update should be used.
type UpgradeInstanceRequest struct {
}
// method id "datafusion.projects.locations.get":
type ProjectsLocationsGetCall struct {
s *Service
name string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// Get: Gets information about a location.
func (r *ProjectsLocationsService) Get(name string) *ProjectsLocationsGetCall {
c := &ProjectsLocationsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsGetCall) Fields(s ...googleapi.Field) *ProjectsLocationsGetCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ProjectsLocationsGetCall) IfNoneMatch(entityTag string) *ProjectsLocationsGetCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsGetCall) Context(ctx context.Context) *ProjectsLocationsGetCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsGetCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsGetCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190924")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datafusion.projects.locations.get" call.
// Exactly one of *Location or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Location.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *ProjectsLocationsGetCall) Do(opts ...googleapi.CallOption) (*Location, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Location{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Gets information about a location.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}",
// "httpMethod": "GET",
// "id": "datafusion.projects.locations.get",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "Resource name for the location.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+name}",
// "response": {
// "$ref": "Location"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datafusion.projects.locations.list":
type ProjectsLocationsListCall struct {
s *Service
name string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Lists information about the supported locations for this
// service.
func (r *ProjectsLocationsService) List(name string) *ProjectsLocationsListCall {
c := &ProjectsLocationsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
return c
}
// Filter sets the optional parameter "filter": The standard list
// filter.
func (c *ProjectsLocationsListCall) Filter(filter string) *ProjectsLocationsListCall {
c.urlParams_.Set("filter", filter)
return c
}
// PageSize sets the optional parameter "pageSize": The standard list
// page size.
func (c *ProjectsLocationsListCall) PageSize(pageSize int64) *ProjectsLocationsListCall {
c.urlParams_.Set("pageSize", fmt.Sprint(pageSize))
return c
}
// PageToken sets the optional parameter "pageToken": The standard list
// page token.
func (c *ProjectsLocationsListCall) PageToken(pageToken string) *ProjectsLocationsListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsListCall) Fields(s ...googleapi.Field) *ProjectsLocationsListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ProjectsLocationsListCall) IfNoneMatch(entityTag string) *ProjectsLocationsListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsListCall) Context(ctx context.Context) *ProjectsLocationsListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190924")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}/locations")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datafusion.projects.locations.list" call.
// Exactly one of *ListLocationsResponse or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *ListLocationsResponse.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ProjectsLocationsListCall) Do(opts ...googleapi.CallOption) (*ListLocationsResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ListLocationsResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Lists information about the supported locations for this service.",
// "flatPath": "v1beta1/projects/{projectsId}/locations",
// "httpMethod": "GET",
// "id": "datafusion.projects.locations.list",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "filter": {
// "description": "The standard list filter.",
// "location": "query",
// "type": "string"
// },
// "name": {
// "description": "The resource that owns the locations collection, if applicable.",
// "location": "path",
// "pattern": "^projects/[^/]+$",
// "required": true,
// "type": "string"
// },
// "pageSize": {
// "description": "The standard list page size.",
// "format": "int32",
// "location": "query",
// "type": "integer"
// },
// "pageToken": {
// "description": "The standard list page token.",
// "location": "query",
// "type": "string"
// }
// },
// "path": "v1beta1/{+name}/locations",
// "response": {
// "$ref": "ListLocationsResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *ProjectsLocationsListCall) Pages(ctx context.Context, f func(*ListLocationsResponse) error) error {
c.ctx_ = ctx
defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.PageToken(x.NextPageToken)
}
}
// method id "datafusion.projects.locations.instances.create":
type ProjectsLocationsInstancesCreateCall struct {
s *Service
parent string
instance *Instance
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Create: Creates a new Data Fusion instance in the specified project
// and location.
func (r *ProjectsLocationsInstancesService) Create(parent string, instance *Instance) *ProjectsLocationsInstancesCreateCall {
c := &ProjectsLocationsInstancesCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.parent = parent
c.instance = instance
return c
}
// InstanceId sets the optional parameter "instanceId": The name of the
// instance to create.
func (c *ProjectsLocationsInstancesCreateCall) InstanceId(instanceId string) *ProjectsLocationsInstancesCreateCall {
c.urlParams_.Set("instanceId", instanceId)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsInstancesCreateCall) Fields(s ...googleapi.Field) *ProjectsLocationsInstancesCreateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsInstancesCreateCall) Context(ctx context.Context) *ProjectsLocationsInstancesCreateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsInstancesCreateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsInstancesCreateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190924")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.instance)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+parent}/instances")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"parent": c.parent,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datafusion.projects.locations.instances.create" call.
// Exactly one of *Operation or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *Operation.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *ProjectsLocationsInstancesCreateCall) Do(opts ...googleapi.CallOption) (*Operation, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Operation{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Creates a new Data Fusion instance in the specified project and location.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/instances",
// "httpMethod": "POST",
// "id": "datafusion.projects.locations.instances.create",
// "parameterOrder": [
// "parent"
// ],
// "parameters": {
// "instanceId": {
// "description": "The name of the instance to create.",
// "location": "query",
// "type": "string"
// },
// "parent": {
// "description": "The instance's project and location in the format\nprojects/{project}/locations/{location}.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+parent}/instances",
// "request": {
// "$ref": "Instance"
// },
// "response": {
// "$ref": "Operation"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datafusion.projects.locations.instances.delete":
type ProjectsLocationsInstancesDeleteCall struct {
s *Service
name string
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Delete: Deletes a single Date Fusion instance.
func (r *ProjectsLocationsInstancesService) Delete(name string) *ProjectsLocationsInstancesDeleteCall {
c := &ProjectsLocationsInstancesDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsInstancesDeleteCall) Fields(s ...googleapi.Field) *ProjectsLocationsInstancesDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsInstancesDeleteCall) Context(ctx context.Context) *ProjectsLocationsInstancesDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsInstancesDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsInstancesDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190924")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("DELETE", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datafusion.projects.locations.instances.delete" call.
// Exactly one of *Operation or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *Operation.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *ProjectsLocationsInstancesDeleteCall) Do(opts ...googleapi.CallOption) (*Operation, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Operation{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Deletes a single Date Fusion instance.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/instances/{instancesId}",
// "httpMethod": "DELETE",
// "id": "datafusion.projects.locations.instances.delete",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "The instance resource name in the format\nprojects/{project}/locations/{location}/instances/{instance}",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/instances/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+name}",
// "response": {
// "$ref": "Operation"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datafusion.projects.locations.instances.get":
type ProjectsLocationsInstancesGetCall struct {
s *Service
name string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// Get: Gets details of a single Data Fusion instance.
func (r *ProjectsLocationsInstancesService) Get(name string) *ProjectsLocationsInstancesGetCall {
c := &ProjectsLocationsInstancesGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsInstancesGetCall) Fields(s ...googleapi.Field) *ProjectsLocationsInstancesGetCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ProjectsLocationsInstancesGetCall) IfNoneMatch(entityTag string) *ProjectsLocationsInstancesGetCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsInstancesGetCall) Context(ctx context.Context) *ProjectsLocationsInstancesGetCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsInstancesGetCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsInstancesGetCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190924")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datafusion.projects.locations.instances.get" call.
// Exactly one of *Instance or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Instance.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *ProjectsLocationsInstancesGetCall) Do(opts ...googleapi.CallOption) (*Instance, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Instance{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Gets details of a single Data Fusion instance.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/instances/{instancesId}",
// "httpMethod": "GET",
// "id": "datafusion.projects.locations.instances.get",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "The instance resource name in the format\nprojects/{project}/locations/{location}/instances/{instance}.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/instances/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+name}",
// "response": {
// "$ref": "Instance"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datafusion.projects.locations.instances.getIamPolicy":
type ProjectsLocationsInstancesGetIamPolicyCall struct {
s *Service
resource string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// GetIamPolicy: Gets the access control policy for a resource.
// Returns an empty policy if the resource exists and does not have a
// policy
// set.
func (r *ProjectsLocationsInstancesService) GetIamPolicy(resource string) *ProjectsLocationsInstancesGetIamPolicyCall {
c := &ProjectsLocationsInstancesGetIamPolicyCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.resource = resource
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsInstancesGetIamPolicyCall) Fields(s ...googleapi.Field) *ProjectsLocationsInstancesGetIamPolicyCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ProjectsLocationsInstancesGetIamPolicyCall) IfNoneMatch(entityTag string) *ProjectsLocationsInstancesGetIamPolicyCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsInstancesGetIamPolicyCall) Context(ctx context.Context) *ProjectsLocationsInstancesGetIamPolicyCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsInstancesGetIamPolicyCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsInstancesGetIamPolicyCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190924")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+resource}:getIamPolicy")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"resource": c.resource,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datafusion.projects.locations.instances.getIamPolicy" call.
// Exactly one of *Policy or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Policy.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ProjectsLocationsInstancesGetIamPolicyCall) Do(opts ...googleapi.CallOption) (*Policy, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Policy{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Gets the access control policy for a resource.\nReturns an empty policy if the resource exists and does not have a policy\nset.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/instances/{instancesId}:getIamPolicy",
// "httpMethod": "GET",
// "id": "datafusion.projects.locations.instances.getIamPolicy",
// "parameterOrder": [
// "resource"
// ],
// "parameters": {
// "resource": {
// "description": "REQUIRED: The resource for which the policy is being requested.\nSee the operation documentation for the appropriate value for this field.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/instances/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+resource}:getIamPolicy",
// "response": {
// "$ref": "Policy"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datafusion.projects.locations.instances.list":
type ProjectsLocationsInstancesListCall struct {
s *Service
parent string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Lists Data Fusion instances in the specified project and
// location.
func (r *ProjectsLocationsInstancesService) List(parent string) *ProjectsLocationsInstancesListCall {
c := &ProjectsLocationsInstancesListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.parent = parent
return c
}
// Filter sets the optional parameter "filter": List filter.
func (c *ProjectsLocationsInstancesListCall) Filter(filter string) *ProjectsLocationsInstancesListCall {
c.urlParams_.Set("filter", filter)
return c
}
// OrderBy sets the optional parameter "orderBy": Sort results.
// Supported values are "name", "name desc", or "" (unsorted).
func (c *ProjectsLocationsInstancesListCall) OrderBy(orderBy string) *ProjectsLocationsInstancesListCall {
c.urlParams_.Set("orderBy", orderBy)
return c
}
// PageSize sets the optional parameter "pageSize": The maximum number
// of items to return.
func (c *ProjectsLocationsInstancesListCall) PageSize(pageSize int64) *ProjectsLocationsInstancesListCall {
c.urlParams_.Set("pageSize", fmt.Sprint(pageSize))
return c
}
// PageToken sets the optional parameter "pageToken": The
// next_page_token value to use if there are additional
// results to retrieve for this list request.
func (c *ProjectsLocationsInstancesListCall) PageToken(pageToken string) *ProjectsLocationsInstancesListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsInstancesListCall) Fields(s ...googleapi.Field) *ProjectsLocationsInstancesListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ProjectsLocationsInstancesListCall) IfNoneMatch(entityTag string) *ProjectsLocationsInstancesListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsInstancesListCall) Context(ctx context.Context) *ProjectsLocationsInstancesListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsInstancesListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsInstancesListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190924")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+parent}/instances")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"parent": c.parent,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datafusion.projects.locations.instances.list" call.
// Exactly one of *ListInstancesResponse or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *ListInstancesResponse.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ProjectsLocationsInstancesListCall) Do(opts ...googleapi.CallOption) (*ListInstancesResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ListInstancesResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Lists Data Fusion instances in the specified project and location.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/instances",
// "httpMethod": "GET",
// "id": "datafusion.projects.locations.instances.list",
// "parameterOrder": [
// "parent"
// ],
// "parameters": {
// "filter": {
// "description": "List filter.",
// "location": "query",
// "type": "string"
// },
// "orderBy": {
// "description": "Sort results. Supported values are \"name\", \"name desc\", or \"\" (unsorted).",
// "location": "query",
// "type": "string"
// },
// "pageSize": {
// "description": "The maximum number of items to return.",
// "format": "int32",
// "location": "query",
// "type": "integer"
// },
// "pageToken": {
// "description": "The next_page_token value to use if there are additional\nresults to retrieve for this list request.",
// "location": "query",
// "type": "string"
// },
// "parent": {
// "description": "The project and location for which to retrieve instance information\nin the format projects/{project}/locations/{location}. If the location is\nspecified as '-' (wildcard), then all regions available to the project\nare queried, and the results are aggregated.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+parent}/instances",
// "response": {
// "$ref": "ListInstancesResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *ProjectsLocationsInstancesListCall) Pages(ctx context.Context, f func(*ListInstancesResponse) error) error {
c.ctx_ = ctx
defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.PageToken(x.NextPageToken)
}
}
// method id "datafusion.projects.locations.instances.patch":
type ProjectsLocationsInstancesPatchCall struct {
s *Service
name string
instance *Instance
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Patch: Updates a single Data Fusion instance.
func (r *ProjectsLocationsInstancesService) Patch(name string, instance *Instance) *ProjectsLocationsInstancesPatchCall {
c := &ProjectsLocationsInstancesPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
c.instance = instance
return c
}
// UpdateMask sets the optional parameter "updateMask": Field mask is
// used to specify the fields that the update will overwrite
// in an instance resource. The fields specified in the update_mask
// are
// relative to the resource, not the full request.
// A field will be overwritten if it is in the mask.
// If the user does not provide a mask, all the supported fields (labels
// and
// options currently) will be overwritten.
func (c *ProjectsLocationsInstancesPatchCall) UpdateMask(updateMask string) *ProjectsLocationsInstancesPatchCall {
c.urlParams_.Set("updateMask", updateMask)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsInstancesPatchCall) Fields(s ...googleapi.Field) *ProjectsLocationsInstancesPatchCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsInstancesPatchCall) Context(ctx context.Context) *ProjectsLocationsInstancesPatchCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsInstancesPatchCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsInstancesPatchCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190924")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.instance)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("PATCH", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datafusion.projects.locations.instances.patch" call.
// Exactly one of *Operation or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *Operation.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *ProjectsLocationsInstancesPatchCall) Do(opts ...googleapi.CallOption) (*Operation, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Operation{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates a single Data Fusion instance.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/instances/{instancesId}",
// "httpMethod": "PATCH",
// "id": "datafusion.projects.locations.instances.patch",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "Output only. The name of this instance is in the form of\nprojects/{project}/locations/{location}/instances/{instance}.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/instances/[^/]+$",
// "required": true,
// "type": "string"
// },
// "updateMask": {
// "description": "Field mask is used to specify the fields that the update will overwrite\nin an instance resource. The fields specified in the update_mask are\nrelative to the resource, not the full request.\nA field will be overwritten if it is in the mask.\nIf the user does not provide a mask, all the supported fields (labels and\noptions currently) will be overwritten.",
// "format": "google-fieldmask",
// "location": "query",
// "type": "string"
// }
// },
// "path": "v1beta1/{+name}",
// "request": {
// "$ref": "Instance"
// },
// "response": {
// "$ref": "Operation"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datafusion.projects.locations.instances.restart":
type ProjectsLocationsInstancesRestartCall struct {
s *Service
name string
restartinstancerequest *RestartInstanceRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Restart: Restart a single Data Fusion instance.
// At the end of an operation instance is fully restarted.
func (r *ProjectsLocationsInstancesService) Restart(name string, restartinstancerequest *RestartInstanceRequest) *ProjectsLocationsInstancesRestartCall {
c := &ProjectsLocationsInstancesRestartCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
c.restartinstancerequest = restartinstancerequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsInstancesRestartCall) Fields(s ...googleapi.Field) *ProjectsLocationsInstancesRestartCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsInstancesRestartCall) Context(ctx context.Context) *ProjectsLocationsInstancesRestartCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsInstancesRestartCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsInstancesRestartCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190924")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.restartinstancerequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}:restart")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datafusion.projects.locations.instances.restart" call.
// Exactly one of *Operation or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *Operation.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *ProjectsLocationsInstancesRestartCall) Do(opts ...googleapi.CallOption) (*Operation, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Operation{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Restart a single Data Fusion instance.\nAt the end of an operation instance is fully restarted.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/instances/{instancesId}:restart",
// "httpMethod": "POST",
// "id": "datafusion.projects.locations.instances.restart",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "Name of the Data Fusion instance which need to be restarted in the form of\nprojects/{project}/locations/{location}/instances/{instance}",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/instances/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+name}:restart",
// "request": {
// "$ref": "RestartInstanceRequest"
// },
// "response": {
// "$ref": "Operation"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datafusion.projects.locations.instances.setIamPolicy":
type ProjectsLocationsInstancesSetIamPolicyCall struct {
s *Service
resource string
setiampolicyrequest *SetIamPolicyRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// SetIamPolicy: Sets the access control policy on the specified
// resource. Replaces any
// existing policy.
func (r *ProjectsLocationsInstancesService) SetIamPolicy(resource string, setiampolicyrequest *SetIamPolicyRequest) *ProjectsLocationsInstancesSetIamPolicyCall {
c := &ProjectsLocationsInstancesSetIamPolicyCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.resource = resource
c.setiampolicyrequest = setiampolicyrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsInstancesSetIamPolicyCall) Fields(s ...googleapi.Field) *ProjectsLocationsInstancesSetIamPolicyCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsInstancesSetIamPolicyCall) Context(ctx context.Context) *ProjectsLocationsInstancesSetIamPolicyCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsInstancesSetIamPolicyCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsInstancesSetIamPolicyCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190924")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.setiampolicyrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+resource}:setIamPolicy")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"resource": c.resource,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datafusion.projects.locations.instances.setIamPolicy" call.
// Exactly one of *Policy or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Policy.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ProjectsLocationsInstancesSetIamPolicyCall) Do(opts ...googleapi.CallOption) (*Policy, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Policy{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Sets the access control policy on the specified resource. Replaces any\nexisting policy.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/instances/{instancesId}:setIamPolicy",
// "httpMethod": "POST",
// "id": "datafusion.projects.locations.instances.setIamPolicy",
// "parameterOrder": [
// "resource"
// ],
// "parameters": {
// "resource": {
// "description": "REQUIRED: The resource for which the policy is being specified.\nSee the operation documentation for the appropriate value for this field.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/instances/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+resource}:setIamPolicy",
// "request": {
// "$ref": "SetIamPolicyRequest"
// },
// "response": {
// "$ref": "Policy"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datafusion.projects.locations.instances.testIamPermissions":
type ProjectsLocationsInstancesTestIamPermissionsCall struct {
s *Service
resource string
testiampermissionsrequest *TestIamPermissionsRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// TestIamPermissions: Returns permissions that a caller has on the
// specified resource.
// If the resource does not exist, this will return an empty set
// of
// permissions, not a NOT_FOUND error.
//
// Note: This operation is designed to be used for building
// permission-aware
// UIs and command-line tools, not for authorization checking. This
// operation
// may "fail open" without warning.
func (r *ProjectsLocationsInstancesService) TestIamPermissions(resource string, testiampermissionsrequest *TestIamPermissionsRequest) *ProjectsLocationsInstancesTestIamPermissionsCall {
c := &ProjectsLocationsInstancesTestIamPermissionsCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.resource = resource
c.testiampermissionsrequest = testiampermissionsrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsInstancesTestIamPermissionsCall) Fields(s ...googleapi.Field) *ProjectsLocationsInstancesTestIamPermissionsCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsInstancesTestIamPermissionsCall) Context(ctx context.Context) *ProjectsLocationsInstancesTestIamPermissionsCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsInstancesTestIamPermissionsCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsInstancesTestIamPermissionsCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190924")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.testiampermissionsrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+resource}:testIamPermissions")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"resource": c.resource,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datafusion.projects.locations.instances.testIamPermissions" call.
// Exactly one of *TestIamPermissionsResponse or error will be non-nil.
// Any non-2xx status code is an error. Response headers are in either
// *TestIamPermissionsResponse.ServerResponse.Header or (if a response
// was returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ProjectsLocationsInstancesTestIamPermissionsCall) Do(opts ...googleapi.CallOption) (*TestIamPermissionsResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &TestIamPermissionsResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Returns permissions that a caller has on the specified resource.\nIf the resource does not exist, this will return an empty set of\npermissions, not a NOT_FOUND error.\n\nNote: This operation is designed to be used for building permission-aware\nUIs and command-line tools, not for authorization checking. This operation\nmay \"fail open\" without warning.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/instances/{instancesId}:testIamPermissions",
// "httpMethod": "POST",
// "id": "datafusion.projects.locations.instances.testIamPermissions",
// "parameterOrder": [
// "resource"
// ],
// "parameters": {
// "resource": {
// "description": "REQUIRED: The resource for which the policy detail is being requested.\nSee the operation documentation for the appropriate value for this field.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/instances/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+resource}:testIamPermissions",
// "request": {
// "$ref": "TestIamPermissionsRequest"
// },
// "response": {
// "$ref": "TestIamPermissionsResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datafusion.projects.locations.instances.upgrade":
type ProjectsLocationsInstancesUpgradeCall struct {
s *Service
name string
upgradeinstancerequest *UpgradeInstanceRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Upgrade: Upgrade a single Data Fusion instance.
// At the end of an operation instance is fully upgraded.
func (r *ProjectsLocationsInstancesService) Upgrade(name string, upgradeinstancerequest *UpgradeInstanceRequest) *ProjectsLocationsInstancesUpgradeCall {
c := &ProjectsLocationsInstancesUpgradeCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
c.upgradeinstancerequest = upgradeinstancerequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsInstancesUpgradeCall) Fields(s ...googleapi.Field) *ProjectsLocationsInstancesUpgradeCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsInstancesUpgradeCall) Context(ctx context.Context) *ProjectsLocationsInstancesUpgradeCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsInstancesUpgradeCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsInstancesUpgradeCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190924")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.upgradeinstancerequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}:upgrade")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datafusion.projects.locations.instances.upgrade" call.
// Exactly one of *Operation or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *Operation.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *ProjectsLocationsInstancesUpgradeCall) Do(opts ...googleapi.CallOption) (*Operation, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Operation{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Upgrade a single Data Fusion instance.\nAt the end of an operation instance is fully upgraded.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/instances/{instancesId}:upgrade",
// "httpMethod": "POST",
// "id": "datafusion.projects.locations.instances.upgrade",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "Name of the Data Fusion instance which need to be upgraded in the form of\nprojects/{project}/locations/{location}/instances/{instance}\nInstance will be upgraded with the latest stable version of the Data\nFusion.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/instances/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+name}:upgrade",
// "request": {
// "$ref": "UpgradeInstanceRequest"
// },
// "response": {
// "$ref": "Operation"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datafusion.projects.locations.operations.cancel":
type ProjectsLocationsOperationsCancelCall struct {
s *Service
name string
canceloperationrequest *CancelOperationRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Cancel: Starts asynchronous cancellation on a long-running operation.
// The server
// makes a best effort to cancel the operation, but success is
// not
// guaranteed. If the server doesn't support this method, it
// returns
// `google.rpc.Code.UNIMPLEMENTED`. Clients can
// use
// Operations.GetOperation or
// other methods to check whether the cancellation succeeded or whether
// the
// operation completed despite cancellation. On successful
// cancellation,
// the operation is not deleted; instead, it becomes an operation
// with
// an Operation.error value with a google.rpc.Status.code of
// 1,
// corresponding to `Code.CANCELLED`.
func (r *ProjectsLocationsOperationsService) Cancel(name string, canceloperationrequest *CancelOperationRequest) *ProjectsLocationsOperationsCancelCall {
c := &ProjectsLocationsOperationsCancelCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
c.canceloperationrequest = canceloperationrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsOperationsCancelCall) Fields(s ...googleapi.Field) *ProjectsLocationsOperationsCancelCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsOperationsCancelCall) Context(ctx context.Context) *ProjectsLocationsOperationsCancelCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsOperationsCancelCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsOperationsCancelCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190924")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.canceloperationrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}:cancel")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datafusion.projects.locations.operations.cancel" call.
// Exactly one of *Empty or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Empty.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ProjectsLocationsOperationsCancelCall) Do(opts ...googleapi.CallOption) (*Empty, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Empty{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Starts asynchronous cancellation on a long-running operation. The server\nmakes a best effort to cancel the operation, but success is not\nguaranteed. If the server doesn't support this method, it returns\n`google.rpc.Code.UNIMPLEMENTED`. Clients can use\nOperations.GetOperation or\nother methods to check whether the cancellation succeeded or whether the\noperation completed despite cancellation. On successful cancellation,\nthe operation is not deleted; instead, it becomes an operation with\nan Operation.error value with a google.rpc.Status.code of 1,\ncorresponding to `Code.CANCELLED`.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/operations/{operationsId}:cancel",
// "httpMethod": "POST",
// "id": "datafusion.projects.locations.operations.cancel",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "The name of the operation resource to be cancelled.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/operations/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+name}:cancel",
// "request": {
// "$ref": "CancelOperationRequest"
// },
// "response": {
// "$ref": "Empty"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datafusion.projects.locations.operations.delete":
type ProjectsLocationsOperationsDeleteCall struct {
s *Service
name string
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Delete: Deletes a long-running operation. This method indicates that
// the client is
// no longer interested in the operation result. It does not cancel
// the
// operation. If the server doesn't support this method, it
// returns
// `google.rpc.Code.UNIMPLEMENTED`.
func (r *ProjectsLocationsOperationsService) Delete(name string) *ProjectsLocationsOperationsDeleteCall {
c := &ProjectsLocationsOperationsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsOperationsDeleteCall) Fields(s ...googleapi.Field) *ProjectsLocationsOperationsDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsOperationsDeleteCall) Context(ctx context.Context) *ProjectsLocationsOperationsDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsOperationsDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsOperationsDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190924")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("DELETE", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datafusion.projects.locations.operations.delete" call.
// Exactly one of *Empty or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Empty.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ProjectsLocationsOperationsDeleteCall) Do(opts ...googleapi.CallOption) (*Empty, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Empty{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Deletes a long-running operation. This method indicates that the client is\nno longer interested in the operation result. It does not cancel the\noperation. If the server doesn't support this method, it returns\n`google.rpc.Code.UNIMPLEMENTED`.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/operations/{operationsId}",
// "httpMethod": "DELETE",
// "id": "datafusion.projects.locations.operations.delete",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "The name of the operation resource to be deleted.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/operations/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+name}",
// "response": {
// "$ref": "Empty"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datafusion.projects.locations.operations.get":
type ProjectsLocationsOperationsGetCall struct {
s *Service
name string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// Get: Gets the latest state of a long-running operation. Clients can
// use this
// method to poll the operation result at intervals as recommended by
// the API
// service.
func (r *ProjectsLocationsOperationsService) Get(name string) *ProjectsLocationsOperationsGetCall {
c := &ProjectsLocationsOperationsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsOperationsGetCall) Fields(s ...googleapi.Field) *ProjectsLocationsOperationsGetCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ProjectsLocationsOperationsGetCall) IfNoneMatch(entityTag string) *ProjectsLocationsOperationsGetCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsOperationsGetCall) Context(ctx context.Context) *ProjectsLocationsOperationsGetCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsOperationsGetCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsOperationsGetCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190924")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datafusion.projects.locations.operations.get" call.
// Exactly one of *Operation or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *Operation.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *ProjectsLocationsOperationsGetCall) Do(opts ...googleapi.CallOption) (*Operation, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Operation{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Gets the latest state of a long-running operation. Clients can use this\nmethod to poll the operation result at intervals as recommended by the API\nservice.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/operations/{operationsId}",
// "httpMethod": "GET",
// "id": "datafusion.projects.locations.operations.get",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "The name of the operation resource.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/operations/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta1/{+name}",
// "response": {
// "$ref": "Operation"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "datafusion.projects.locations.operations.list":
type ProjectsLocationsOperationsListCall struct {
s *Service
name string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Lists operations that match the specified filter in the
// request. If the
// server doesn't support this method, it returns
// `UNIMPLEMENTED`.
//
// NOTE: the `name` binding allows API services to override the
// binding
// to use different resource name schemes, such as `users/*/operations`.
// To
// override the binding, API services can add a binding such
// as
// "/v1/{name=users/*}/operations" to their service configuration.
// For backwards compatibility, the default name includes the
// operations
// collection id, however overriding users must ensure the name
// binding
// is the parent resource, without the operations collection id.
func (r *ProjectsLocationsOperationsService) List(name string) *ProjectsLocationsOperationsListCall {
c := &ProjectsLocationsOperationsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
return c
}
// Filter sets the optional parameter "filter": The standard list
// filter.
func (c *ProjectsLocationsOperationsListCall) Filter(filter string) *ProjectsLocationsOperationsListCall {
c.urlParams_.Set("filter", filter)
return c
}
// PageSize sets the optional parameter "pageSize": The standard list
// page size.
func (c *ProjectsLocationsOperationsListCall) PageSize(pageSize int64) *ProjectsLocationsOperationsListCall {
c.urlParams_.Set("pageSize", fmt.Sprint(pageSize))
return c
}
// PageToken sets the optional parameter "pageToken": The standard list
// page token.
func (c *ProjectsLocationsOperationsListCall) PageToken(pageToken string) *ProjectsLocationsOperationsListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsOperationsListCall) Fields(s ...googleapi.Field) *ProjectsLocationsOperationsListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ProjectsLocationsOperationsListCall) IfNoneMatch(entityTag string) *ProjectsLocationsOperationsListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsOperationsListCall) Context(ctx context.Context) *ProjectsLocationsOperationsListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsOperationsListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsOperationsListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190924")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}/operations")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "datafusion.projects.locations.operations.list" call.
// Exactly one of *ListOperationsResponse or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *ListOperationsResponse.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ProjectsLocationsOperationsListCall) Do(opts ...googleapi.CallOption) (*ListOperationsResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ListOperationsResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Lists operations that match the specified filter in the request. If the\nserver doesn't support this method, it returns `UNIMPLEMENTED`.\n\nNOTE: the `name` binding allows API services to override the binding\nto use different resource name schemes, such as `users/*/operations`. To\noverride the binding, API services can add a binding such as\n`\"/v1/{name=users/*}/operations\"` to their service configuration.\nFor backwards compatibility, the default name includes the operations\ncollection id, however overriding users must ensure the name binding\nis the parent resource, without the operations collection id.",
// "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/operations",
// "httpMethod": "GET",
// "id": "datafusion.projects.locations.operations.list",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "filter": {
// "description": "The standard list filter.",
// "location": "query",
// "type": "string"
// },
// "name": {
// "description": "The name of the operation's parent resource.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+$",
// "required": true,
// "type": "string"
// },
// "pageSize": {
// "description": "The standard list page size.",
// "format": "int32",
// "location": "query",
// "type": "integer"
// },
// "pageToken": {
// "description": "The standard list page token.",
// "location": "query",
// "type": "string"
// }
// },
// "path": "v1beta1/{+name}/operations",
// "response": {
// "$ref": "ListOperationsResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *ProjectsLocationsOperationsListCall) Pages(ctx context.Context, f func(*ListOperationsResponse) error) error {
c.ctx_ = ctx
defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.PageToken(x.NextPageToken)
}
}
| pushbullet/engineer | vendor/google.golang.org/api/datafusion/v1beta1/datafusion-gen.go | GO | mit | 150,488 |