repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
XetaIO/Xetaravel | resources/views/Admin/Role/role/update.blade.php | 2797 | @extends('layouts.admin')
{!! config(['app.title' => 'Update ' . e($role->name)]) !!}
@section('content')
<div class="col-sm-12 col-md-10 offset-md-2 p-2">
{!! $breadcrumbs->render() !!}
</div>
<div class="col-sm-12 col-md-10 offset-md-2 pl-2 pr-2 pb-2">
<div class="card card-inverse bg-inverse">
<h5 class="card-header">
Update : {{ $role->name }}
</h5>
<div class="card-block">
@if ($role->permissions()->get()->contains($permission))
<p class="text-danger">
Be careful when editing the permissions, you can remove the administration access for this role !
</p>
@endif
{!! Form::model(
$role,
[
'route' => ['admin.role.role.update', $role->id],
'method' => 'put'
]
) !!}
{!! Form::bsText(
'name',
'Name',
null,
['class' => 'form-control form-control-inverse col-md-6', 'placeholder' => 'Role name...']
) !!}
{!! Form::bsText(
'css',
'CSS',
null,
[
'class' => 'form-control form-control-inverse col-md-6',
'formText' => 'This CSS is used to color the role name everywhere on the website.',
'placeholder' => 'Role css...']
) !!}
{!! Form::bsNumber(
'level',
'Level',
null,
['class' => 'form-control form-control-inverse col-md-6']
) !!}
{!! Form::bsSelect(
'permissions[]',
$permissions,
'Permissions',
$role->permissions->pluck('id')->toArray(),
['class' => 'form-control form-control-inverse col-md-6', 'multiple'],
$optionsAttributes
) !!}
{!! Form::bsTextarea(
'description',
'Description',
null,
['class' => 'form-control form-control-inverse col-md-6', 'placeholder' => 'Role description...']
) !!}
<div class="form-group">
<div class="col-md-12">
{!! Form::button('<i class="fa fa-edit" aria-hidden="true"></i> Update', ['type' => 'submit', 'class' => 'btn btn-outline-primary']) !!}
</div>
</div>
{!! Form::close() !!}
</div>
</div>
</div>
@endsection
| mit |
web-innovate/leave-tracking | frontend/src/resources/value-converters/compute-badge.js | 426 | import { REQUEST_STATUS } from '~/util/constants'
export class ComputeBadgeValueConverter {
toView(value) {
switch(value) {
case REQUEST_STATUS.APPROVED:
return 'list-group-item-success';
case REQUEST_STATUS.REJECTED:
return 'list-group-item-danger';
case REQUEST_STATUS.PENDING:
return 'list-group-item-info';
}
}
}
| mit |
ncgreco1440/php-library-bootstrap | lib/controllers/adminpages.contrl.php | 3215 | <?php
use Quasar\Kernel;
use Authentication\Authenticate;
use Authentication\Validate;
use Quasar\Page;
use Database\Connection;
use Bulletproof\Image;
class AdminPages extends Page
{
private $ID;
public function load()
{
$query = Kernel::getQuery() != "" ? Kernel::getQuery() : false;
$this->ID = Connection::query("SELECT `ID` FROM `Q_PAGES` WHERE `name` = '$query'", true)['ID'];
Authenticate::loggedIn();
$message = self::analyzePost();
$selectedPage = false;
if($query)
$selectedPage = self::getWebPage($query);
$page = "Quasar | Pages";
$text = "Manage your websites webpages.";
$webpages = self::getWebPages();
return ["file" => "admin/pages", "query" => $query,
"content" => compact("page", "text", "webpages", "selectedPage")];
}
/**
* [analyzePost Will take a look at the post a determine
* if it's a standard contact or signin form]
* @param [array] $post [posted values from $_POST]
* @return [void] [void]
*/
private function analyzePost()
{
if(isset($_REQUEST['logout']))
Authenticate::logOut();
if(isset($_POST['savePage']) && isset($_FILES))
{
$this->setWebPageText($_POST);
$this->setWebPageImg($_FILES);
}
}
private function getWebPage($page)
{
$contents = Connection::query("SELECT * FROM `Q_PAGES` WHERE `ID` = '$this->ID'", true);
return ["Pagename" => $page, "Contents" => $contents];
}
private function getWebPages()
{
$select = "*";
$from = "main_navigation";
$webpages = Connection::simplySelAll(compact("select", "from"));
foreach($webpages as $key => $value)
{
$tmp = strtolower($value['name']);
$tmp = str_replace(" ", "-", $tmp);
$value['name'] == "Home" ? $value['link'] = "/" : $value['link'] = $tmp;
$webpages[$key] = $value;
}
return $webpages;
}
private function setWebPageText($post)
{
Connection::query("UPDATE `Q_PAGES` SET
`main_text` = '$post[main_text]',
`sub_text_1` = '$post[sub_text_1]',
`sub_text_2` = '$post[sub_text_2]',
`sub_text_3` = '$post[sub_text_3]'
WHERE `ID` = $this->ID");
}
private function setWebPageImg($post)
{
$image = new Image($post);
$image->setLocation(__DIR__."/../../public/images/uploads");
$image->setSize(100, 1000000);
$image->setDimension(2000, 2000);
foreach($post as $key => $value)
{
if($image[$key])
{
$upload = $image->upload();
if(!$upload)
echo $image["error"];
$basis = $image->getFullPath();
$imgType = strrev(substr(strrev($basis), 0, strpos(strrev($basis), ".") + 1));
$result = Connection::query("UPDATE `Q_PAGES` SET
`$key` = "."'/images/uploads/".$image->getName().$imgType.
"' WHERE `ID` = '$this->ID'");
}
}
}
} | mit |
ishandutta2007/test | public/js/ace/lib/ace/mode/behaviour/xml.js | 3701 | /* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Chris Spencer <chris.ag.spencer AT googlemail DOT com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define(function(require, exports, module) {
var oop = require("../../lib/oop");
var Behaviour = require("../behaviour").Behaviour;
var CstyleBehaviour = require("./cstyle").CstyleBehaviour;
var XmlBehaviour = function () {
this.inherit(CstyleBehaviour, ["string_dquotes"]); // Get string behaviour
this.add("brackets", "insertion", function (state, action, editor, session, text) {
if (text == '<') {
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "") {
return false;
} else {
return {
text: '<>',
selection: [1, 1]
}
}
} else if (text == '>') {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == '>') { // need some kind of matching check here
return {
text: '',
selection: [1, 1]
}
}
} else if (text == "\n") {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChars = line.substring(cursor.column, cursor.column + 2);
if (rightChars == '</') {
var indent = this.$getIndent(session.doc.getLine(cursor.row)) + session.getTabString();
var next_indent = this.$getIndent(session.doc.getLine(cursor.row));
return {
text: '\n' + indent + '\n' + next_indent,
selection: [1, indent.length, 1, indent.length]
}
}
}
});
}
oop.inherits(XmlBehaviour, Behaviour);
exports.XmlBehaviour = XmlBehaviour;
}); | mit |
keen/explorer | src/components/VisualizationPlaceholder/VisualizationPlaceholder.styles.ts | 661 | import styled from 'styled-components';
import { colors } from '@keen.io/colors';
export const Container = styled.div`
position: relative;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
width: 100%;
height: 360px;
`;
type TextProps = {
color?: string;
};
export const Text = styled.div<TextProps>`
font-family: 'Gangster Grotesk Regular', sans-serif;
font-size: 20px;
line-height: 24px;
color: ${(props) => (props.color ? props.color : colors.green[400])};
`;
export const ButtonWrapper = styled.div`
margin-top: 20px;
`;
export const LoaderWrapper = styled.div`
margin-bottom: 10px;
`;
| mit |
muhbalhester/comex-app | node_modules/async/timeout.js | 2058 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = timeout;
var _initialParams = require('./internal/initialParams');
var _initialParams2 = _interopRequireDefault(_initialParams);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Sets a time limit on an asynchronous function. If the function does not call
* its callback within the specified milliseconds, it will be called with a
* timeout error. The code property for the error object will be `'ETIMEDOUT'`.
*
* @name timeout
* @static
* @memberOf module:Utils
* @method
* @category Util
* @param {Function} asyncFn - The asynchronous function you want to set the
* time limit.
* @param {number} milliseconds - The specified time limit.
* @param {*} [info] - Any variable you want attached (`string`, `object`, etc)
* to timeout Error for more information..
* @returns {Function} Returns a wrapped function that can be used with any of
* the control flow functions.
* @example
*
* async.timeout(function(callback) {
* doAsyncTask(callback);
* }, 1000);
*/
function timeout(asyncFn, milliseconds, info) {
var originalCallback, timer;
var timedOut = false;
function injectedCallback() {
if (!timedOut) {
originalCallback.apply(null, arguments);
clearTimeout(timer);
}
}
function timeoutCallback() {
var name = asyncFn.name || 'anonymous';
var error = new Error('Callback function "' + name + '" timed out.');
error.code = 'ETIMEDOUT';
if (info) {
error.info = info;
}
timedOut = true;
originalCallback(error);
}
return (0, _initialParams2.default)(function (args, origCallback) {
originalCallback = origCallback;
// setup timer and call original function
timer = setTimeout(timeoutCallback, milliseconds);
asyncFn.apply(null, args.concat(injectedCallback));
});
}
module.exports = exports['default'];
| mit |
dflynn15/flomo | server/config/env/test.js | 134 | 'use strict';
module.exports = {
db: 'mongodb://localhost/flomo-test',
port: 3001,
app: {
name: 'Flomo'
}
};
| mit |
banchawaipea/sys | application/views/home.php | 6116 |
<main class=bs-docs-masthead id=content tabindex=-1 >
<div class=container>
<span class="bs-docs-booticon bs-docs-booticon-lg bs-docs-booticon-outline">WD</span>
<p class=lead>เราคือมืออาชีพในงานสำรวจ จัดทำแผนที่สำรวจทางดาวเทียม รังวัดสอบเขต</p>
<p class=lead> <a href=# class="btn btn-outline-inverse btn-lg" onclick='ga("send","event","Jumbotron actions","Download","Download 3.3.7")'>Portfolio</a> </p>
<p class=version>Waipia Development Company Limited</p>
</main>
<div class=bs-docs-featurette>
<div class=container>
<h2 class=bs-docs-featurette-title>เกี่ยวกับเรา</h2>
<p class=lead>เป็นบริษัทรับเหมาก่อสร้างที่ให้บริการด้าน สถาปัตยกรรม , วิศวกรรม , ควบคุมงานก่อสร้าง , สำรวจ ,ที่ปรึกษาโครงการโดยมีกลุ่มบุคลากรที่มีความเชี่ยวชาญและมีประสบการณ์ในสายงานโดยตรง</p>
<hr class=half-rule>
<div class=row>
<div class=col-sm-4> <img alt="Sass and Less support" src=<?php echo base_url('assets/img/worker.png');?> class=homepage-grid-icon>
<h3>รับเหมาก่อสร้าง</h3>
<p>บริษัท ไวเปีย ดีเวลลอปเม้นท์ จำกัด เป็นบริษัทรับเหมาก่อสร้าง ที่ให้บริการด้านวิชาชีพในการรับเหมาก่อสร้าง โดยบุคลากรหลักที่มีความรู้ ประสบการณ์และความชำนาญ</p>
</div>
<div class=col-sm-4> <img alt="Responsive across devices" src=<?php echo base_url('assets/img/compass.png');?> class=homepage-grid-icon>
<h3>ออกแบบ</h3>
<p>เราออกแบบและควบคุมงานก่อสร้าง ให้มีมาตราฐานสามารถแข่งขันได้ รวมทั้งยังนำเทคโนโลยีใหม่ๆ มาพัฒนาระบบและเทคนิคการทำงานตลาดเวลา</p>
</div>
<div class=col-sm-4> <img alt=Components src=<?php echo base_url('assets/img/location.png');?> class=homepage-grid-icon>
<h3>งานรังวัด</h3>
<p>บริษัท ไวเปีย ดีเวลลอปเม้นท์ จำกัด บริการงานรังวัดเอกชน สอบเขต แบ่งแยก รวมโฉนด สำรวจทำแผนที่เพื่อการออกแบบ คำนวนปริมาตร วางตำแหน่งเสาเข็ม วางผังจัดสรร รังวัดด้วยดาวเทียม</p>
</div>
</div>
<hr class=half-rule>
<p class=lead>รับเหมาก่อสร้าง โดยบริษัทรับเหมาก่อสร้างมืออาชีพ</p> <a href=# class="btn btn-outline btn-lg">CONTACT</a> </div>
</div>
<!--<div class="bs-docs-featurette">
<div class="container">
<h2 class="bs-docs-featurette-title">Official Bootstrap Themes</h2>
<p class="lead">
Take Bootstrap to the next level with official premium themes. Each theme is its own toolkit featuring all of Bootstrap, brand new components and plugins, full docs, build tools, and more.
</p>
<p class="lead">
<a href="https://themes.getbootstrap.com" class="btn btn-outline btn-lg">Browse themes</a>
</p>
<img class="img-responsive" src="/assets/img/bs-themes.png" alt="Bootstrap Themes" width="1024" height="388" style="margin-left: auto; margin-right: auto;">
</div>
</div>-->
<div class=bs-docs-featurette>
<div class=container>
<h2 class=bs-docs-featurette-title>Portfolio</h2>
<p class=lead>ผลงานของบริษัท ไวเปียดีเวลลอปเม้นท์ จำกัด ทั้งงานก่อสร้างและงานสำรวจ</p>
<hr class=half-rule>
<div class="row bs-docs-featured-sites">
<div class="col-xs-6 col-sm-3">
<a href=# target=_blank title=Lyft> <img alt=Lyft src=https://scontent.fbkk5-3.fna.fbcdn.net/v/t1.0-9/21742955_465081453878289_3874484140068739635_n.jpg?oh=9062049e1a9c5526813c7977aafd97a0&oe=5A17757D class=img-responsive> </a>
</div>
<div class="col-xs-6 col-sm-3">
<a href=# target=_blank title=Vogue> <img alt=Vogue src=https://scontent.fbkk5-3.fna.fbcdn.net/v/t1.0-9/21369629_460334161019685_6534091094252126445_n.jpg?oh=a3a9c6cf8a90449a8327dfb45bbc49c6&oe=5A609EB9 class=img-responsive> </a>
</div>
<div class="col-xs-6 col-sm-3">
<a href=# target=_blank title="Riot Design"> <img alt="Riot Design" src=https://scontent.fbkk5-3.fna.fbcdn.net/v/t1.0-9/16508625_360106674375768_8590761181424186928_n.jpg?oh=57135c790e14e6e619e0ff1dab844127&oe=5A5BCB66 class=img-responsive> </a>
</div>
<div class="col-xs-6 col-sm-3">
<a href=# target=_blank title=Newsweek> <img alt=Newsweek src=https://scontent.fbkk5-3.fna.fbcdn.net/v/t1.0-9/15267735_327741997612236_2190241023769609601_n.jpg?oh=b41b56b233edde759571a7c202316a07&oe=5A1239CE class=img-responsive> </a>
</div>
</div>
<hr class=half-rule>
<p class="lead">มีผลงานของทางบริษัทอีกมามาย</p><a href=# class="btn btn-outline btn-lg">More</a> </div>
</div>
| mit |
tivvit/aerospike-client-mock-python | AerospikeClientMock/__init__.py | 114 | from .AerospikeClientMock import AerospikeClientMock
from .AerospikePredicatesMock import AerospikePredicatesMock
| mit |
karolikl/OctopusDeployLab | OctopusDeployLab/Controllers/HomeController.cs | 500 | using System.Web.Mvc;
namespace OctopusDeployLab.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
} | mit |
Mick3y16/LAPR2 | src/eventoscientificos/model/state/submissao/SubmissaoRevistaState.java | 3939 | package eventoscientificos.model.state.submissao;
import eventoscientificos.model.Submissao;
/**
* Representa uma instância de SubmissaoRevistaState através de uma submissão.
*
* @author G01
*/
public class SubmissaoRevistaState implements SubmissaoState {
/**
* Submissao que adota o estado.
*/
private Submissao submissao;
/**
* Constroi uma instância de SubmissaoRevistaState recebendo uma Submissao
*
* @param submissao Submissao que adota o estado.
*/
public SubmissaoRevistaState(Submissao submissao) {
this.submissao = submissao;
}
/**
* Modifica o estado da submissão para o estado Submissão Criada
*
* @return Falso, não deve ser possível mudar de Revista para Criada.
*/
@Override
public boolean setCriada() {
return false;
}
/**
* Modifica o estado da submissão para o estado Submissão Em Submissão.
*
* @return Falso, não deve ser possível mudar de Revista para EmSubmissao.
*/
@Override
public boolean setEmSubmissao() {
return false;
}
/**
* Modifica o estado da submissão para o estado Submissão EmLicitação.
*
* @return Falso, não deve ser possível mudar de Revista para Em Licitação.
*/
@Override
public boolean setEmLicitacao() {
return false;
}
/**
* Modifica o estado da submissão para o estado Submissão Em Revisão.
*
* @return Falso, não deve ser possível mudar de Revista para EmRevisão.
*/
@Override
public boolean setEmRevisao() {
return false;
}
/**
* Modifica o estado da submissão para o estado Submissão Revista
*
* @return Verdadeiro, a submissão encontra-se neste estado.
*/
@Override
public boolean setRevista() {
return true;
}
/**
* Modifica o estado da submissão para o estado Submissão Aceite.
*
* @return Verdadeiro se for possivel alterar o estado para Aceite e
* falso caso não seja.
*/
@Override
public boolean setAceite() {
if (validarEstado()) {
this.submissao.setEstado(new SubmissaoAceiteState(this.submissao));
return true;
}
return false;
}
/**
* Modifica o estado da submissão para o estado Submissão Rejeitada.
*
* @return Verdadeiro se for possivel alterar o estado para Rejeitada e
* falso caso não seja.
*/
@Override
public boolean setRejeitada() {
if (validarEstado()) {
this.submissao.setEstado(new SubmissaoRejeitadaState(this.submissao));
return true;
}
return false;
}
/**
* Modifica o estado da submissão para o estado Submissão EmCameraReady.
*
* @return Falso, não deve ser possível mudar de revista para EmCameraReady.
*/
@Override
public boolean setEmCameraReady() {
return false;
}
/**
* Modifica o estado da submissão para o estado Submissão SemArtigoFinal.
*
* @return Falso, não deve ser possível mudar de Revista para SemArtigoFinal.
*/
@Override
public boolean setSemArtigoFinal() {
return false;
}
/**
* Modifica o estado da submissão para o estado Submissão Removida.
*
* @return Verdadeiro, deve ser possível mudar de Revista para Removida.
*/
@Override
public boolean setRemovida() {
submissao.setEstado(new SubmissaoRemovidaState(submissao));
return true;
}
/**
* valida se cumpre as condicoes necessarias para efetuar a mudanca de
* estado pretendida
*
* @return verdadeiro se poder passar de estado e falso se nao cumprir as
* condicoes necessarias de mudanca de estado
*/
@Override
public boolean validarEstado() {
return true;
}
}
| mit |
BD-RBC/workflow | example/views/test/index.php | 2093 | <?php
/* @var $this yii\web\View */
use workflow\models\Arc;
use workflow\models\Place;
$this->title = 'workflow';
?>
<div class="site-index">
<div id="demo"></div>
<nav class="navbar navbar-default navbar-fixed-bottom" role="navigation">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="<?= \yii\helpers\Url::to(['move-token'])?>">
Move Token
</a>
</div>
</div>
</nav>
</div>
<?php
$nodes = '';
$lines = '';
$nodeWidth = 0;
$height = 0;
$width = 0;
foreach ($workflow['node'] as $index => $node) {
$nodeWidth++;
foreach ($node as $floor => $point) {
$top = 30 + (100 * (int)$floor);
$height = $top + 520 ;
$left = (50 * $nodeWidth);
$width = $left + 200;
if ($point instanceof Place) {
$type = 'node';
if ($point->type == Place::PLACE_TYPE_START) {
$type = "start";
} elseif ($point->type == Place::PLACE_TYPE_END) {
$type = "end";
}
if (isset($tokens[$point->id])) {
$type = "state";
}
$nodes .= "place_node_" . $point->id . ": {width: 100, height: 30, name: '" . $point->name . "', type: '" . $type . "', left: " . $left . ", top: " . $top . "},";
} else {
$nodes .= "transition_node_" . $point->id . ": {width: 100, height: 30, name: '" . $point->name . "', type: 'task', left: " . $left . ", top: " . $top . "},";
}
}
}
foreach ($workflow['line'] as $line) {
if ($line->direction === Arc::DIRECTION_TYPE_IN) {
$lines .= "line_" . $line->id . ": {marked: false, name: '" . $line->name . "', type: 'sl', from: 'place_node_" . $line->place->id . "', to: 'transition_node_" . $line->transition->id . "'},";
} else {
$lines .= "line_" . $line->id . ": {marked: false, name: '" . $line->name . "', type: 'sl', from: 'transition_node_" . $line->transition->id . "', to: 'place_node_" . $line->place->id . "'},";
}
}
$this->registerJs('
var demo = $(\'#demo\').createGooFlow({
//id: "demo"
height: ' . $height . ',
width: ' . $width . '
});
demo.loadData({
lines: {
' . $lines .'
},
nodes: {
' . $nodes . '
}
});
', \yii\web\View::POS_END);
| mit |
Zifah/udacity-fsnd-project-3.1 | news_reports.py | 2458 | # Python 2.7.12 or Higher
""" Logs Analysis """
import psycopg2
DBNAME = "news"
POPULAR_ARTICLES_QUERY = """
select a.title, count(l.id) as views
from articles a left join log l
on concat('/article/',a.slug) = l.path
group by a.title
order by views desc
limit 3;
"""
AUTHOR_RANKING_QUERY = """
select au.name, count(l.id) as views
from authors au
left join articles ar on ar.author = au.id
left join log l on concat('/article/',ar.slug) = l.path
group by au.id
order by views desc;
"""
ERRONEOUS_DAY_QUERY = """
select to_char(error_summary.date, 'Mon DD, YYYY') date,
round((error_size::float * 100/all_size)::numeric, 2) percent
from (select time::date as date, count(id) error_size
from log
where status != '200 OK'
group by date) as error_summary
left join (select time::date date, count(id) all_size
from log
group by date) as all_summary
on error_summary.date = all_summary.date
where error_size::float * 100/all_size > 1
order by percent desc;
"""
def show_popular_articles():
"""Print out the top 3 articles by popularity among website visitors"""
cursor = DB_CONNECTION.cursor()
cursor.execute(POPULAR_ARTICLES_QUERY)
results = cursor.fetchall()
print("POPULAR ARTICLES")
print("-------------------------------")
for title, views in results:
print("%s - %s views" % (title, views))
print("\r\n")
def show_authors_by_popularity():
"""List out all authors based on popularity
(how many visits their articles have cummulatively)"""
cursor = DB_CONNECTION.cursor()
cursor.execute(AUTHOR_RANKING_QUERY)
results = cursor.fetchall()
print("POPULAR AUTHORS")
print("-------------------------------")
for name, views in results:
print("%s - %s views" % (name, views))
print("\r\n")
def show_high_error_days():
"""Print out any days where HTTP error responses
exceed 1% of all requests, along with the percentage"""
cursor = DB_CONNECTION.cursor()
cursor.execute(ERRONEOUS_DAY_QUERY)
results = cursor.fetchall()
print("HIGH ERROR DAYS")
print("-------------------------------")
for date, percent in results:
print("%s - %s%% errors" % (date, percent))
print("\r\n")
if __name__ == '__main__':
# Print out all the statistics
DB_CONNECTION = psycopg2.connect(database=DBNAME)
show_popular_articles()
show_authors_by_popularity()
show_high_error_days()
DB_CONNECTION.close()
| mit |
luismiguens/parcelaja | src/AppBundle/Form/TagencyType.php | 3605 | <?php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Vich\UploaderBundle\Form\Type\VichImageType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
class TagencyType extends AbstractType {
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('fagencyname')
->add('ffiscalname')
->add('ftaxidnumber')
->add('faddress', TextareaType::class, array(
'attr' => array('class' => 'form-control'),
))
->add('taxAddress', TextareaType::class, array(
'attr' => array('class' => 'form-control'),
))
// ->add('fpostalcode1')
// ->add('fpostalcode2')
// ->add('flocation')
->add('femail1', TextType::class, array(
'required' => true,
))
->add('femail2')
->add('fcontactperson')
->add('ftelephone')
->add('fmobilephone')
->add('fwebsite')
->add('fbank')
->add('fiban')
->add('fbicswift')
->add('frnavt')
->add('fpaymethodid', TextType::class, array(
'disabled' => true,))
//FP
->add('fpaymethodfees', CollectionType::class, array(
'entry_type' => TpaymethodfeeType::class,
'label' =>' ',
'by_reference' => true,
'entry_options' => array('label' => false),
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
'attr' => array(
'class' => 'fee-selector',
),
))
//->add('flogo')
->add('imageFile', VichImageType::class, [
'required' => false,
])
->add('fstate', ChoiceType::class
, array(
'choices' => array(
'Activo' => true,
'Inactivo' => false,
)))->add('fuseonlyshoptax', ChoiceType::class
, array(
'choices' => array(
'Activo' => true,
'Inactivo' => false,
)))
->add('subgroup', null, ['required' => true])
->add('broker')->add('invoiceFrequency', ChoiceType::class
, array(
'choices' => array(
'Diário' => 1,
'Semanal' => 2,
'Mensal' => 3,
)));
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver) {
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Tagency'
));
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix() {
return 'appbundle_tagency';
}
}
| mit |
Catorpilor/LeetCode | 842_split_array_into_fibonacci_sequence/seq_test.go | 1323 | package seq
import (
"reflect"
"strconv"
"strings"
"testing"
)
func TestSplitIntoFib(t *testing.T) {
st := []struct {
name string
s string
exp []int
}{
{"len(s)=1", "2", []int{}},
{"len(s)=2", "12", []int{}},
{"valid len(s)=3", "123", []int{1, 2, 3}},
{"invalid with leading 0", "011", []int{0, 1, 1}},
{"valid with 0", "101", []int{1, 0, 1}},
{"testcase1", "112358130", []int{}},
{"testcase2", "11235813", []int{1, 1, 2, 3, 5, 8, 13}},
{"failed1", "539834657215398346785398346991079669377161950407626991734534318677529701785098211336528511", []int{}},
{"faield2", `3611537383985343591834441270352104793375145479938855071433500231900737525076071514982402115895535257195564161509167334647108949738176284385285234123461518508746752631120827113919550237703163294909`, []int{}},
}
for _, tt := range st {
t.Run(tt.name, func(t *testing.T) {
out := splitIntoFib(tt.s)
if !reflect.DeepEqual(tt.exp, out) {
t.Fatalf("with input s:%s wanted %v but got %v", tt.s, tt.exp, out)
}
genStr := gen(out)
if tt.s != genStr {
t.Fatalf("origin str: %s and genrated str: %s", tt.s, genStr)
}
t.Log("pass")
})
}
}
func gen(fibs []int) string {
var sb strings.Builder
for _, v := range fibs {
sb.WriteString(strconv.FormatInt(int64(v), 10))
}
return sb.String()
}
| mit |
rafamvc/Refinery-Banner | vendor/plugins/news/app/controllers/admin/news_items_controller.rb | 112 | class Admin::NewsItemsController < Admin::BaseController
crudify :news_item, :order => "created_at DESC"
end | mit |
mekentosj/ling | node_modules/cucumber/spec/cucumber/support_code/step_definition_snippet_builder_syntax_spec.js | 4534 | require('../../support/spec_helper');
describe('Cucumber.SupportCode.StepDefinitionSnippetBuilderSyntax', function () {
var Cucumber = requireLib('cucumber');
var Syntax = Cucumber.SupportCode.StepDefinitionSnippetBuilderSyntax;
var stepDefinitionEndComment = 'express the regexp above with the code you wish you had';
function testBaseSyntax(syntax) {
describe('getStepDefinitionDocString()', function () {
it('returns "string"', function () {
expect(syntax.getStepDefinitionDocString()).toBe('string');
});
});
describe('getStepDefinitionDataTable()', function () {
it('returns "table"', function () {
expect(syntax.getStepDefinitionDataTable()).toBe('table');
});
});
describe('getStepDefinitionCallback()', function () {
it('returns "callback"', function () {
expect(syntax.getStepDefinitionCallback()).toBe('callback');
});
});
describe('getPatternStart()', function () {
it('returns "/^"', function () {
expect(syntax.getPatternStart()).toBe('/^');
});
});
describe('getPatternEnd()', function () {
it('returns "$/"', function () {
expect(syntax.getPatternEnd()).toBe('$/');
});
});
describe('getContextStepDefinitionFunctionName()', function () {
it('returns "Given"', function () {
expect(syntax.getContextStepDefinitionFunctionName()).toBe('Given');
});
});
describe('getEventStepDefinitionFunctionName()', function () {
it('returns "When"', function () {
expect(syntax.getEventStepDefinitionFunctionName()).toBe('When');
});
});
describe('getOutcomeStepDefinitionFunctionName()', function () {
it('returns "Then"', function () {
expect(syntax.getOutcomeStepDefinitionFunctionName()).toBe('Then');
});
});
describe('getNumberMatchingGroup()', function () {
it('returns (\\d+)', function () {
expect(syntax.getNumberMatchingGroup()).toBe('(\\d+)');
});
});
describe('getQuotedStringMatchingGroup()', function () {
it('returns "([^"]*)"', function () {
expect(syntax.getQuotedStringMatchingGroup()).toBe('"([^"]*)"');
});
});
describe('getFunctionParameterSeparator()', function () {
it('returns ", "', function () {
expect(syntax.getFunctionParameterSeparator()).toBe(', ');
});
});
describe('getStepDefinitionEndComment()', function () {
it('returns "' + stepDefinitionEndComment + '"', function () {
expect(syntax.getStepDefinitionEndComment()).toBe(stepDefinitionEndComment);
});
});
}
describe('JavaScript', function () {
var syntax = new Syntax.JavaScript();
testBaseSyntax(syntax);
describe('getStepDefinitionStart()', function () {
it('returns "this."', function () {
expect(syntax.getStepDefinitionStart()).toBe('this.');
});
});
describe('getStepDefinitionInner1()', function () {
it('returns "("', function () {
expect(syntax.getStepDefinitionInner1()).toBe('(');
});
});
describe('getStepDefinitionInner2()', function () {
it('returns ", function ("', function () {
expect(syntax.getStepDefinitionInner2()).toBe(', function (');
});
});
describe('getStepDefinitionEnd()', function () {
var str = ") {\n // " + stepDefinitionEndComment + "\n callback.pending();\n});\n";
it('returns "' + str + '"', function () {
expect(syntax.getStepDefinitionEnd()).toBe(str);
});
});
});
describe('CoffeeScipt', function () {
var syntax = new Syntax.CoffeeScript();
testBaseSyntax(syntax);
describe('getStepDefinitionStart()', function () {
it('returns "@"', function () {
expect(syntax.getStepDefinitionStart()).toBe('@');
});
});
describe('getStepDefinitioninner1()', function () {
it('returns " "', function () {
expect(syntax.getStepDefinitionInner1()).toBe(' ');
});
});
describe('getStepDefinitionInner2()', function () {
it('returns ", ("', function () {
expect(syntax.getStepDefinitionInner2()).toBe(', (');
});
});
describe('getStepDefinitionEnd()', function () {
var str = ") ->\n # " + stepDefinitionEndComment + "\n callback.pending()\n";
it('returns "' + str + '"', function () {
expect(syntax.getStepDefinitionEnd()).toBe(str);
});
});
});
});
| mit |
CRTX/Curl | src/Curl.php | 1674 | <?php
/*
* This file is part of the CRTX\Curl package.
*
* (c) Christian Ruiz <ruiz.d.christian@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace CRTX\Curl;
use InvalidArgumentException;
/**
* @author Christian Ruiz <ruiz.d.christian@gmail.com>
*/
class Curl implements CurlInterface
{
protected $curlHandle;
protected $optionList;
public function __construct($curlHandle, Array $optionList = array())
{
$this->curlHandle = $curlHandle;
$this->setOptions($optionList);
}
public function execute() : String
{
$this->resourceCheck($this->curlHandle);
$result = curl_exec($this->curlHandle);
if(!is_string($result)) {
return '';
}
return $result;
}
public function getError() : String
{
$errorNumber = curl_errno($this->curlHandle);
$message = curl_error($this->curlHandle);
return "cURL error $errorNumber: " . PHP_EOL . $message;
}
protected function setOptions(Array $optionList) : void
{
foreach($optionList as $optionName => $optionValue) {
curl_setopt($this->curlHandle, $optionName, $optionValue);
}
}
protected function resourceCheck($value) : void
{
if (!is_resource($value)) {
throw new InvalidArgumentException('Object Curl expects a curl_init(). Incorrect argument provided.');
}
}
public function __destruct()
{
if(is_resource($this->curlHandle)) {
curl_close($this->curlHandle);
}
}
}
| mit |
jenidarnold/racquetball | resources/views/pages/players/journal/opponent/create.blade.php | 2060 | @extends('pages.players.journal.opponent.layout')
@section('style')
<style type="text/css">
.starrr{
color: green;
font-size: 14pt;
}
.eval-header{
color:white;
font-weight: 500;
font-size: 14pt;
width:450px;
padding-left: 10px !important;
}
.opp-title{
font-weight:700;
font-size: 12pt;
}
.form-label{
font-weight:500;
padding-bottom: 10px;
}
</style>
@parent
@stop
@section('title')
<label class="player-sub-title">Create New Opponent Entry</label>
<label class="entry-date" style="float:right">Last Entry: 6/1/15</label>
@stop
@section('opponent-content')
<div>
{!! Form::open(array('class' =>'form-inline','role'=>'form', 'method'=>'POST', 'route' => array('opponent.evaluation.store', $player->player_id, $target_id, $entry)))!!}
<div class="row col-md-8">
<div class="form-group">
{!! Form::label('Opponent:','', array('class' =>'form-label opp-title', 'for' =>'ddlPlayer')) !!}
{!! Form::select('ddlPlayer', $players_list, null, array('class' => 'form-control', 'style' => 'width:200px' )) !!}
</div>
</div>
<div class="row col-md-8">
<div class="form-group">
{!! Form::label('Entry Title:','', array('class' =>'form-label opp-title', 'for' =>'entry_title')) !!}
{!! Form::text('entry_title','', array('class' =>'form-control', 'style' => 'width:400px')) !!}
</div>
</div>
<div class="row col-md-8">
<div class="form-group">
{!! Form::submit('Submit', array('class' =>'btn btn-sm btn-success', 'style' => 'font-style:italic; font-weight:bolder')) !!}
{!! Form::button('Reset', array('class' =>'btn btn-sm btn-warning', 'style' => 'font-style:italic; font-weight:bolder')) !!}
</div>
</div>
{!! Form::close() !!}
</div>
@stop
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#ddlPlayer').change(function(){
target_id = $('#ddlPlayer').val();
});
});
</script> | mit |
michaldubiel/BarberApp | src/Barber/Scripts/Controllers/datepickerController.js | 1368 | (function () {
'use strict';
angular
.module('barberApp')
.controller('DatepickerController', DatepickerController);
DatepickerController.$inject = ['$scope'];
function DatepickerController($scope) {
$scope.today = function () {
$scope.dt = new Date();
};
$scope.clear = function () {
$scope.dt = null;
};
// Disable weekend selection
$scope.disabled = function (date, mode) {
return mode === 'day' && (date.getDay() === 0 || date.getDay() === 6);
};
$scope.toggleMin = function () {
$scope.minDate = $scope.minDate ? null : new Date();
};
$scope.toggleMin();
$scope.maxDate = new Date(2099, 12, 31);
$scope.open = function () {
$scope.popup.opened = true;
};
$scope.setDate = function (year, month, day) {
$scope.dt = new Date(year, month, day);
};
$scope.dateOptions = {
formatYear: 'yy',
startingDay: 1
};
$scope.formats = ['yyyy-mm-dd', 'dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
$scope.format = $scope.formats[0];
$scope.altInputFormats = ['M!/d!/yyyy'];
$scope.popup = {
opened: false
};
}
})(); | mit |
HeavyWombat/spruce | vendor/gopkg.in/yaml.v3/scannerc.go | 87455 | //
// Copyright (c) 2011-2019 Canonical Ltd
// Copyright (c) 2006-2010 Kirill Simonov
//
// 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 yaml
import (
"bytes"
"fmt"
)
// Introduction
// ************
//
// The following notes assume that you are familiar with the YAML specification
// (http://yaml.org/spec/1.2/spec.html). We mostly follow it, although in
// some cases we are less restrictive that it requires.
//
// The process of transforming a YAML stream into a sequence of events is
// divided on two steps: Scanning and Parsing.
//
// The Scanner transforms the input stream into a sequence of tokens, while the
// parser transform the sequence of tokens produced by the Scanner into a
// sequence of parsing events.
//
// The Scanner is rather clever and complicated. The Parser, on the contrary,
// is a straightforward implementation of a recursive-descendant parser (or,
// LL(1) parser, as it is usually called).
//
// Actually there are two issues of Scanning that might be called "clever", the
// rest is quite straightforward. The issues are "block collection start" and
// "simple keys". Both issues are explained below in details.
//
// Here the Scanning step is explained and implemented. We start with the list
// of all the tokens produced by the Scanner together with short descriptions.
//
// Now, tokens:
//
// STREAM-START(encoding) # The stream start.
// STREAM-END # The stream end.
// VERSION-DIRECTIVE(major,minor) # The '%YAML' directive.
// TAG-DIRECTIVE(handle,prefix) # The '%TAG' directive.
// DOCUMENT-START # '---'
// DOCUMENT-END # '...'
// BLOCK-SEQUENCE-START # Indentation increase denoting a block
// BLOCK-MAPPING-START # sequence or a block mapping.
// BLOCK-END # Indentation decrease.
// FLOW-SEQUENCE-START # '['
// FLOW-SEQUENCE-END # ']'
// BLOCK-SEQUENCE-START # '{'
// BLOCK-SEQUENCE-END # '}'
// BLOCK-ENTRY # '-'
// FLOW-ENTRY # ','
// KEY # '?' or nothing (simple keys).
// VALUE # ':'
// ALIAS(anchor) # '*anchor'
// ANCHOR(anchor) # '&anchor'
// TAG(handle,suffix) # '!handle!suffix'
// SCALAR(value,style) # A scalar.
//
// The following two tokens are "virtual" tokens denoting the beginning and the
// end of the stream:
//
// STREAM-START(encoding)
// STREAM-END
//
// We pass the information about the input stream encoding with the
// STREAM-START token.
//
// The next two tokens are responsible for tags:
//
// VERSION-DIRECTIVE(major,minor)
// TAG-DIRECTIVE(handle,prefix)
//
// Example:
//
// %YAML 1.1
// %TAG ! !foo
// %TAG !yaml! tag:yaml.org,2002:
// ---
//
// The correspoding sequence of tokens:
//
// STREAM-START(utf-8)
// VERSION-DIRECTIVE(1,1)
// TAG-DIRECTIVE("!","!foo")
// TAG-DIRECTIVE("!yaml","tag:yaml.org,2002:")
// DOCUMENT-START
// STREAM-END
//
// Note that the VERSION-DIRECTIVE and TAG-DIRECTIVE tokens occupy a whole
// line.
//
// The document start and end indicators are represented by:
//
// DOCUMENT-START
// DOCUMENT-END
//
// Note that if a YAML stream contains an implicit document (without '---'
// and '...' indicators), no DOCUMENT-START and DOCUMENT-END tokens will be
// produced.
//
// In the following examples, we present whole documents together with the
// produced tokens.
//
// 1. An implicit document:
//
// 'a scalar'
//
// Tokens:
//
// STREAM-START(utf-8)
// SCALAR("a scalar",single-quoted)
// STREAM-END
//
// 2. An explicit document:
//
// ---
// 'a scalar'
// ...
//
// Tokens:
//
// STREAM-START(utf-8)
// DOCUMENT-START
// SCALAR("a scalar",single-quoted)
// DOCUMENT-END
// STREAM-END
//
// 3. Several documents in a stream:
//
// 'a scalar'
// ---
// 'another scalar'
// ---
// 'yet another scalar'
//
// Tokens:
//
// STREAM-START(utf-8)
// SCALAR("a scalar",single-quoted)
// DOCUMENT-START
// SCALAR("another scalar",single-quoted)
// DOCUMENT-START
// SCALAR("yet another scalar",single-quoted)
// STREAM-END
//
// We have already introduced the SCALAR token above. The following tokens are
// used to describe aliases, anchors, tag, and scalars:
//
// ALIAS(anchor)
// ANCHOR(anchor)
// TAG(handle,suffix)
// SCALAR(value,style)
//
// The following series of examples illustrate the usage of these tokens:
//
// 1. A recursive sequence:
//
// &A [ *A ]
//
// Tokens:
//
// STREAM-START(utf-8)
// ANCHOR("A")
// FLOW-SEQUENCE-START
// ALIAS("A")
// FLOW-SEQUENCE-END
// STREAM-END
//
// 2. A tagged scalar:
//
// !!float "3.14" # A good approximation.
//
// Tokens:
//
// STREAM-START(utf-8)
// TAG("!!","float")
// SCALAR("3.14",double-quoted)
// STREAM-END
//
// 3. Various scalar styles:
//
// --- # Implicit empty plain scalars do not produce tokens.
// --- a plain scalar
// --- 'a single-quoted scalar'
// --- "a double-quoted scalar"
// --- |-
// a literal scalar
// --- >-
// a folded
// scalar
//
// Tokens:
//
// STREAM-START(utf-8)
// DOCUMENT-START
// DOCUMENT-START
// SCALAR("a plain scalar",plain)
// DOCUMENT-START
// SCALAR("a single-quoted scalar",single-quoted)
// DOCUMENT-START
// SCALAR("a double-quoted scalar",double-quoted)
// DOCUMENT-START
// SCALAR("a literal scalar",literal)
// DOCUMENT-START
// SCALAR("a folded scalar",folded)
// STREAM-END
//
// Now it's time to review collection-related tokens. We will start with
// flow collections:
//
// FLOW-SEQUENCE-START
// FLOW-SEQUENCE-END
// FLOW-MAPPING-START
// FLOW-MAPPING-END
// FLOW-ENTRY
// KEY
// VALUE
//
// The tokens FLOW-SEQUENCE-START, FLOW-SEQUENCE-END, FLOW-MAPPING-START, and
// FLOW-MAPPING-END represent the indicators '[', ']', '{', and '}'
// correspondingly. FLOW-ENTRY represent the ',' indicator. Finally the
// indicators '?' and ':', which are used for denoting mapping keys and values,
// are represented by the KEY and VALUE tokens.
//
// The following examples show flow collections:
//
// 1. A flow sequence:
//
// [item 1, item 2, item 3]
//
// Tokens:
//
// STREAM-START(utf-8)
// FLOW-SEQUENCE-START
// SCALAR("item 1",plain)
// FLOW-ENTRY
// SCALAR("item 2",plain)
// FLOW-ENTRY
// SCALAR("item 3",plain)
// FLOW-SEQUENCE-END
// STREAM-END
//
// 2. A flow mapping:
//
// {
// a simple key: a value, # Note that the KEY token is produced.
// ? a complex key: another value,
// }
//
// Tokens:
//
// STREAM-START(utf-8)
// FLOW-MAPPING-START
// KEY
// SCALAR("a simple key",plain)
// VALUE
// SCALAR("a value",plain)
// FLOW-ENTRY
// KEY
// SCALAR("a complex key",plain)
// VALUE
// SCALAR("another value",plain)
// FLOW-ENTRY
// FLOW-MAPPING-END
// STREAM-END
//
// A simple key is a key which is not denoted by the '?' indicator. Note that
// the Scanner still produce the KEY token whenever it encounters a simple key.
//
// For scanning block collections, the following tokens are used (note that we
// repeat KEY and VALUE here):
//
// BLOCK-SEQUENCE-START
// BLOCK-MAPPING-START
// BLOCK-END
// BLOCK-ENTRY
// KEY
// VALUE
//
// The tokens BLOCK-SEQUENCE-START and BLOCK-MAPPING-START denote indentation
// increase that precedes a block collection (cf. the INDENT token in Python).
// The token BLOCK-END denote indentation decrease that ends a block collection
// (cf. the DEDENT token in Python). However YAML has some syntax pecularities
// that makes detections of these tokens more complex.
//
// The tokens BLOCK-ENTRY, KEY, and VALUE are used to represent the indicators
// '-', '?', and ':' correspondingly.
//
// The following examples show how the tokens BLOCK-SEQUENCE-START,
// BLOCK-MAPPING-START, and BLOCK-END are emitted by the Scanner:
//
// 1. Block sequences:
//
// - item 1
// - item 2
// -
// - item 3.1
// - item 3.2
// -
// key 1: value 1
// key 2: value 2
//
// Tokens:
//
// STREAM-START(utf-8)
// BLOCK-SEQUENCE-START
// BLOCK-ENTRY
// SCALAR("item 1",plain)
// BLOCK-ENTRY
// SCALAR("item 2",plain)
// BLOCK-ENTRY
// BLOCK-SEQUENCE-START
// BLOCK-ENTRY
// SCALAR("item 3.1",plain)
// BLOCK-ENTRY
// SCALAR("item 3.2",plain)
// BLOCK-END
// BLOCK-ENTRY
// BLOCK-MAPPING-START
// KEY
// SCALAR("key 1",plain)
// VALUE
// SCALAR("value 1",plain)
// KEY
// SCALAR("key 2",plain)
// VALUE
// SCALAR("value 2",plain)
// BLOCK-END
// BLOCK-END
// STREAM-END
//
// 2. Block mappings:
//
// a simple key: a value # The KEY token is produced here.
// ? a complex key
// : another value
// a mapping:
// key 1: value 1
// key 2: value 2
// a sequence:
// - item 1
// - item 2
//
// Tokens:
//
// STREAM-START(utf-8)
// BLOCK-MAPPING-START
// KEY
// SCALAR("a simple key",plain)
// VALUE
// SCALAR("a value",plain)
// KEY
// SCALAR("a complex key",plain)
// VALUE
// SCALAR("another value",plain)
// KEY
// SCALAR("a mapping",plain)
// BLOCK-MAPPING-START
// KEY
// SCALAR("key 1",plain)
// VALUE
// SCALAR("value 1",plain)
// KEY
// SCALAR("key 2",plain)
// VALUE
// SCALAR("value 2",plain)
// BLOCK-END
// KEY
// SCALAR("a sequence",plain)
// VALUE
// BLOCK-SEQUENCE-START
// BLOCK-ENTRY
// SCALAR("item 1",plain)
// BLOCK-ENTRY
// SCALAR("item 2",plain)
// BLOCK-END
// BLOCK-END
// STREAM-END
//
// YAML does not always require to start a new block collection from a new
// line. If the current line contains only '-', '?', and ':' indicators, a new
// block collection may start at the current line. The following examples
// illustrate this case:
//
// 1. Collections in a sequence:
//
// - - item 1
// - item 2
// - key 1: value 1
// key 2: value 2
// - ? complex key
// : complex value
//
// Tokens:
//
// STREAM-START(utf-8)
// BLOCK-SEQUENCE-START
// BLOCK-ENTRY
// BLOCK-SEQUENCE-START
// BLOCK-ENTRY
// SCALAR("item 1",plain)
// BLOCK-ENTRY
// SCALAR("item 2",plain)
// BLOCK-END
// BLOCK-ENTRY
// BLOCK-MAPPING-START
// KEY
// SCALAR("key 1",plain)
// VALUE
// SCALAR("value 1",plain)
// KEY
// SCALAR("key 2",plain)
// VALUE
// SCALAR("value 2",plain)
// BLOCK-END
// BLOCK-ENTRY
// BLOCK-MAPPING-START
// KEY
// SCALAR("complex key")
// VALUE
// SCALAR("complex value")
// BLOCK-END
// BLOCK-END
// STREAM-END
//
// 2. Collections in a mapping:
//
// ? a sequence
// : - item 1
// - item 2
// ? a mapping
// : key 1: value 1
// key 2: value 2
//
// Tokens:
//
// STREAM-START(utf-8)
// BLOCK-MAPPING-START
// KEY
// SCALAR("a sequence",plain)
// VALUE
// BLOCK-SEQUENCE-START
// BLOCK-ENTRY
// SCALAR("item 1",plain)
// BLOCK-ENTRY
// SCALAR("item 2",plain)
// BLOCK-END
// KEY
// SCALAR("a mapping",plain)
// VALUE
// BLOCK-MAPPING-START
// KEY
// SCALAR("key 1",plain)
// VALUE
// SCALAR("value 1",plain)
// KEY
// SCALAR("key 2",plain)
// VALUE
// SCALAR("value 2",plain)
// BLOCK-END
// BLOCK-END
// STREAM-END
//
// YAML also permits non-indented sequences if they are included into a block
// mapping. In this case, the token BLOCK-SEQUENCE-START is not produced:
//
// key:
// - item 1 # BLOCK-SEQUENCE-START is NOT produced here.
// - item 2
//
// Tokens:
//
// STREAM-START(utf-8)
// BLOCK-MAPPING-START
// KEY
// SCALAR("key",plain)
// VALUE
// BLOCK-ENTRY
// SCALAR("item 1",plain)
// BLOCK-ENTRY
// SCALAR("item 2",plain)
// BLOCK-END
//
// Ensure that the buffer contains the required number of characters.
// Return true on success, false on failure (reader error or memory error).
func cache(parser *yaml_parser_t, length int) bool {
// [Go] This was inlined: !cache(A, B) -> unread < B && !update(A, B)
return parser.unread >= length || yaml_parser_update_buffer(parser, length)
}
// Advance the buffer pointer.
func skip(parser *yaml_parser_t) {
if !is_blank(parser.buffer, parser.buffer_pos) {
parser.newlines = 0
}
parser.mark.index++
parser.mark.column++
parser.unread--
parser.buffer_pos += width(parser.buffer[parser.buffer_pos])
}
func skip_line(parser *yaml_parser_t) {
if is_crlf(parser.buffer, parser.buffer_pos) {
parser.mark.index += 2
parser.mark.column = 0
parser.mark.line++
parser.unread -= 2
parser.buffer_pos += 2
parser.newlines++
} else if is_break(parser.buffer, parser.buffer_pos) {
parser.mark.index++
parser.mark.column = 0
parser.mark.line++
parser.unread--
parser.buffer_pos += width(parser.buffer[parser.buffer_pos])
parser.newlines++
}
}
// Copy a character to a string buffer and advance pointers.
func read(parser *yaml_parser_t, s []byte) []byte {
if !is_blank(parser.buffer, parser.buffer_pos) {
parser.newlines = 0
}
w := width(parser.buffer[parser.buffer_pos])
if w == 0 {
panic("invalid character sequence")
}
if len(s) == 0 {
s = make([]byte, 0, 32)
}
if w == 1 && len(s)+w <= cap(s) {
s = s[:len(s)+1]
s[len(s)-1] = parser.buffer[parser.buffer_pos]
parser.buffer_pos++
} else {
s = append(s, parser.buffer[parser.buffer_pos:parser.buffer_pos+w]...)
parser.buffer_pos += w
}
parser.mark.index++
parser.mark.column++
parser.unread--
return s
}
// Copy a line break character to a string buffer and advance pointers.
func read_line(parser *yaml_parser_t, s []byte) []byte {
buf := parser.buffer
pos := parser.buffer_pos
switch {
case buf[pos] == '\r' && buf[pos+1] == '\n':
// CR LF . LF
s = append(s, '\n')
parser.buffer_pos += 2
parser.mark.index++
parser.unread--
case buf[pos] == '\r' || buf[pos] == '\n':
// CR|LF . LF
s = append(s, '\n')
parser.buffer_pos += 1
case buf[pos] == '\xC2' && buf[pos+1] == '\x85':
// NEL . LF
s = append(s, '\n')
parser.buffer_pos += 2
case buf[pos] == '\xE2' && buf[pos+1] == '\x80' && (buf[pos+2] == '\xA8' || buf[pos+2] == '\xA9'):
// LS|PS . LS|PS
s = append(s, buf[parser.buffer_pos:pos+3]...)
parser.buffer_pos += 3
default:
return s
}
parser.mark.index++
parser.mark.column = 0
parser.mark.line++
parser.unread--
parser.newlines++
return s
}
// Get the next token.
func yaml_parser_scan(parser *yaml_parser_t, token *yaml_token_t) bool {
// Erase the token object.
*token = yaml_token_t{} // [Go] Is this necessary?
// No tokens after STREAM-END or error.
if parser.stream_end_produced || parser.error != yaml_NO_ERROR {
return true
}
// Ensure that the tokens queue contains enough tokens.
if !parser.token_available {
if !yaml_parser_fetch_more_tokens(parser) {
return false
}
}
// Fetch the next token from the queue.
*token = parser.tokens[parser.tokens_head]
parser.tokens_head++
parser.tokens_parsed++
parser.token_available = false
if token.typ == yaml_STREAM_END_TOKEN {
parser.stream_end_produced = true
}
return true
}
// Set the scanner error and return false.
func yaml_parser_set_scanner_error(parser *yaml_parser_t, context string, context_mark yaml_mark_t, problem string) bool {
parser.error = yaml_SCANNER_ERROR
parser.context = context
parser.context_mark = context_mark
parser.problem = problem
parser.problem_mark = parser.mark
return false
}
func yaml_parser_set_scanner_tag_error(parser *yaml_parser_t, directive bool, context_mark yaml_mark_t, problem string) bool {
context := "while parsing a tag"
if directive {
context = "while parsing a %TAG directive"
}
return yaml_parser_set_scanner_error(parser, context, context_mark, problem)
}
func trace(args ...interface{}) func() {
pargs := append([]interface{}{"+++"}, args...)
fmt.Println(pargs...)
pargs = append([]interface{}{"---"}, args...)
return func() { fmt.Println(pargs...) }
}
// Ensure that the tokens queue contains at least one token which can be
// returned to the Parser.
func yaml_parser_fetch_more_tokens(parser *yaml_parser_t) bool {
// While we need more tokens to fetch, do it.
for {
// [Go] The comment parsing logic requires a lookahead of two tokens
// so that foot comments may be parsed in time of associating them
// with the tokens that are parsed before them, and also for line
// comments to be transformed into head comments in some edge cases.
if parser.tokens_head < len(parser.tokens)-2 {
// If a potential simple key is at the head position, we need to fetch
// the next token to disambiguate it.
head_tok_idx, ok := parser.simple_keys_by_tok[parser.tokens_parsed]
if !ok {
break
} else if valid, ok := yaml_simple_key_is_valid(parser, &parser.simple_keys[head_tok_idx]); !ok {
return false
} else if !valid {
break
}
}
// Fetch the next token.
if !yaml_parser_fetch_next_token(parser) {
return false
}
}
parser.token_available = true
return true
}
// The dispatcher for token fetchers.
func yaml_parser_fetch_next_token(parser *yaml_parser_t) (ok bool) {
// Ensure that the buffer is initialized.
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false
}
// Check if we just started scanning. Fetch STREAM-START then.
if !parser.stream_start_produced {
return yaml_parser_fetch_stream_start(parser)
}
scan_mark := parser.mark
// Eat whitespaces and comments until we reach the next token.
if !yaml_parser_scan_to_next_token(parser) {
return false
}
// [Go] While unrolling indents, transform the head comments of prior
// indentation levels observed after scan_start into foot comments at
// the respective indexes.
// Check the indentation level against the current column.
if !yaml_parser_unroll_indent(parser, parser.mark.column, scan_mark) {
return false
}
// Ensure that the buffer contains at least 4 characters. 4 is the length
// of the longest indicators ('--- ' and '... ').
if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) {
return false
}
// Is it the end of the stream?
if is_z(parser.buffer, parser.buffer_pos) {
return yaml_parser_fetch_stream_end(parser)
}
// Is it a directive?
if parser.mark.column == 0 && parser.buffer[parser.buffer_pos] == '%' {
return yaml_parser_fetch_directive(parser)
}
buf := parser.buffer
pos := parser.buffer_pos
// Is it the document start indicator?
if parser.mark.column == 0 && buf[pos] == '-' && buf[pos+1] == '-' && buf[pos+2] == '-' && is_blankz(buf, pos+3) {
return yaml_parser_fetch_document_indicator(parser, yaml_DOCUMENT_START_TOKEN)
}
// Is it the document end indicator?
if parser.mark.column == 0 && buf[pos] == '.' && buf[pos+1] == '.' && buf[pos+2] == '.' && is_blankz(buf, pos+3) {
return yaml_parser_fetch_document_indicator(parser, yaml_DOCUMENT_END_TOKEN)
}
comment_mark := parser.mark
if len(parser.tokens) > 0 && (parser.flow_level == 0 && buf[pos] == ':' || parser.flow_level > 0 && buf[pos] == ',') {
// Associate any following comments with the prior token.
comment_mark = parser.tokens[len(parser.tokens)-1].start_mark
}
defer func() {
if !ok {
return
}
if !yaml_parser_scan_line_comment(parser, comment_mark) {
ok = false
return
}
}()
// Is it the flow sequence start indicator?
if buf[pos] == '[' {
return yaml_parser_fetch_flow_collection_start(parser, yaml_FLOW_SEQUENCE_START_TOKEN)
}
// Is it the flow mapping start indicator?
if parser.buffer[parser.buffer_pos] == '{' {
return yaml_parser_fetch_flow_collection_start(parser, yaml_FLOW_MAPPING_START_TOKEN)
}
// Is it the flow sequence end indicator?
if parser.buffer[parser.buffer_pos] == ']' {
return yaml_parser_fetch_flow_collection_end(parser,
yaml_FLOW_SEQUENCE_END_TOKEN)
}
// Is it the flow mapping end indicator?
if parser.buffer[parser.buffer_pos] == '}' {
return yaml_parser_fetch_flow_collection_end(parser,
yaml_FLOW_MAPPING_END_TOKEN)
}
// Is it the flow entry indicator?
if parser.buffer[parser.buffer_pos] == ',' {
return yaml_parser_fetch_flow_entry(parser)
}
// Is it the block entry indicator?
if parser.buffer[parser.buffer_pos] == '-' && is_blankz(parser.buffer, parser.buffer_pos+1) {
return yaml_parser_fetch_block_entry(parser)
}
// Is it the key indicator?
if parser.buffer[parser.buffer_pos] == '?' && (parser.flow_level > 0 || is_blankz(parser.buffer, parser.buffer_pos+1)) {
return yaml_parser_fetch_key(parser)
}
// Is it the value indicator?
if parser.buffer[parser.buffer_pos] == ':' && (parser.flow_level > 0 || is_blankz(parser.buffer, parser.buffer_pos+1)) {
return yaml_parser_fetch_value(parser)
}
// Is it an alias?
if parser.buffer[parser.buffer_pos] == '*' {
return yaml_parser_fetch_anchor(parser, yaml_ALIAS_TOKEN)
}
// Is it an anchor?
if parser.buffer[parser.buffer_pos] == '&' {
return yaml_parser_fetch_anchor(parser, yaml_ANCHOR_TOKEN)
}
// Is it a tag?
if parser.buffer[parser.buffer_pos] == '!' {
return yaml_parser_fetch_tag(parser)
}
// Is it a literal scalar?
if parser.buffer[parser.buffer_pos] == '|' && parser.flow_level == 0 {
return yaml_parser_fetch_block_scalar(parser, true)
}
// Is it a folded scalar?
if parser.buffer[parser.buffer_pos] == '>' && parser.flow_level == 0 {
return yaml_parser_fetch_block_scalar(parser, false)
}
// Is it a single-quoted scalar?
if parser.buffer[parser.buffer_pos] == '\'' {
return yaml_parser_fetch_flow_scalar(parser, true)
}
// Is it a double-quoted scalar?
if parser.buffer[parser.buffer_pos] == '"' {
return yaml_parser_fetch_flow_scalar(parser, false)
}
// Is it a plain scalar?
//
// A plain scalar may start with any non-blank characters except
//
// '-', '?', ':', ',', '[', ']', '{', '}',
// '#', '&', '*', '!', '|', '>', '\'', '\"',
// '%', '@', '`'.
//
// In the block context (and, for the '-' indicator, in the flow context
// too), it may also start with the characters
//
// '-', '?', ':'
//
// if it is followed by a non-space character.
//
// The last rule is more restrictive than the specification requires.
// [Go] TODO Make this logic more reasonable.
//switch parser.buffer[parser.buffer_pos] {
//case '-', '?', ':', ',', '?', '-', ',', ':', ']', '[', '}', '{', '&', '#', '!', '*', '>', '|', '"', '\'', '@', '%', '-', '`':
//}
if !(is_blankz(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == '-' ||
parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == ':' ||
parser.buffer[parser.buffer_pos] == ',' || parser.buffer[parser.buffer_pos] == '[' ||
parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '{' ||
parser.buffer[parser.buffer_pos] == '}' || parser.buffer[parser.buffer_pos] == '#' ||
parser.buffer[parser.buffer_pos] == '&' || parser.buffer[parser.buffer_pos] == '*' ||
parser.buffer[parser.buffer_pos] == '!' || parser.buffer[parser.buffer_pos] == '|' ||
parser.buffer[parser.buffer_pos] == '>' || parser.buffer[parser.buffer_pos] == '\'' ||
parser.buffer[parser.buffer_pos] == '"' || parser.buffer[parser.buffer_pos] == '%' ||
parser.buffer[parser.buffer_pos] == '@' || parser.buffer[parser.buffer_pos] == '`') ||
(parser.buffer[parser.buffer_pos] == '-' && !is_blank(parser.buffer, parser.buffer_pos+1)) ||
(parser.flow_level == 0 &&
(parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == ':') &&
!is_blankz(parser.buffer, parser.buffer_pos+1)) {
return yaml_parser_fetch_plain_scalar(parser)
}
// If we don't determine the token type so far, it is an error.
return yaml_parser_set_scanner_error(parser,
"while scanning for the next token", parser.mark,
"found character that cannot start any token")
}
func yaml_simple_key_is_valid(parser *yaml_parser_t, simple_key *yaml_simple_key_t) (valid, ok bool) {
if !simple_key.possible {
return false, true
}
// The 1.2 specification says:
//
// "If the ? indicator is omitted, parsing needs to see past the
// implicit key to recognize it as such. To limit the amount of
// lookahead required, the “:” indicator must appear at most 1024
// Unicode characters beyond the start of the key. In addition, the key
// is restricted to a single line."
//
if simple_key.mark.line < parser.mark.line || simple_key.mark.index+1024 < parser.mark.index {
// Check if the potential simple key to be removed is required.
if simple_key.required {
return false, yaml_parser_set_scanner_error(parser,
"while scanning a simple key", simple_key.mark,
"could not find expected ':'")
}
simple_key.possible = false
return false, true
}
return true, true
}
// Check if a simple key may start at the current position and add it if
// needed.
func yaml_parser_save_simple_key(parser *yaml_parser_t) bool {
// A simple key is required at the current position if the scanner is in
// the block context and the current column coincides with the indentation
// level.
required := parser.flow_level == 0 && parser.indent == parser.mark.column
//
// If the current position may start a simple key, save it.
//
if parser.simple_key_allowed {
simple_key := yaml_simple_key_t{
possible: true,
required: required,
token_number: parser.tokens_parsed + (len(parser.tokens) - parser.tokens_head),
mark: parser.mark,
}
if !yaml_parser_remove_simple_key(parser) {
return false
}
parser.simple_keys[len(parser.simple_keys)-1] = simple_key
parser.simple_keys_by_tok[simple_key.token_number] = len(parser.simple_keys) - 1
}
return true
}
// Remove a potential simple key at the current flow level.
func yaml_parser_remove_simple_key(parser *yaml_parser_t) bool {
i := len(parser.simple_keys) - 1
if parser.simple_keys[i].possible {
// If the key is required, it is an error.
if parser.simple_keys[i].required {
return yaml_parser_set_scanner_error(parser,
"while scanning a simple key", parser.simple_keys[i].mark,
"could not find expected ':'")
}
// Remove the key from the stack.
parser.simple_keys[i].possible = false
delete(parser.simple_keys_by_tok, parser.simple_keys[i].token_number)
}
return true
}
// max_flow_level limits the flow_level
const max_flow_level = 10000
// Increase the flow level and resize the simple key list if needed.
func yaml_parser_increase_flow_level(parser *yaml_parser_t) bool {
// Reset the simple key on the next level.
parser.simple_keys = append(parser.simple_keys, yaml_simple_key_t{
possible: false,
required: false,
token_number: parser.tokens_parsed + (len(parser.tokens) - parser.tokens_head),
mark: parser.mark,
})
// Increase the flow level.
parser.flow_level++
if parser.flow_level > max_flow_level {
return yaml_parser_set_scanner_error(parser,
"while increasing flow level", parser.simple_keys[len(parser.simple_keys)-1].mark,
fmt.Sprintf("exceeded max depth of %d", max_flow_level))
}
return true
}
// Decrease the flow level.
func yaml_parser_decrease_flow_level(parser *yaml_parser_t) bool {
if parser.flow_level > 0 {
parser.flow_level--
last := len(parser.simple_keys) - 1
delete(parser.simple_keys_by_tok, parser.simple_keys[last].token_number)
parser.simple_keys = parser.simple_keys[:last]
}
return true
}
// max_indents limits the indents stack size
const max_indents = 10000
// Push the current indentation level to the stack and set the new level
// the current column is greater than the indentation level. In this case,
// append or insert the specified token into the token queue.
func yaml_parser_roll_indent(parser *yaml_parser_t, column, number int, typ yaml_token_type_t, mark yaml_mark_t) bool {
// In the flow context, do nothing.
if parser.flow_level > 0 {
return true
}
if parser.indent < column {
// Push the current indentation level to the stack and set the new
// indentation level.
parser.indents = append(parser.indents, parser.indent)
parser.indent = column
if len(parser.indents) > max_indents {
return yaml_parser_set_scanner_error(parser,
"while increasing indent level", parser.simple_keys[len(parser.simple_keys)-1].mark,
fmt.Sprintf("exceeded max depth of %d", max_indents))
}
// Create a token and insert it into the queue.
token := yaml_token_t{
typ: typ,
start_mark: mark,
end_mark: mark,
}
if number > -1 {
number -= parser.tokens_parsed
}
yaml_insert_token(parser, number, &token)
}
return true
}
// Pop indentation levels from the indents stack until the current level
// becomes less or equal to the column. For each indentation level, append
// the BLOCK-END token.
func yaml_parser_unroll_indent(parser *yaml_parser_t, column int, scan_mark yaml_mark_t) bool {
// In the flow context, do nothing.
if parser.flow_level > 0 {
return true
}
block_mark := scan_mark
block_mark.index--
// Loop through the indentation levels in the stack.
for parser.indent > column {
// [Go] Reposition the end token before potential following
// foot comments of parent blocks. For that, search
// backwards for recent comments that were at the same
// indent as the block that is ending now.
stop_index := block_mark.index
for i := len(parser.comments) - 1; i >= 0; i-- {
comment := &parser.comments[i]
if comment.end_mark.index < stop_index {
// Don't go back beyond the start of the comment/whitespace scan, unless column < 0.
// If requested indent column is < 0, then the document is over and everything else
// is a foot anyway.
break
}
if comment.start_mark.column == parser.indent+1 {
// This is a good match. But maybe there's a former comment
// at that same indent level, so keep searching.
block_mark = comment.start_mark
}
// While the end of the former comment matches with
// the start of the following one, we know there's
// nothing in between and scanning is still safe.
stop_index = comment.scan_mark.index
}
// Create a token and append it to the queue.
token := yaml_token_t{
typ: yaml_BLOCK_END_TOKEN,
start_mark: block_mark,
end_mark: block_mark,
}
yaml_insert_token(parser, -1, &token)
// Pop the indentation level.
parser.indent = parser.indents[len(parser.indents)-1]
parser.indents = parser.indents[:len(parser.indents)-1]
}
return true
}
// Initialize the scanner and produce the STREAM-START token.
func yaml_parser_fetch_stream_start(parser *yaml_parser_t) bool {
// Set the initial indentation.
parser.indent = -1
// Initialize the simple key stack.
parser.simple_keys = append(parser.simple_keys, yaml_simple_key_t{})
parser.simple_keys_by_tok = make(map[int]int)
// A simple key is allowed at the beginning of the stream.
parser.simple_key_allowed = true
// We have started.
parser.stream_start_produced = true
// Create the STREAM-START token and append it to the queue.
token := yaml_token_t{
typ: yaml_STREAM_START_TOKEN,
start_mark: parser.mark,
end_mark: parser.mark,
encoding: parser.encoding,
}
yaml_insert_token(parser, -1, &token)
return true
}
// Produce the STREAM-END token and shut down the scanner.
func yaml_parser_fetch_stream_end(parser *yaml_parser_t) bool {
// Force new line.
if parser.mark.column != 0 {
parser.mark.column = 0
parser.mark.line++
}
// Reset the indentation level.
if !yaml_parser_unroll_indent(parser, -1, parser.mark) {
return false
}
// Reset simple keys.
if !yaml_parser_remove_simple_key(parser) {
return false
}
parser.simple_key_allowed = false
// Create the STREAM-END token and append it to the queue.
token := yaml_token_t{
typ: yaml_STREAM_END_TOKEN,
start_mark: parser.mark,
end_mark: parser.mark,
}
yaml_insert_token(parser, -1, &token)
return true
}
// Produce a VERSION-DIRECTIVE or TAG-DIRECTIVE token.
func yaml_parser_fetch_directive(parser *yaml_parser_t) bool {
// Reset the indentation level.
if !yaml_parser_unroll_indent(parser, -1, parser.mark) {
return false
}
// Reset simple keys.
if !yaml_parser_remove_simple_key(parser) {
return false
}
parser.simple_key_allowed = false
// Create the YAML-DIRECTIVE or TAG-DIRECTIVE token.
token := yaml_token_t{}
if !yaml_parser_scan_directive(parser, &token) {
return false
}
// Append the token to the queue.
yaml_insert_token(parser, -1, &token)
return true
}
// Produce the DOCUMENT-START or DOCUMENT-END token.
func yaml_parser_fetch_document_indicator(parser *yaml_parser_t, typ yaml_token_type_t) bool {
// Reset the indentation level.
if !yaml_parser_unroll_indent(parser, -1, parser.mark) {
return false
}
// Reset simple keys.
if !yaml_parser_remove_simple_key(parser) {
return false
}
parser.simple_key_allowed = false
// Consume the token.
start_mark := parser.mark
skip(parser)
skip(parser)
skip(parser)
end_mark := parser.mark
// Create the DOCUMENT-START or DOCUMENT-END token.
token := yaml_token_t{
typ: typ,
start_mark: start_mark,
end_mark: end_mark,
}
// Append the token to the queue.
yaml_insert_token(parser, -1, &token)
return true
}
// Produce the FLOW-SEQUENCE-START or FLOW-MAPPING-START token.
func yaml_parser_fetch_flow_collection_start(parser *yaml_parser_t, typ yaml_token_type_t) bool {
// The indicators '[' and '{' may start a simple key.
if !yaml_parser_save_simple_key(parser) {
return false
}
// Increase the flow level.
if !yaml_parser_increase_flow_level(parser) {
return false
}
// A simple key may follow the indicators '[' and '{'.
parser.simple_key_allowed = true
// Consume the token.
start_mark := parser.mark
skip(parser)
end_mark := parser.mark
// Create the FLOW-SEQUENCE-START of FLOW-MAPPING-START token.
token := yaml_token_t{
typ: typ,
start_mark: start_mark,
end_mark: end_mark,
}
// Append the token to the queue.
yaml_insert_token(parser, -1, &token)
return true
}
// Produce the FLOW-SEQUENCE-END or FLOW-MAPPING-END token.
func yaml_parser_fetch_flow_collection_end(parser *yaml_parser_t, typ yaml_token_type_t) bool {
// Reset any potential simple key on the current flow level.
if !yaml_parser_remove_simple_key(parser) {
return false
}
// Decrease the flow level.
if !yaml_parser_decrease_flow_level(parser) {
return false
}
// No simple keys after the indicators ']' and '}'.
parser.simple_key_allowed = false
// Consume the token.
start_mark := parser.mark
skip(parser)
end_mark := parser.mark
// Create the FLOW-SEQUENCE-END of FLOW-MAPPING-END token.
token := yaml_token_t{
typ: typ,
start_mark: start_mark,
end_mark: end_mark,
}
// Append the token to the queue.
yaml_insert_token(parser, -1, &token)
return true
}
// Produce the FLOW-ENTRY token.
func yaml_parser_fetch_flow_entry(parser *yaml_parser_t) bool {
// Reset any potential simple keys on the current flow level.
if !yaml_parser_remove_simple_key(parser) {
return false
}
// Simple keys are allowed after ','.
parser.simple_key_allowed = true
// Consume the token.
start_mark := parser.mark
skip(parser)
end_mark := parser.mark
// Create the FLOW-ENTRY token and append it to the queue.
token := yaml_token_t{
typ: yaml_FLOW_ENTRY_TOKEN,
start_mark: start_mark,
end_mark: end_mark,
}
yaml_insert_token(parser, -1, &token)
return true
}
// Produce the BLOCK-ENTRY token.
func yaml_parser_fetch_block_entry(parser *yaml_parser_t) bool {
// Check if the scanner is in the block context.
if parser.flow_level == 0 {
// Check if we are allowed to start a new entry.
if !parser.simple_key_allowed {
return yaml_parser_set_scanner_error(parser, "", parser.mark,
"block sequence entries are not allowed in this context")
}
// Add the BLOCK-SEQUENCE-START token if needed.
if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_SEQUENCE_START_TOKEN, parser.mark) {
return false
}
} else {
// It is an error for the '-' indicator to occur in the flow context,
// but we let the Parser detect and report about it because the Parser
// is able to point to the context.
}
// Reset any potential simple keys on the current flow level.
if !yaml_parser_remove_simple_key(parser) {
return false
}
// Simple keys are allowed after '-'.
parser.simple_key_allowed = true
// Consume the token.
start_mark := parser.mark
skip(parser)
end_mark := parser.mark
// Create the BLOCK-ENTRY token and append it to the queue.
token := yaml_token_t{
typ: yaml_BLOCK_ENTRY_TOKEN,
start_mark: start_mark,
end_mark: end_mark,
}
yaml_insert_token(parser, -1, &token)
return true
}
// Produce the KEY token.
func yaml_parser_fetch_key(parser *yaml_parser_t) bool {
// In the block context, additional checks are required.
if parser.flow_level == 0 {
// Check if we are allowed to start a new key (not nessesary simple).
if !parser.simple_key_allowed {
return yaml_parser_set_scanner_error(parser, "", parser.mark,
"mapping keys are not allowed in this context")
}
// Add the BLOCK-MAPPING-START token if needed.
if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_MAPPING_START_TOKEN, parser.mark) {
return false
}
}
// Reset any potential simple keys on the current flow level.
if !yaml_parser_remove_simple_key(parser) {
return false
}
// Simple keys are allowed after '?' in the block context.
parser.simple_key_allowed = parser.flow_level == 0
// Consume the token.
start_mark := parser.mark
skip(parser)
end_mark := parser.mark
// Create the KEY token and append it to the queue.
token := yaml_token_t{
typ: yaml_KEY_TOKEN,
start_mark: start_mark,
end_mark: end_mark,
}
yaml_insert_token(parser, -1, &token)
return true
}
// Produce the VALUE token.
func yaml_parser_fetch_value(parser *yaml_parser_t) bool {
simple_key := &parser.simple_keys[len(parser.simple_keys)-1]
// Have we found a simple key?
if valid, ok := yaml_simple_key_is_valid(parser, simple_key); !ok {
return false
} else if valid {
// Create the KEY token and insert it into the queue.
token := yaml_token_t{
typ: yaml_KEY_TOKEN,
start_mark: simple_key.mark,
end_mark: simple_key.mark,
}
yaml_insert_token(parser, simple_key.token_number-parser.tokens_parsed, &token)
// In the block context, we may need to add the BLOCK-MAPPING-START token.
if !yaml_parser_roll_indent(parser, simple_key.mark.column,
simple_key.token_number,
yaml_BLOCK_MAPPING_START_TOKEN, simple_key.mark) {
return false
}
// Remove the simple key.
simple_key.possible = false
delete(parser.simple_keys_by_tok, simple_key.token_number)
// A simple key cannot follow another simple key.
parser.simple_key_allowed = false
} else {
// The ':' indicator follows a complex key.
// In the block context, extra checks are required.
if parser.flow_level == 0 {
// Check if we are allowed to start a complex value.
if !parser.simple_key_allowed {
return yaml_parser_set_scanner_error(parser, "", parser.mark,
"mapping values are not allowed in this context")
}
// Add the BLOCK-MAPPING-START token if needed.
if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_MAPPING_START_TOKEN, parser.mark) {
return false
}
}
// Simple keys after ':' are allowed in the block context.
parser.simple_key_allowed = parser.flow_level == 0
}
// Consume the token.
start_mark := parser.mark
skip(parser)
end_mark := parser.mark
// Create the VALUE token and append it to the queue.
token := yaml_token_t{
typ: yaml_VALUE_TOKEN,
start_mark: start_mark,
end_mark: end_mark,
}
yaml_insert_token(parser, -1, &token)
return true
}
// Produce the ALIAS or ANCHOR token.
func yaml_parser_fetch_anchor(parser *yaml_parser_t, typ yaml_token_type_t) bool {
// An anchor or an alias could be a simple key.
if !yaml_parser_save_simple_key(parser) {
return false
}
// A simple key cannot follow an anchor or an alias.
parser.simple_key_allowed = false
// Create the ALIAS or ANCHOR token and append it to the queue.
var token yaml_token_t
if !yaml_parser_scan_anchor(parser, &token, typ) {
return false
}
yaml_insert_token(parser, -1, &token)
return true
}
// Produce the TAG token.
func yaml_parser_fetch_tag(parser *yaml_parser_t) bool {
// A tag could be a simple key.
if !yaml_parser_save_simple_key(parser) {
return false
}
// A simple key cannot follow a tag.
parser.simple_key_allowed = false
// Create the TAG token and append it to the queue.
var token yaml_token_t
if !yaml_parser_scan_tag(parser, &token) {
return false
}
yaml_insert_token(parser, -1, &token)
return true
}
// Produce the SCALAR(...,literal) or SCALAR(...,folded) tokens.
func yaml_parser_fetch_block_scalar(parser *yaml_parser_t, literal bool) bool {
// Remove any potential simple keys.
if !yaml_parser_remove_simple_key(parser) {
return false
}
// A simple key may follow a block scalar.
parser.simple_key_allowed = true
// Create the SCALAR token and append it to the queue.
var token yaml_token_t
if !yaml_parser_scan_block_scalar(parser, &token, literal) {
return false
}
yaml_insert_token(parser, -1, &token)
return true
}
// Produce the SCALAR(...,single-quoted) or SCALAR(...,double-quoted) tokens.
func yaml_parser_fetch_flow_scalar(parser *yaml_parser_t, single bool) bool {
// A plain scalar could be a simple key.
if !yaml_parser_save_simple_key(parser) {
return false
}
// A simple key cannot follow a flow scalar.
parser.simple_key_allowed = false
// Create the SCALAR token and append it to the queue.
var token yaml_token_t
if !yaml_parser_scan_flow_scalar(parser, &token, single) {
return false
}
yaml_insert_token(parser, -1, &token)
return true
}
// Produce the SCALAR(...,plain) token.
func yaml_parser_fetch_plain_scalar(parser *yaml_parser_t) bool {
// A plain scalar could be a simple key.
if !yaml_parser_save_simple_key(parser) {
return false
}
// A simple key cannot follow a flow scalar.
parser.simple_key_allowed = false
// Create the SCALAR token and append it to the queue.
var token yaml_token_t
if !yaml_parser_scan_plain_scalar(parser, &token) {
return false
}
yaml_insert_token(parser, -1, &token)
return true
}
// Eat whitespaces and comments until the next token is found.
func yaml_parser_scan_to_next_token(parser *yaml_parser_t) bool {
scan_mark := parser.mark
// Until the next token is not found.
for {
// Allow the BOM mark to start a line.
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false
}
if parser.mark.column == 0 && is_bom(parser.buffer, parser.buffer_pos) {
skip(parser)
}
// Eat whitespaces.
// Tabs are allowed:
// - in the flow context
// - in the block context, but not at the beginning of the line or
// after '-', '?', or ':' (complex value).
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false
}
for parser.buffer[parser.buffer_pos] == ' ' || ((parser.flow_level > 0 || !parser.simple_key_allowed) && parser.buffer[parser.buffer_pos] == '\t') {
skip(parser)
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false
}
}
// Check if we just had a line comment under a sequence entry that
// looks more like a header to the following content. Similar to this:
//
// - # The comment
// - Some data
//
// If so, transform the line comment to a head comment and reposition.
if len(parser.comments) > 0 && len(parser.tokens) > 1 {
tokenA := parser.tokens[len(parser.tokens)-2]
tokenB := parser.tokens[len(parser.tokens)-1]
comment := &parser.comments[len(parser.comments)-1]
if tokenA.typ == yaml_BLOCK_SEQUENCE_START_TOKEN && tokenB.typ == yaml_BLOCK_ENTRY_TOKEN && len(comment.line) > 0 && !is_break(parser.buffer, parser.buffer_pos) {
// If it was in the prior line, reposition so it becomes a
// header of the follow up token. Otherwise, keep it in place
// so it becomes a header of the former.
comment.head = comment.line
comment.line = nil
if comment.start_mark.line == parser.mark.line-1 {
comment.token_mark = parser.mark
}
}
}
// Eat a comment until a line break.
if parser.buffer[parser.buffer_pos] == '#' {
if !yaml_parser_scan_comments(parser, scan_mark) {
return false
}
}
// If it is a line break, eat it.
if is_break(parser.buffer, parser.buffer_pos) {
if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) {
return false
}
skip_line(parser)
// In the block context, a new line may start a simple key.
if parser.flow_level == 0 {
parser.simple_key_allowed = true
}
} else {
break // We have found a token.
}
}
return true
}
// Scan a YAML-DIRECTIVE or TAG-DIRECTIVE token.
//
// Scope:
// %YAML 1.1 # a comment \n
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// %TAG !yaml! tag:yaml.org,2002: \n
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//
func yaml_parser_scan_directive(parser *yaml_parser_t, token *yaml_token_t) bool {
// Eat '%'.
start_mark := parser.mark
skip(parser)
// Scan the directive name.
var name []byte
if !yaml_parser_scan_directive_name(parser, start_mark, &name) {
return false
}
// Is it a YAML directive?
if bytes.Equal(name, []byte("YAML")) {
// Scan the VERSION directive value.
var major, minor int8
if !yaml_parser_scan_version_directive_value(parser, start_mark, &major, &minor) {
return false
}
end_mark := parser.mark
// Create a VERSION-DIRECTIVE token.
*token = yaml_token_t{
typ: yaml_VERSION_DIRECTIVE_TOKEN,
start_mark: start_mark,
end_mark: end_mark,
major: major,
minor: minor,
}
// Is it a TAG directive?
} else if bytes.Equal(name, []byte("TAG")) {
// Scan the TAG directive value.
var handle, prefix []byte
if !yaml_parser_scan_tag_directive_value(parser, start_mark, &handle, &prefix) {
return false
}
end_mark := parser.mark
// Create a TAG-DIRECTIVE token.
*token = yaml_token_t{
typ: yaml_TAG_DIRECTIVE_TOKEN,
start_mark: start_mark,
end_mark: end_mark,
value: handle,
prefix: prefix,
}
// Unknown directive.
} else {
yaml_parser_set_scanner_error(parser, "while scanning a directive",
start_mark, "found unknown directive name")
return false
}
// Eat the rest of the line including any comments.
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false
}
for is_blank(parser.buffer, parser.buffer_pos) {
skip(parser)
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false
}
}
if parser.buffer[parser.buffer_pos] == '#' {
// [Go] Discard this inline comment for the time being.
//if !yaml_parser_scan_line_comment(parser, start_mark) {
// return false
//}
for !is_breakz(parser.buffer, parser.buffer_pos) {
skip(parser)
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false
}
}
}
// Check if we are at the end of the line.
if !is_breakz(parser.buffer, parser.buffer_pos) {
yaml_parser_set_scanner_error(parser, "while scanning a directive",
start_mark, "did not find expected comment or line break")
return false
}
// Eat a line break.
if is_break(parser.buffer, parser.buffer_pos) {
if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) {
return false
}
skip_line(parser)
}
return true
}
// Scan the directive name.
//
// Scope:
// %YAML 1.1 # a comment \n
// ^^^^
// %TAG !yaml! tag:yaml.org,2002: \n
// ^^^
//
func yaml_parser_scan_directive_name(parser *yaml_parser_t, start_mark yaml_mark_t, name *[]byte) bool {
// Consume the directive name.
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false
}
var s []byte
for is_alpha(parser.buffer, parser.buffer_pos) {
s = read(parser, s)
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false
}
}
// Check if the name is empty.
if len(s) == 0 {
yaml_parser_set_scanner_error(parser, "while scanning a directive",
start_mark, "could not find expected directive name")
return false
}
// Check for an blank character after the name.
if !is_blankz(parser.buffer, parser.buffer_pos) {
yaml_parser_set_scanner_error(parser, "while scanning a directive",
start_mark, "found unexpected non-alphabetical character")
return false
}
*name = s
return true
}
// Scan the value of VERSION-DIRECTIVE.
//
// Scope:
// %YAML 1.1 # a comment \n
// ^^^^^^
func yaml_parser_scan_version_directive_value(parser *yaml_parser_t, start_mark yaml_mark_t, major, minor *int8) bool {
// Eat whitespaces.
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false
}
for is_blank(parser.buffer, parser.buffer_pos) {
skip(parser)
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false
}
}
// Consume the major version number.
if !yaml_parser_scan_version_directive_number(parser, start_mark, major) {
return false
}
// Eat '.'.
if parser.buffer[parser.buffer_pos] != '.' {
return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive",
start_mark, "did not find expected digit or '.' character")
}
skip(parser)
// Consume the minor version number.
if !yaml_parser_scan_version_directive_number(parser, start_mark, minor) {
return false
}
return true
}
const max_number_length = 2
// Scan the version number of VERSION-DIRECTIVE.
//
// Scope:
// %YAML 1.1 # a comment \n
// ^
// %YAML 1.1 # a comment \n
// ^
func yaml_parser_scan_version_directive_number(parser *yaml_parser_t, start_mark yaml_mark_t, number *int8) bool {
// Repeat while the next character is digit.
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false
}
var value, length int8
for is_digit(parser.buffer, parser.buffer_pos) {
// Check if the number is too long.
length++
if length > max_number_length {
return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive",
start_mark, "found extremely long version number")
}
value = value*10 + int8(as_digit(parser.buffer, parser.buffer_pos))
skip(parser)
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false
}
}
// Check if the number was present.
if length == 0 {
return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive",
start_mark, "did not find expected version number")
}
*number = value
return true
}
// Scan the value of a TAG-DIRECTIVE token.
//
// Scope:
// %TAG !yaml! tag:yaml.org,2002: \n
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//
func yaml_parser_scan_tag_directive_value(parser *yaml_parser_t, start_mark yaml_mark_t, handle, prefix *[]byte) bool {
var handle_value, prefix_value []byte
// Eat whitespaces.
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false
}
for is_blank(parser.buffer, parser.buffer_pos) {
skip(parser)
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false
}
}
// Scan a handle.
if !yaml_parser_scan_tag_handle(parser, true, start_mark, &handle_value) {
return false
}
// Expect a whitespace.
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false
}
if !is_blank(parser.buffer, parser.buffer_pos) {
yaml_parser_set_scanner_error(parser, "while scanning a %TAG directive",
start_mark, "did not find expected whitespace")
return false
}
// Eat whitespaces.
for is_blank(parser.buffer, parser.buffer_pos) {
skip(parser)
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false
}
}
// Scan a prefix.
if !yaml_parser_scan_tag_uri(parser, true, nil, start_mark, &prefix_value) {
return false
}
// Expect a whitespace or line break.
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false
}
if !is_blankz(parser.buffer, parser.buffer_pos) {
yaml_parser_set_scanner_error(parser, "while scanning a %TAG directive",
start_mark, "did not find expected whitespace or line break")
return false
}
*handle = handle_value
*prefix = prefix_value
return true
}
func yaml_parser_scan_anchor(parser *yaml_parser_t, token *yaml_token_t, typ yaml_token_type_t) bool {
var s []byte
// Eat the indicator character.
start_mark := parser.mark
skip(parser)
// Consume the value.
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false
}
for is_alpha(parser.buffer, parser.buffer_pos) {
s = read(parser, s)
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false
}
}
end_mark := parser.mark
/*
* Check if length of the anchor is greater than 0 and it is followed by
* a whitespace character or one of the indicators:
*
* '?', ':', ',', ']', '}', '%', '@', '`'.
*/
if len(s) == 0 ||
!(is_blankz(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == '?' ||
parser.buffer[parser.buffer_pos] == ':' || parser.buffer[parser.buffer_pos] == ',' ||
parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '}' ||
parser.buffer[parser.buffer_pos] == '%' || parser.buffer[parser.buffer_pos] == '@' ||
parser.buffer[parser.buffer_pos] == '`') {
context := "while scanning an alias"
if typ == yaml_ANCHOR_TOKEN {
context = "while scanning an anchor"
}
yaml_parser_set_scanner_error(parser, context, start_mark,
"did not find expected alphabetic or numeric character")
return false
}
// Create a token.
*token = yaml_token_t{
typ: typ,
start_mark: start_mark,
end_mark: end_mark,
value: s,
}
return true
}
/*
* Scan a TAG token.
*/
func yaml_parser_scan_tag(parser *yaml_parser_t, token *yaml_token_t) bool {
var handle, suffix []byte
start_mark := parser.mark
// Check if the tag is in the canonical form.
if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) {
return false
}
if parser.buffer[parser.buffer_pos+1] == '<' {
// Keep the handle as ''
// Eat '!<'
skip(parser)
skip(parser)
// Consume the tag value.
if !yaml_parser_scan_tag_uri(parser, false, nil, start_mark, &suffix) {
return false
}
// Check for '>' and eat it.
if parser.buffer[parser.buffer_pos] != '>' {
yaml_parser_set_scanner_error(parser, "while scanning a tag",
start_mark, "did not find the expected '>'")
return false
}
skip(parser)
} else {
// The tag has either the '!suffix' or the '!handle!suffix' form.
// First, try to scan a handle.
if !yaml_parser_scan_tag_handle(parser, false, start_mark, &handle) {
return false
}
// Check if it is, indeed, handle.
if handle[0] == '!' && len(handle) > 1 && handle[len(handle)-1] == '!' {
// Scan the suffix now.
if !yaml_parser_scan_tag_uri(parser, false, nil, start_mark, &suffix) {
return false
}
} else {
// It wasn't a handle after all. Scan the rest of the tag.
if !yaml_parser_scan_tag_uri(parser, false, handle, start_mark, &suffix) {
return false
}
// Set the handle to '!'.
handle = []byte{'!'}
// A special case: the '!' tag. Set the handle to '' and the
// suffix to '!'.
if len(suffix) == 0 {
handle, suffix = suffix, handle
}
}
}
// Check the character which ends the tag.
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false
}
if !is_blankz(parser.buffer, parser.buffer_pos) {
yaml_parser_set_scanner_error(parser, "while scanning a tag",
start_mark, "did not find expected whitespace or line break")
return false
}
end_mark := parser.mark
// Create a token.
*token = yaml_token_t{
typ: yaml_TAG_TOKEN,
start_mark: start_mark,
end_mark: end_mark,
value: handle,
suffix: suffix,
}
return true
}
// Scan a tag handle.
func yaml_parser_scan_tag_handle(parser *yaml_parser_t, directive bool, start_mark yaml_mark_t, handle *[]byte) bool {
// Check the initial '!' character.
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false
}
if parser.buffer[parser.buffer_pos] != '!' {
yaml_parser_set_scanner_tag_error(parser, directive,
start_mark, "did not find expected '!'")
return false
}
var s []byte
// Copy the '!' character.
s = read(parser, s)
// Copy all subsequent alphabetical and numerical characters.
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false
}
for is_alpha(parser.buffer, parser.buffer_pos) {
s = read(parser, s)
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false
}
}
// Check if the trailing character is '!' and copy it.
if parser.buffer[parser.buffer_pos] == '!' {
s = read(parser, s)
} else {
// It's either the '!' tag or not really a tag handle. If it's a %TAG
// directive, it's an error. If it's a tag token, it must be a part of URI.
if directive && string(s) != "!" {
yaml_parser_set_scanner_tag_error(parser, directive,
start_mark, "did not find expected '!'")
return false
}
}
*handle = s
return true
}
// Scan a tag.
func yaml_parser_scan_tag_uri(parser *yaml_parser_t, directive bool, head []byte, start_mark yaml_mark_t, uri *[]byte) bool {
//size_t length = head ? strlen((char *)head) : 0
var s []byte
hasTag := len(head) > 0
// Copy the head if needed.
//
// Note that we don't copy the leading '!' character.
if len(head) > 1 {
s = append(s, head[1:]...)
}
// Scan the tag.
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false
}
// The set of characters that may appear in URI is as follows:
//
// '0'-'9', 'A'-'Z', 'a'-'z', '_', '-', ';', '/', '?', ':', '@', '&',
// '=', '+', '$', ',', '.', '!', '~', '*', '\'', '(', ')', '[', ']',
// '%'.
// [Go] TODO Convert this into more reasonable logic.
for is_alpha(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == ';' ||
parser.buffer[parser.buffer_pos] == '/' || parser.buffer[parser.buffer_pos] == '?' ||
parser.buffer[parser.buffer_pos] == ':' || parser.buffer[parser.buffer_pos] == '@' ||
parser.buffer[parser.buffer_pos] == '&' || parser.buffer[parser.buffer_pos] == '=' ||
parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '$' ||
parser.buffer[parser.buffer_pos] == ',' || parser.buffer[parser.buffer_pos] == '.' ||
parser.buffer[parser.buffer_pos] == '!' || parser.buffer[parser.buffer_pos] == '~' ||
parser.buffer[parser.buffer_pos] == '*' || parser.buffer[parser.buffer_pos] == '\'' ||
parser.buffer[parser.buffer_pos] == '(' || parser.buffer[parser.buffer_pos] == ')' ||
parser.buffer[parser.buffer_pos] == '[' || parser.buffer[parser.buffer_pos] == ']' ||
parser.buffer[parser.buffer_pos] == '%' {
// Check if it is a URI-escape sequence.
if parser.buffer[parser.buffer_pos] == '%' {
if !yaml_parser_scan_uri_escapes(parser, directive, start_mark, &s) {
return false
}
} else {
s = read(parser, s)
}
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false
}
hasTag = true
}
if !hasTag {
yaml_parser_set_scanner_tag_error(parser, directive,
start_mark, "did not find expected tag URI")
return false
}
*uri = s
return true
}
// Decode an URI-escape sequence corresponding to a single UTF-8 character.
func yaml_parser_scan_uri_escapes(parser *yaml_parser_t, directive bool, start_mark yaml_mark_t, s *[]byte) bool {
// Decode the required number of characters.
w := 1024
for w > 0 {
// Check for a URI-escaped octet.
if parser.unread < 3 && !yaml_parser_update_buffer(parser, 3) {
return false
}
if !(parser.buffer[parser.buffer_pos] == '%' &&
is_hex(parser.buffer, parser.buffer_pos+1) &&
is_hex(parser.buffer, parser.buffer_pos+2)) {
return yaml_parser_set_scanner_tag_error(parser, directive,
start_mark, "did not find URI escaped octet")
}
// Get the octet.
octet := byte((as_hex(parser.buffer, parser.buffer_pos+1) << 4) + as_hex(parser.buffer, parser.buffer_pos+2))
// If it is the leading octet, determine the length of the UTF-8 sequence.
if w == 1024 {
w = width(octet)
if w == 0 {
return yaml_parser_set_scanner_tag_error(parser, directive,
start_mark, "found an incorrect leading UTF-8 octet")
}
} else {
// Check if the trailing octet is correct.
if octet&0xC0 != 0x80 {
return yaml_parser_set_scanner_tag_error(parser, directive,
start_mark, "found an incorrect trailing UTF-8 octet")
}
}
// Copy the octet and move the pointers.
*s = append(*s, octet)
skip(parser)
skip(parser)
skip(parser)
w--
}
return true
}
// Scan a block scalar.
func yaml_parser_scan_block_scalar(parser *yaml_parser_t, token *yaml_token_t, literal bool) bool {
// Eat the indicator '|' or '>'.
start_mark := parser.mark
skip(parser)
// Scan the additional block scalar indicators.
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false
}
// Check for a chomping indicator.
var chomping, increment int
if parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '-' {
// Set the chomping method and eat the indicator.
if parser.buffer[parser.buffer_pos] == '+' {
chomping = +1
} else {
chomping = -1
}
skip(parser)
// Check for an indentation indicator.
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false
}
if is_digit(parser.buffer, parser.buffer_pos) {
// Check that the indentation is greater than 0.
if parser.buffer[parser.buffer_pos] == '0' {
yaml_parser_set_scanner_error(parser, "while scanning a block scalar",
start_mark, "found an indentation indicator equal to 0")
return false
}
// Get the indentation level and eat the indicator.
increment = as_digit(parser.buffer, parser.buffer_pos)
skip(parser)
}
} else if is_digit(parser.buffer, parser.buffer_pos) {
// Do the same as above, but in the opposite order.
if parser.buffer[parser.buffer_pos] == '0' {
yaml_parser_set_scanner_error(parser, "while scanning a block scalar",
start_mark, "found an indentation indicator equal to 0")
return false
}
increment = as_digit(parser.buffer, parser.buffer_pos)
skip(parser)
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false
}
if parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '-' {
if parser.buffer[parser.buffer_pos] == '+' {
chomping = +1
} else {
chomping = -1
}
skip(parser)
}
}
// Eat whitespaces and comments to the end of the line.
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false
}
for is_blank(parser.buffer, parser.buffer_pos) {
skip(parser)
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false
}
}
if parser.buffer[parser.buffer_pos] == '#' {
// TODO Test this and then re-enable it.
//if !yaml_parser_scan_line_comment(parser, start_mark) {
// return false
//}
for !is_breakz(parser.buffer, parser.buffer_pos) {
skip(parser)
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false
}
}
}
// Check if we are at the end of the line.
if !is_breakz(parser.buffer, parser.buffer_pos) {
yaml_parser_set_scanner_error(parser, "while scanning a block scalar",
start_mark, "did not find expected comment or line break")
return false
}
// Eat a line break.
if is_break(parser.buffer, parser.buffer_pos) {
if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) {
return false
}
skip_line(parser)
}
end_mark := parser.mark
// Set the indentation level if it was specified.
var indent int
if increment > 0 {
if parser.indent >= 0 {
indent = parser.indent + increment
} else {
indent = increment
}
}
// Scan the leading line breaks and determine the indentation level if needed.
var s, leading_break, trailing_breaks []byte
if !yaml_parser_scan_block_scalar_breaks(parser, &indent, &trailing_breaks, start_mark, &end_mark) {
return false
}
// Scan the block scalar content.
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false
}
var leading_blank, trailing_blank bool
for parser.mark.column == indent && !is_z(parser.buffer, parser.buffer_pos) {
// We are at the beginning of a non-empty line.
// Is it a trailing whitespace?
trailing_blank = is_blank(parser.buffer, parser.buffer_pos)
// Check if we need to fold the leading line break.
if !literal && !leading_blank && !trailing_blank && len(leading_break) > 0 && leading_break[0] == '\n' {
// Do we need to join the lines by space?
if len(trailing_breaks) == 0 {
s = append(s, ' ')
}
} else {
s = append(s, leading_break...)
}
leading_break = leading_break[:0]
// Append the remaining line breaks.
s = append(s, trailing_breaks...)
trailing_breaks = trailing_breaks[:0]
// Is it a leading whitespace?
leading_blank = is_blank(parser.buffer, parser.buffer_pos)
// Consume the current line.
for !is_breakz(parser.buffer, parser.buffer_pos) {
s = read(parser, s)
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false
}
}
// Consume the line break.
if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) {
return false
}
leading_break = read_line(parser, leading_break)
// Eat the following indentation spaces and line breaks.
if !yaml_parser_scan_block_scalar_breaks(parser, &indent, &trailing_breaks, start_mark, &end_mark) {
return false
}
}
// Chomp the tail.
if chomping != -1 {
s = append(s, leading_break...)
}
if chomping == 1 {
s = append(s, trailing_breaks...)
}
// Create a token.
*token = yaml_token_t{
typ: yaml_SCALAR_TOKEN,
start_mark: start_mark,
end_mark: end_mark,
value: s,
style: yaml_LITERAL_SCALAR_STYLE,
}
if !literal {
token.style = yaml_FOLDED_SCALAR_STYLE
}
return true
}
// Scan indentation spaces and line breaks for a block scalar. Determine the
// indentation level if needed.
func yaml_parser_scan_block_scalar_breaks(parser *yaml_parser_t, indent *int, breaks *[]byte, start_mark yaml_mark_t, end_mark *yaml_mark_t) bool {
*end_mark = parser.mark
// Eat the indentation spaces and line breaks.
max_indent := 0
for {
// Eat the indentation spaces.
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false
}
for (*indent == 0 || parser.mark.column < *indent) && is_space(parser.buffer, parser.buffer_pos) {
skip(parser)
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false
}
}
if parser.mark.column > max_indent {
max_indent = parser.mark.column
}
// Check for a tab character messing the indentation.
if (*indent == 0 || parser.mark.column < *indent) && is_tab(parser.buffer, parser.buffer_pos) {
return yaml_parser_set_scanner_error(parser, "while scanning a block scalar",
start_mark, "found a tab character where an indentation space is expected")
}
// Have we found a non-empty line?
if !is_break(parser.buffer, parser.buffer_pos) {
break
}
// Consume the line break.
if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) {
return false
}
// [Go] Should really be returning breaks instead.
*breaks = read_line(parser, *breaks)
*end_mark = parser.mark
}
// Determine the indentation level if needed.
if *indent == 0 {
*indent = max_indent
if *indent < parser.indent+1 {
*indent = parser.indent + 1
}
if *indent < 1 {
*indent = 1
}
}
return true
}
// Scan a quoted scalar.
func yaml_parser_scan_flow_scalar(parser *yaml_parser_t, token *yaml_token_t, single bool) bool {
// Eat the left quote.
start_mark := parser.mark
skip(parser)
// Consume the content of the quoted scalar.
var s, leading_break, trailing_breaks, whitespaces []byte
for {
// Check that there are no document indicators at the beginning of the line.
if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) {
return false
}
if parser.mark.column == 0 &&
((parser.buffer[parser.buffer_pos+0] == '-' &&
parser.buffer[parser.buffer_pos+1] == '-' &&
parser.buffer[parser.buffer_pos+2] == '-') ||
(parser.buffer[parser.buffer_pos+0] == '.' &&
parser.buffer[parser.buffer_pos+1] == '.' &&
parser.buffer[parser.buffer_pos+2] == '.')) &&
is_blankz(parser.buffer, parser.buffer_pos+3) {
yaml_parser_set_scanner_error(parser, "while scanning a quoted scalar",
start_mark, "found unexpected document indicator")
return false
}
// Check for EOF.
if is_z(parser.buffer, parser.buffer_pos) {
yaml_parser_set_scanner_error(parser, "while scanning a quoted scalar",
start_mark, "found unexpected end of stream")
return false
}
// Consume non-blank characters.
leading_blanks := false
for !is_blankz(parser.buffer, parser.buffer_pos) {
if single && parser.buffer[parser.buffer_pos] == '\'' && parser.buffer[parser.buffer_pos+1] == '\'' {
// Is is an escaped single quote.
s = append(s, '\'')
skip(parser)
skip(parser)
} else if single && parser.buffer[parser.buffer_pos] == '\'' {
// It is a right single quote.
break
} else if !single && parser.buffer[parser.buffer_pos] == '"' {
// It is a right double quote.
break
} else if !single && parser.buffer[parser.buffer_pos] == '\\' && is_break(parser.buffer, parser.buffer_pos+1) {
// It is an escaped line break.
if parser.unread < 3 && !yaml_parser_update_buffer(parser, 3) {
return false
}
skip(parser)
skip_line(parser)
leading_blanks = true
break
} else if !single && parser.buffer[parser.buffer_pos] == '\\' {
// It is an escape sequence.
code_length := 0
// Check the escape character.
switch parser.buffer[parser.buffer_pos+1] {
case '0':
s = append(s, 0)
case 'a':
s = append(s, '\x07')
case 'b':
s = append(s, '\x08')
case 't', '\t':
s = append(s, '\x09')
case 'n':
s = append(s, '\x0A')
case 'v':
s = append(s, '\x0B')
case 'f':
s = append(s, '\x0C')
case 'r':
s = append(s, '\x0D')
case 'e':
s = append(s, '\x1B')
case ' ':
s = append(s, '\x20')
case '"':
s = append(s, '"')
case '\'':
s = append(s, '\'')
case '\\':
s = append(s, '\\')
case 'N': // NEL (#x85)
s = append(s, '\xC2')
s = append(s, '\x85')
case '_': // #xA0
s = append(s, '\xC2')
s = append(s, '\xA0')
case 'L': // LS (#x2028)
s = append(s, '\xE2')
s = append(s, '\x80')
s = append(s, '\xA8')
case 'P': // PS (#x2029)
s = append(s, '\xE2')
s = append(s, '\x80')
s = append(s, '\xA9')
case 'x':
code_length = 2
case 'u':
code_length = 4
case 'U':
code_length = 8
default:
yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar",
start_mark, "found unknown escape character")
return false
}
skip(parser)
skip(parser)
// Consume an arbitrary escape code.
if code_length > 0 {
var value int
// Scan the character value.
if parser.unread < code_length && !yaml_parser_update_buffer(parser, code_length) {
return false
}
for k := 0; k < code_length; k++ {
if !is_hex(parser.buffer, parser.buffer_pos+k) {
yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar",
start_mark, "did not find expected hexdecimal number")
return false
}
value = (value << 4) + as_hex(parser.buffer, parser.buffer_pos+k)
}
// Check the value and write the character.
if (value >= 0xD800 && value <= 0xDFFF) || value > 0x10FFFF {
yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar",
start_mark, "found invalid Unicode character escape code")
return false
}
if value <= 0x7F {
s = append(s, byte(value))
} else if value <= 0x7FF {
s = append(s, byte(0xC0+(value>>6)))
s = append(s, byte(0x80+(value&0x3F)))
} else if value <= 0xFFFF {
s = append(s, byte(0xE0+(value>>12)))
s = append(s, byte(0x80+((value>>6)&0x3F)))
s = append(s, byte(0x80+(value&0x3F)))
} else {
s = append(s, byte(0xF0+(value>>18)))
s = append(s, byte(0x80+((value>>12)&0x3F)))
s = append(s, byte(0x80+((value>>6)&0x3F)))
s = append(s, byte(0x80+(value&0x3F)))
}
// Advance the pointer.
for k := 0; k < code_length; k++ {
skip(parser)
}
}
} else {
// It is a non-escaped non-blank character.
s = read(parser, s)
}
if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) {
return false
}
}
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false
}
// Check if we are at the end of the scalar.
if single {
if parser.buffer[parser.buffer_pos] == '\'' {
break
}
} else {
if parser.buffer[parser.buffer_pos] == '"' {
break
}
}
// Consume blank characters.
for is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos) {
if is_blank(parser.buffer, parser.buffer_pos) {
// Consume a space or a tab character.
if !leading_blanks {
whitespaces = read(parser, whitespaces)
} else {
skip(parser)
}
} else {
if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) {
return false
}
// Check if it is a first line break.
if !leading_blanks {
whitespaces = whitespaces[:0]
leading_break = read_line(parser, leading_break)
leading_blanks = true
} else {
trailing_breaks = read_line(parser, trailing_breaks)
}
}
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false
}
}
// Join the whitespaces or fold line breaks.
if leading_blanks {
// Do we need to fold line breaks?
if len(leading_break) > 0 && leading_break[0] == '\n' {
if len(trailing_breaks) == 0 {
s = append(s, ' ')
} else {
s = append(s, trailing_breaks...)
}
} else {
s = append(s, leading_break...)
s = append(s, trailing_breaks...)
}
trailing_breaks = trailing_breaks[:0]
leading_break = leading_break[:0]
} else {
s = append(s, whitespaces...)
whitespaces = whitespaces[:0]
}
}
// Eat the right quote.
skip(parser)
end_mark := parser.mark
// Create a token.
*token = yaml_token_t{
typ: yaml_SCALAR_TOKEN,
start_mark: start_mark,
end_mark: end_mark,
value: s,
style: yaml_SINGLE_QUOTED_SCALAR_STYLE,
}
if !single {
token.style = yaml_DOUBLE_QUOTED_SCALAR_STYLE
}
return true
}
// Scan a plain scalar.
func yaml_parser_scan_plain_scalar(parser *yaml_parser_t, token *yaml_token_t) bool {
var s, leading_break, trailing_breaks, whitespaces []byte
var leading_blanks bool
var indent = parser.indent + 1
start_mark := parser.mark
end_mark := parser.mark
// Consume the content of the plain scalar.
for {
// Check for a document indicator.
if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) {
return false
}
if parser.mark.column == 0 &&
((parser.buffer[parser.buffer_pos+0] == '-' &&
parser.buffer[parser.buffer_pos+1] == '-' &&
parser.buffer[parser.buffer_pos+2] == '-') ||
(parser.buffer[parser.buffer_pos+0] == '.' &&
parser.buffer[parser.buffer_pos+1] == '.' &&
parser.buffer[parser.buffer_pos+2] == '.')) &&
is_blankz(parser.buffer, parser.buffer_pos+3) {
break
}
// Check for a comment.
if parser.buffer[parser.buffer_pos] == '#' {
break
}
// Consume non-blank characters.
for !is_blankz(parser.buffer, parser.buffer_pos) {
// Check for indicators that may end a plain scalar.
if (parser.buffer[parser.buffer_pos] == ':' && is_blankz(parser.buffer, parser.buffer_pos+1)) ||
(parser.flow_level > 0 &&
(parser.buffer[parser.buffer_pos] == ',' ||
parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == '[' ||
parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '{' ||
parser.buffer[parser.buffer_pos] == '}')) {
break
}
// Check if we need to join whitespaces and breaks.
if leading_blanks || len(whitespaces) > 0 {
if leading_blanks {
// Do we need to fold line breaks?
if leading_break[0] == '\n' {
if len(trailing_breaks) == 0 {
s = append(s, ' ')
} else {
s = append(s, trailing_breaks...)
}
} else {
s = append(s, leading_break...)
s = append(s, trailing_breaks...)
}
trailing_breaks = trailing_breaks[:0]
leading_break = leading_break[:0]
leading_blanks = false
} else {
s = append(s, whitespaces...)
whitespaces = whitespaces[:0]
}
}
// Copy the character.
s = read(parser, s)
end_mark = parser.mark
if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) {
return false
}
}
// Is it the end?
if !(is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos)) {
break
}
// Consume blank characters.
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false
}
for is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos) {
if is_blank(parser.buffer, parser.buffer_pos) {
// Check for tab characters that abuse indentation.
if leading_blanks && parser.mark.column < indent && is_tab(parser.buffer, parser.buffer_pos) {
yaml_parser_set_scanner_error(parser, "while scanning a plain scalar",
start_mark, "found a tab character that violates indentation")
return false
}
// Consume a space or a tab character.
if !leading_blanks {
whitespaces = read(parser, whitespaces)
} else {
skip(parser)
}
} else {
if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) {
return false
}
// Check if it is a first line break.
if !leading_blanks {
whitespaces = whitespaces[:0]
leading_break = read_line(parser, leading_break)
leading_blanks = true
} else {
trailing_breaks = read_line(parser, trailing_breaks)
}
}
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false
}
}
// Check indentation level.
if parser.flow_level == 0 && parser.mark.column < indent {
break
}
}
// Create a token.
*token = yaml_token_t{
typ: yaml_SCALAR_TOKEN,
start_mark: start_mark,
end_mark: end_mark,
value: s,
style: yaml_PLAIN_SCALAR_STYLE,
}
// Note that we change the 'simple_key_allowed' flag.
if leading_blanks {
parser.simple_key_allowed = true
}
return true
}
func yaml_parser_scan_line_comment(parser *yaml_parser_t, token_mark yaml_mark_t) bool {
if parser.newlines > 0 {
return true
}
var start_mark yaml_mark_t
var text []byte
for peek := 0; peek < 512; peek++ {
if parser.unread < peek+1 && !yaml_parser_update_buffer(parser, peek+1) {
break
}
if is_blank(parser.buffer, parser.buffer_pos+peek) {
continue
}
if parser.buffer[parser.buffer_pos+peek] == '#' {
seen := parser.mark.index+peek
for {
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false
}
if is_breakz(parser.buffer, parser.buffer_pos) {
if parser.mark.index >= seen {
break
}
if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) {
return false
}
skip_line(parser)
} else {
if parser.mark.index >= seen {
if len(text) == 0 {
start_mark = parser.mark
}
text = append(text, parser.buffer[parser.buffer_pos])
}
skip(parser)
}
}
}
break
}
if len(text) > 0 {
parser.comments = append(parser.comments, yaml_comment_t{
token_mark: token_mark,
start_mark: start_mark,
line: text,
})
}
return true
}
func yaml_parser_scan_comments(parser *yaml_parser_t, scan_mark yaml_mark_t) bool {
token := parser.tokens[len(parser.tokens)-1]
if token.typ == yaml_FLOW_ENTRY_TOKEN && len(parser.tokens) > 1 {
token = parser.tokens[len(parser.tokens)-2]
}
var token_mark = token.start_mark
var start_mark yaml_mark_t
var recent_empty = false
var first_empty = parser.newlines <= 1
var line = parser.mark.line
var column = parser.mark.column
var text []byte
// The foot line is the place where a comment must start to
// still be considered as a foot of the prior content.
// If there's some content in the currently parsed line, then
// the foot is the line below it.
var foot_line = -1
if scan_mark.line > 0 {
foot_line = parser.mark.line-parser.newlines+1
if parser.newlines == 0 && parser.mark.column > 1 {
foot_line++
}
}
var peek = 0
for ; peek < 512; peek++ {
if parser.unread < peek+1 && !yaml_parser_update_buffer(parser, peek+1) {
break
}
column++
if is_blank(parser.buffer, parser.buffer_pos+peek) {
continue
}
c := parser.buffer[parser.buffer_pos+peek]
if is_breakz(parser.buffer, parser.buffer_pos+peek) || parser.flow_level > 0 && (c == ']' || c == '}') {
// Got line break or terminator.
if !recent_empty {
if first_empty && (start_mark.line == foot_line || start_mark.column-1 < parser.indent) {
// This is the first empty line and there were no empty lines before,
// so this initial part of the comment is a foot of the prior token
// instead of being a head for the following one. Split it up.
if len(text) > 0 {
if start_mark.column-1 < parser.indent {
// If dedented it's unrelated to the prior token.
token_mark = start_mark
}
parser.comments = append(parser.comments, yaml_comment_t{
scan_mark: scan_mark,
token_mark: token_mark,
start_mark: start_mark,
end_mark: yaml_mark_t{parser.mark.index + peek, line, column},
foot: text,
})
scan_mark = yaml_mark_t{parser.mark.index + peek, line, column}
token_mark = scan_mark
text = nil
}
} else {
if len(text) > 0 && parser.buffer[parser.buffer_pos+peek] != 0 {
text = append(text, '\n')
}
}
}
if !is_break(parser.buffer, parser.buffer_pos+peek) {
break
}
first_empty = false
recent_empty = true
column = 0
line++
continue
}
if len(text) > 0 && column < parser.indent+1 && column != start_mark.column {
// The comment at the different indentation is a foot of the
// preceding data rather than a head of the upcoming one.
parser.comments = append(parser.comments, yaml_comment_t{
scan_mark: scan_mark,
token_mark: token_mark,
start_mark: start_mark,
end_mark: yaml_mark_t{parser.mark.index + peek, line, column},
foot: text,
})
scan_mark = yaml_mark_t{parser.mark.index + peek, line, column}
token_mark = scan_mark
text = nil
}
if parser.buffer[parser.buffer_pos+peek] != '#' {
break
}
if len(text) == 0 {
start_mark = yaml_mark_t{parser.mark.index + peek, line, column}
} else {
text = append(text, '\n')
}
recent_empty = false
// Consume until after the consumed comment line.
seen := parser.mark.index+peek
for {
if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) {
return false
}
if is_breakz(parser.buffer, parser.buffer_pos) {
if parser.mark.index >= seen {
break
}
if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) {
return false
}
skip_line(parser)
} else if parser.mark.index >= seen {
text = read(parser, text)
} else {
skip(parser)
}
}
peek = 0
column = 0
line = parser.mark.line
}
if len(text) > 0 {
parser.comments = append(parser.comments, yaml_comment_t{
scan_mark: scan_mark,
token_mark: start_mark,
start_mark: start_mark,
end_mark: yaml_mark_t{parser.mark.index + peek - 1, line, column},
head: text,
})
}
return true
}
| mit |
stues/camel-sensor-routes | transmitter-route/sos/src/main/java/ch/stue/transmitter/sos/converter/FeatureToInsertObservationConverter.java | 1527 | package ch.stue.transmitter.sos.converter;
import javax.xml.bind.JAXBElement;
import org.apache.camel.BeanInject;
import org.apache.camel.Converter;
import org.apache.camel.RuntimeCamelException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.stue.domain.Feature;
import ch.stue.transmitter.sos.converter.insertobservation.InsertObservationJAXBHelper;
import ch.stue.transmitter.sos.converter.insertobservation.InsertObservationSOSV2Configuration;
import net.opengis.sos.v_2_0_0.InsertObservationType;
/**
* Converts a {@link Feature} to a {@link JAXBElement} which represents a
* Insert Observation
*
* @author stue
*/
@Converter
public class FeatureToInsertObservationConverter {
private static final Logger LOGGER = LoggerFactory.getLogger(FeatureToInsertObservationConverter.class);
@BeanInject("sosConfiguration")
private SOSConfiguration sosConfiguration;
/**
* converts the {@link Feature} into a {@link JAXBElement}
*
* @param feature
* @return
*/
@Converter(allowNull = true)
public JAXBElement<InsertObservationType> convert(Feature<?> feature) {
InsertObservationSOSV2Configuration configuration = this.sosConfiguration.getConfiguration(feature);
if(configuration != null){
return InsertObservationJAXBHelper.getInsertObservation(configuration, feature);
}
else{
String warnMessage = String.format("No SOS configuration has been found for the Feature: %s", feature);
LOGGER.warn(warnMessage);
throw new RuntimeCamelException(warnMessage);
}
}
}
| mit |
o2ocoin/o2ocoin | src/qt/locale/bitcoin_el_GR.ts | 138075 | <?xml version="1.0" ?><!DOCTYPE TS><TS language="el_GR" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About O2ocoin</source>
<translation>Σχετικά με το O2ocoin</translation>
</message>
<message>
<location line="+39"/>
<source><b>O2ocoin</b> version</source>
<translation>Έκδοση O2ocoin</translation>
</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>
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.</translation>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation>Πνευματική ιδιοκτησία </translation>
</message>
<message>
<location line="+0"/>
<source>The O2ocoin developers</source>
<translation>Οι O2ocoin προγραμματιστές </translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Βιβλίο Διευθύνσεων</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>Διπλό-κλικ για επεξεργασία της διεύθυνσης ή της ετικέτας</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Δημιούργησε νέα διεύθυνση</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Αντέγραψε την επιλεγμένη διεύθυνση στο πρόχειρο του συστήματος</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&Νέα διεύθυνση</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your O2ocoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation>Αυτές είναι οι O2ocoin διευθύνσεις σας για να λαμβάνετε πληρωμές. Δίνοντας μία ξεχωριστή διεύθυνση σε κάθε αποστολέα, θα μπορείτε να ελέγχετε ποιος σας πληρώνει.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation>&Αντιγραφή διεύθυνσης</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>Δείξε &QR κωδικα</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a O2ocoin address</source>
<translation>Υπογράψτε ένα μήνυμα για ν' αποδείξετε πως σας ανήκει μια συγκεκριμένη διεύθυνση O2ocoin</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>&Υπέγραψε το μήνυμα</translation>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation>Αντιγραφη της επιλεγμενης διεύθυνσης στο πρόχειρο του συστηματος</translation>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation>Εξαγωγή δεδομένων καρτέλας σε αρχείο</translation>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation>&Εξαγωγή</translation>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified O2ocoin address</source>
<translation>Υπογράψτε ένα μήνυμα για ν' αποδείξετε πως ανήκει μια συγκεκριμένη διεύθυνση O2ocoin</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>&Επιβεβαίωση μηνύματος</translation>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Διαγραφή</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your O2ocoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation>Αυτές είναι οι O2ocoin διευθύνσεις σας για να λαμβάνετε πληρωμές. Δίνοντας μία ξεχωριστή διεύθυνση σε κάθε αποστολέα, θα μπορείτε να ελέγχετε ποιος σας πληρώνει.</translation>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation>Αντιγραφή &επιγραφής</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>&Επεξεργασία</translation>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation>Αποστολή νομισμάτων</translation>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>Εξαγωγή Δεδομενων Βιβλίου Διευθύνσεων</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Αρχείο οριοθετημένο με κόμματα (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Εξαγωγή λαθών</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Αδυναμία εγγραφής στο αρχείο %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Ετικέτα</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Διεύθυνση</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(χωρίς ετικέτα)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Φράση πρόσβασης </translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Βάλτε κωδικό πρόσβασης</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Νέος κωδικός πρόσβασης</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Επανέλαβε τον νέο κωδικό πρόσβασης</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+33"/>
<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>Εισάγετε τον νέο κωδικό πρόσβασης στον πορτοφόλι <br/> Παρακαλώ χρησιμοποιείστε ένα κωδικό με <b> 10 ή περισσότερους τυχαίους χαρακτήρες</b> ή <b> οχτώ ή παραπάνω λέξεις</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Κρυπτογράφησε το πορτοφόλι</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Αυτη η ενεργεία χρειάζεται τον κωδικό του πορτοφολιού για να ξεκλειδώσει το πορτοφόλι.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Ξεκλειδωσε το πορτοφολι</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Αυτη η ενεργεια χρειάζεται τον κωδικο του πορτοφολιου για να αποκρυπτογραφησειι το πορτοφολι.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Αποκρυπτογράφησε το πορτοφολι</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Άλλαξε κωδικο πρόσβασης</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Εισάγετε τον παλιό και τον νεο κωδικο στο πορτοφολι.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Επιβεβαίωσε την κρυπτογραφηση του πορτοφολιού</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR O2OCOINS</b>!</source>
<translation>Προσοχη: Εαν κρυπτογραφησεις το πορτοφολι σου και χάσεις τον κωδικο σου θα χάσεις <b> ΟΛΑ ΣΟΥ ΤΑ O2OCOINS</b>!
Είσαι σίγουρος ότι θέλεις να κρυπτογραφησεις το πορτοφολι;</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Είστε σίγουροι ότι θέλετε να κρυπτογραφήσετε το πορτοφόλι σας;</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation>ΣΗΜΑΝΤΙΚΟ: Τα προηγούμενα αντίγραφα ασφαλείας που έχετε κάνει από το αρχείο του πορτοφόλιου σας θα πρέπει να αντικατασταθουν με το νέο που δημιουργείται, κρυπτογραφημένο αρχείο πορτοφόλιου. Για λόγους ασφαλείας, τα προηγούμενα αντίγραφα ασφαλείας του μη κρυπτογραφημένου αρχείου πορτοφόλιου θα καταστουν άχρηστα μόλις αρχίσετε να χρησιμοποιείτε το νέο κρυπτογραφημένο πορτοφόλι. </translation>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Προσοχη: το πλήκτρο Caps Lock είναι ενεργο.</translation>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>Κρυπτογραφημενο πορτοφολι</translation>
</message>
<message>
<location line="-56"/>
<source>O2ocoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your o2ocoins from being stolen by malware infecting your computer.</source>
<translation>Το O2ocoin θα κλεισει τώρα για να τελειώσει την διαδικασία κρυπτογραφησης. Θυμησου ότι κρυπτογραφώντας το πορτοφολι σου δεν μπορείς να προστατέψεις πλήρως τα o2ocoins σου από κλοπή στην περίπτωση όπου μολυνθεί ο υπολογιστής σου με κακόβουλο λογισμικο.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Η κρυπτογραφηση του πορτοφολιού απέτυχε</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Η κρυπτογράφηση του πορτοφολιού απέτυχε λογω εσωτερικού σφάλματος. Το πορτοφολι δεν κρυπτογραφηθηκε.</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>Οι εισαχθέντες κωδικοί δεν ταιριάζουν.</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>το ξεκλείδωμα του πορτοφολιού απέτυχε</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Ο κωδικος που εισήχθη για την αποκρυπτογραφηση του πορτοφολιού ήταν λαθος.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Η αποκρυπτογραφηση του πορτοφολιού απέτυχε</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Ο κωδικος του πορτοφολιού άλλαξε με επιτυχία.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation>Υπογραφή &Μηνύματος...</translation>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>Συγχρονισμός με το δίκτυο...</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>&Επισκόπηση</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Εμφάνισε γενική εικονα του πορτοφολιού</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>&Συναλλαγές</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Περιήγηση στο ιστορικο συνναλαγων</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Εξεργασια της λιστας των αποθηκευμενων διευθύνσεων και ετικετων</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Εμφάνισε την λίστα των διευθύνσεων για την παραλαβή πληρωμων</translation>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>Έ&ξοδος</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Εξοδος από την εφαρμογή</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about O2ocoin</source>
<translation>Εμφάνισε πληροφορίες σχετικά με το O2ocoin</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>Σχετικά με &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Εμφάνισε πληροφορίες σχετικά με Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Επιλογές...</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation>&Κρυπτογράφησε το πορτοφόλι</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>&Αντίγραφο ασφαλείας του πορτοφολιού</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Άλλαξε κωδικο πρόσβασης</translation>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation>Εισαγωγή μπλοκ από τον σκληρο δίσκο ... </translation>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation>Φόρτωση ευρετηρίου μπλοκ στον σκληρο δισκο...</translation>
</message>
<message>
<location line="-347"/>
<source>Send coins to a O2ocoin address</source>
<translation>Στείλε νομισματα σε μια διεύθυνση o2ocoin</translation>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for O2ocoin</source>
<translation>Επεργασία ρυθμισεων επιλογών για το O2ocoin</translation>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation>Δημιουργία αντιγράφου ασφαλείας πορτοφολιού σε άλλη τοποθεσία</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Αλλαγή του κωδικού κρυπτογράφησης του πορτοφολιού</translation>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation>&Παράθυρο αποσφαλμάτωσης</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Άνοιγμα κονσόλας αποσφαλμάτωσης και διαγνωστικών</translation>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation>&Επιβεβαίωση μηνύματος</translation>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>O2ocoin</source>
<translation>O2ocoin</translation>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation>Πορτοφόλι</translation>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation>&Αποστολή</translation>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation>&Παραλαβή </translation>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation>&Διεύθυνσεις</translation>
</message>
<message>
<location line="+22"/>
<source>&About O2ocoin</source>
<translation>&Σχετικα:O2ocoin</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&Εμφάνισε/Κρύψε</translation>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation>Εμφάνιση ή αποκρύψη του κεντρικου παράθυρου </translation>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation>Κρυπτογραφήστε τα ιδιωτικά κλειδιά που ανήκουν στο πορτοφόλι σας </translation>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your O2ocoin addresses to prove you own them</source>
<translation>Υπογράψτε ένα μήνυμα για να βεβαιώσετε πως είστε ο κάτοχος αυτής της διεύθυνσης</translation>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified O2ocoin addresses</source>
<translation>Υπογράψτε ένα μήνυμα για ν' αποδείξετε πως ανήκει μια συγκεκριμένη διεύθυνση O2ocoin</translation>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>&Αρχείο</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>&Ρυθμίσεις</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>&Βοήθεια</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>Εργαλειοθήκη καρτελών</translation>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location line="+47"/>
<source>O2ocoin client</source>
<translation>Πελάτης O2ocoin</translation>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to O2ocoin network</source>
<translation><numerusform>%n ενεργή σύνδεση στο δίκτυο O2ocoin</numerusform><numerusform>%n ενεργές συνδέσεις στο δίκτυο Βitcoin</numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation>Η πηγή του μπλοκ δεν ειναι διαθέσιμη... </translation>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation>Μεταποιημένα %1 απο % 2 (κατ 'εκτίμηση) μπλοκ της ιστορίας της συναλλαγής. </translation>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation>Έγινε λήψη %1 μπλοκ ιστορικού συναλλαγών</translation>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation><numerusform>%n ώρες </numerusform><numerusform>%n ώρες </numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation><numerusform>%n ημέρες </numerusform><numerusform>%n ημέρες </numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation><numerusform>%n εβδομαδες</numerusform><numerusform>%n εβδομαδες</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation>%1 πίσω</translation>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation>Το τελευταίο μπλοκ που ελήφθη δημιουργήθηκε %1 πριν.</translation>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation>Οι συναλλαγές μετά από αυτό δεν θα είναι ακόμη ορατες.</translation>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation>Σφάλμα</translation>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation>Προειδοποίηση</translation>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation>Πληροφορία</translation>
</message>
<message>
<location line="+70"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation>Η συναλλαγή ξεπερνάει το όριο.
Μπορεί να ολοκληρωθεί με μια αμοιβή των %1, η οποία αποδίδεται στους κόμβους που επεξεργάζονται τις συναλλαγές και βοηθούν στην υποστήριξη του δικτύου.
Θέλετε να συνεχίσετε;</translation>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation>Ενημερωμένο</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation>Ενημέρωση...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation>Επιβεβαίωση αμοιβής συναλλαγής</translation>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>Η συναλλαγή απεστάλη</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>Εισερχόμενη συναλλαγή</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Ημερομηνία: %1
Ποσό: %2
Τύπος: %3
Διεύθυνση: %4
</translation>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation>Χειρισμός URI</translation>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid O2ocoin address or malformed URI parameters.</source>
<translation>Το URI δεν μπορεί να αναλυθεί! Αυτό μπορεί να προκληθεί από μια μη έγκυρη διεύθυνση O2ocoin ή ακατάλληλη παραμέτρο URI.</translation>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Το πορτοφόλι είναι <b>κρυπτογραφημένο</b> και <b>ξεκλείδωτο</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Το πορτοφόλι είναι <b>κρυπτογραφημένο</b> και <b>κλειδωμένο</b></translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. O2ocoin can no longer continue safely and will quit.</source>
<translation>Παρουσιάστηκε ανεπανόρθωτο σφάλμα. Το O2ocoin δεν μπορεί πλέον να συνεχίσει με ασφάλεια και θα τερματισθει.</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation>Ειδοποίηση Δικτύου</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Επεξεργασία Διεύθυνσης</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Επιγραφή</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>Η επιγραφή που σχετίζεται με αυτή την καταχώρηση του βιβλίου διευθύνσεων</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Διεύθυνση</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>Η διεύθυνση που σχετίζεται με αυτή την καταχώρηση του βιβλίου διευθύνσεων. Μπορεί να τροποποιηθεί μόνο για τις διευθύνσεις αποστολής.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>Νέα διεύθυνση λήψης</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Νέα διεύθυνση αποστολής</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Επεξεργασία διεύθυνσης λήψης</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Επεξεργασία διεύθυνσης αποστολής</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Η διεύθυνση "%1" βρίσκεται ήδη στο βιβλίο διευθύνσεων.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid O2ocoin address.</source>
<translation>Η διεύθυνση "%1" δεν είναι έγκυρη O2ocoin διεύθυνση.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Δεν είναι δυνατό το ξεκλείδωμα του πορτοφολιού.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Η δημιουργία νέου κλειδιού απέτυχε.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>O2ocoin-Qt</source>
<translation>o2ocoin-qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>έκδοση</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Χρήση:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>επιλογής γραμμής εντολών</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>επιλογές UI</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Όρισε γλώσσα, για παράδειγμα "de_DE"(προεπιλογή:τοπικές ρυθμίσεις)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Έναρξη ελαχιστοποιημένο</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>Εμφάνισε την οθόνη εκκίνησης κατά την εκκίνηση(προεπιλογή:1)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Ρυθμίσεις</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Κύριο</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source>
<translation>Η προαιρετική αμοιβή για κάθε kB επισπεύδει την επεξεργασία των συναλλαγών σας. Οι περισσότερες συναλλαγές είναι 1 kB. </translation>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Αμοιβή &συναλλαγής</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start O2ocoin after logging in to the system.</source>
<translation>Αυτόματη εκκίνηση του O2ocoin μετά την εισαγωγή στο σύστημα</translation>
</message>
<message>
<location line="+3"/>
<source>&Start O2ocoin on system login</source>
<translation>&Έναρξη του Βιtcoin κατά την εκκίνηση του συστήματος</translation>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation>Επαναφορα όλων των επιλογων του πελάτη σε default.</translation>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation>Επαναφορα ρυθμίσεων</translation>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation>&Δίκτυο</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the O2ocoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Αυτόματο άνοιγμα των θυρών O2ocoin στον δρομολογητή. Λειτουργεί μόνο αν ο δρομολογητής σας υποστηρίζει τη λειτουργία UPnP.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Απόδοση θυρών με χρήστη &UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the O2ocoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>Σύνδεση στο O2ocoin δίκτυο μέσω διαμεσολαβητή SOCKS4 (π.χ. για σύνδεση μέσω Tor)</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>&Σύνδεση μέσω διαμεσολαβητή SOCKS</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>&IP διαμεσολαβητή:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>Διεύθυνση IP του διαμεσολαβητή (π.χ. 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Θύρα:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Θύρα διαμεσολαβητή</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>SOCKS &Έκδοση:</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>SOCKS εκδοση του διαμεσολαβητη (e.g. 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Παράθυρο</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Εμφάνιση μόνο εικονιδίου στην περιοχή ειδοποιήσεων κατά την ελαχιστοποίηση</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Ελαχιστοποίηση στην περιοχή ειδοποιήσεων αντί της γραμμής εργασιών</translation>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>Ελαχιστοποίηση αντί για έξοδο κατά το κλείσιμο του παραθύρου</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>Ε&λαχιστοποίηση κατά το κλείσιμο</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>%Απεικόνιση</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>Γλώσσα περιβάλλοντος εργασίας: </translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting O2ocoin.</source>
<translation>Εδώ μπορεί να ρυθμιστεί η γλώσσα διεπαφής χρήστη. Αυτή η ρύθμιση θα ισχύσει μετά την επανεκκίνηση του O2ocoin.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Μονάδα μέτρησης:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Διαλέξτε την προεπιλεγμένη υποδιαίρεση που θα εμφανίζεται όταν στέλνετε νομίσματα.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show O2ocoin addresses in the transaction list or not.</source>
<translation>Επιλέξτε αν θέλετε να εμφανίζονται οι διευθύνσεις O2ocoin στη λίστα συναλλαγών.</translation>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>Εμφάνιση διευθύνσεων στη λίστα συναλλαγών</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&ΟΚ</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Ακύρωση</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>&Εφαρμογή</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation>προεπιλογή</translation>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation>Επιβεβαιώση των επιλογων επαναφοράς </translation>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation>Για ορισμένες ρυθμίσεις πρεπει η επανεκκίνηση να τεθεί σε ισχύ.</translation>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation>Θέλετε να προχωρήσετε;</translation>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation>Προειδοποίηση</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting O2ocoin.</source>
<translation>Αυτή η ρύθμιση θα ισχύσει μετά την επανεκκίνηση του O2ocoin.</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>Δεν είναι έγκυρη η διεύθυνση διαμεσολαβητή</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Φόρμα</translation>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the O2ocoin network after a connection is established, but this process has not completed yet.</source>
<translation>Οι πληροφορίες που εμφανίζονται μπορεί να είναι ξεπερασμένες. Το πορτοφόλι σας συγχρονίζεται αυτόματα με το δίκτυο O2ocoin μετά από μια σύνδεση, αλλά αυτή η διαδικασία δεν έχει ακόμη ολοκληρωθεί. </translation>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation>Υπόλοιπο</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>Ανεπιβεβαίωτες</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>Πορτοφόλι</translation>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation>Ανώριμος</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>Εξορυγμενο υπόλοιπο που δεν έχει ακόμα ωριμάσει </translation>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Πρόσφατες συναλλαγές</b></translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation>Το τρέχον υπόλοιπο</translation>
</message>
<message>
<location line="+29"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>Το άθροισμα των συναλλαγών που δεν έχουν ακόμα επιβεβαιωθεί και δεν προσμετρώνται στο τρέχον υπόλοιπό σας</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation>εκτός συγχρονισμού</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start o2ocoin: click-to-pay handler</source>
<translation>Δεν είναι δυνατή η εκκίνηση του O2ocoin: click-to-pay handler</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>Κώδικας QR</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Αίτηση πληρωμής</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Ποσό:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Επιγραφή:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Μήνυμα:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&Αποθήκευση ως...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>Σφάλμα κατά την κωδικοποίηση του URI σε κώδικα QR</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>Το αναγραφόμενο ποσό δεν είναι έγκυρο, παρακαλούμε να το ελέγξετε.</translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>Το αποτέλεσμα της διεύθυνσης είναι πολύ μεγάλο. Μειώστε το μέγεθος για το κείμενο της ετικέτας/ μηνύματος.</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>Αποθήκευση κώδικα QR</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>Εικόνες PNG (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Όνομα Πελάτη</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+339"/>
<source>N/A</source>
<translation>Μη διαθέσιμο</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>Έκδοση Πελάτη</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Πληροφορία</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Χρησιμοποιηση της OpenSSL εκδοσης</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Χρόνος εκκίνησης</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Δίκτυο</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Αριθμός συνδέσεων</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>Στο testnet</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>αλυσίδα εμποδισμού</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Τρέχον αριθμός μπλοκ</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>Κατ' εκτίμηση συνολικά μπλοκς</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Χρόνος τελευταίου μπλοκ</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Άνοιγμα</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>επιλογής γραμμής εντολών</translation>
</message>
<message>
<location line="+7"/>
<source>Show the O2ocoin-Qt help message to get a list with possible O2ocoin command-line options.</source>
<translation>Εμφανιση του O2ocoin-Qt μήνυματος βοήθειας για να πάρετε μια λίστα με τις πιθανές επιλογές O2ocoin γραμμής εντολών.</translation>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>&Εμφάνιση</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Κονσόλα</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>Ημερομηνία κατασκευής</translation>
</message>
<message>
<location line="-104"/>
<source>O2ocoin - Debug window</source>
<translation>O2ocoin - Παράθυρο αποσφαλμάτωσης</translation>
</message>
<message>
<location line="+25"/>
<source>O2ocoin Core</source>
<translation>O2ocoin Core</translation>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation>Αρχείο καταγραφής εντοπισμού σφαλμάτων </translation>
</message>
<message>
<location line="+7"/>
<source>Open the O2ocoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation>Ανοίξτε το αρχείο καταγραφής εντοπισμού σφαλμάτων από τον τρέχοντα κατάλογο δεδομένων. Αυτό μπορεί να πάρει μερικά δευτερόλεπτα για τα μεγάλα αρχεία καταγραφής. </translation>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Καθαρισμός κονσόλας</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the O2ocoin RPC console.</source>
<translation>Καλώς ήρθατε στην O2ocoin RPC κονσόλα.</translation>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Χρησιμοποιήστε το πάνω και κάτω βέλος για να περιηγηθείτε στο ιστορικο, και <b>Ctrl-L</b> για εκκαθαριση οθονης.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Γράψτε <b>βοήθεια</b> για μια επισκόπηση των διαθέσιμων εντολών</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+124"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Αποστολή νομισμάτων</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>Αποστολή σε πολλούς αποδέκτες ταυτόχρονα</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>&Προσθήκη αποδέκτη</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>Διαγραφή όλων των πεδίων συναλλαγής</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>Καθαρισμός &Όλων</translation>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>Υπόλοιπο:</translation>
</message>
<message>
<location line="+10"/>
<source>123.456 BTC</source>
<translation>123,456 BTC</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Επιβεβαίωση αποστολής</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>Αποστολη</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> σε %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Επιβεβαίωση αποστολής νομισμάτων</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>Είστε βέβαιοι για την αποστολή %1;</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation>και</translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>Η διεύθυνση του αποδέκτη δεν είναι σωστή. Παρακαλώ ελέγξτε ξανά.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Το ποσό πληρωμής πρέπει να είναι μεγαλύτερο από 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>Το ποσό ξεπερνάει το διαθέσιμο υπόλοιπο</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Το σύνολο υπερβαίνει το υπόλοιπό σας όταν συμπεριληφθεί και η αμοιβή %1</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Βρέθηκε η ίδια διεύθυνση δύο φορές. Επιτρέπεται μία μόνο εγγραφή για κάθε διεύθυνση, σε κάθε διαδικασία αποστολής.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation>Σφάλμα: Η δημιουργία της συναλλαγής απέτυχε</translation>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Σφάλμα: Η συναλλαγή απερρίφθη. Αυτό ενδέχεται να συμβαίνει αν κάποια από τα νομίσματα έχουν ήδη ξοδευθεί, όπως αν χρησιμοποιήσατε αντίγραφο του wallet.dat και τα νομίσματα ξοδεύθηκαν εκεί.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Φόρμα</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>&Ποσό:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>Πληρωμή &σε:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. Qi1NooNjQySQLDJ643HWfZZ7UN2EmLEvix)</source>
<translation>Διεύθυνση αποστολής της πληρωμής (e.g. Qi1NooNjQySQLDJ643HWfZZ7UN2EmLEvix)</translation>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Εισάγετε μια επιγραφή για αυτή τη διεύθυνση ώστε να καταχωρηθεί στο βιβλίο διευθύνσεων</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>&Επιγραφή</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>Επιλογή διεύθυνσης από το βιβλίο διευθύνσεων</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Επικόλληση διεύθυνσης από το πρόχειρο</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation>Αφαίρεση αποδέκτη</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a O2ocoin address (e.g. Qi1NooNjQySQLDJ643HWfZZ7UN2EmLEvix)</source>
<translation>Εισάγετε μια διεύθυνση O2ocoin (π.χ. Qi1NooNjQySQLDJ643HWfZZ7UN2EmLEvix)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>Υπογραφές - Είσοδος / Επαλήθευση μήνυματος </translation>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation>&Υπογραφή Μηνύματος</translation>
</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>Μπορείτε να υπογράφετε μηνύματα με τις διευθύνσεις σας, ώστε ν' αποδεικνύετε πως αυτές σας ανήκουν. Αποφεύγετε να υπογράφετε κάτι αόριστο καθώς ενδέχεται να εξαπατηθείτε. Υπογράφετε μόνο πλήρης δηλώσεις με τις οποίες συμφωνείτε.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. Qi1NooNjQySQLDJ643HWfZZ7UN2EmLEvix)</source>
<translation>Εισάγετε μια διεύθυνση O2ocoin (π.χ. Qi1NooNjQySQLDJ643HWfZZ7UN2EmLEvix)</translation>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation>Επιλογή διεύθυνσης από το βιβλίο διευθύνσεων</translation>
</message>
<message>
<location line="-203"/>
<location line="+213"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-203"/>
<source>Paste address from clipboard</source>
<translation>Επικόλληση διεύθυνσης από το βιβλίο διευθύνσεων</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation>Εισάγετε εδώ το μήνυμα που θέλετε να υπογράψετε</translation>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation>Υπογραφή</translation>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Αντέγραφη της επιλεγμενης διεύθυνσης στο πρόχειρο του συστηματος</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this O2ocoin address</source>
<translation>Υπογράψτε ένα μήνυμα για ν' αποδείξετε πως σας ανήκει μια συγκεκριμένη διεύθυνση O2ocoin</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Υπογραφη μήνυματος</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation>Επαναφορά όλων των πεδίων μήνυματος</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>Καθαρισμός &Όλων</translation>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation>&Επιβεβαίωση μηνύματος</translation>
</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>Πληκτρολογήστε την υπογραφή διεύθυνσης, μήνυμα (βεβαιωθείτε ότι έχετε αντιγράψει τις αλλαγές γραμμής, κενά, tabs, κ.λπ. ακριβώς) και την υπογραφή παρακάτω, για να ελέγξει το μήνυμα. Να είστε προσεκτικοί για να μην διαβάσετε περισσότερα στην υπογραφή ό, τι είναι στην υπογραφή ίδιο το μήνυμα , για να μην εξαπατηθούν από έναν άνθρωπο -in - the-middle επίθεση.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. Qi1NooNjQySQLDJ643HWfZZ7UN2EmLEvix)</source>
<translation>Εισάγετε μια διεύθυνση O2ocoin (π.χ. Qi1NooNjQySQLDJ643HWfZZ7UN2EmLEvix)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified O2ocoin address</source>
<translation>Υπογράψτε ένα μήνυμα για ν' αποδείξετε πως υπογραφθηκε απο μια συγκεκριμένη διεύθυνση O2ocoin</translation>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation>Επιβεβαίωση μηνύματος</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation>Επαναφορά όλων επαλήθευμενων πεδίων μήνυματος </translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a O2ocoin address (e.g. Qi1NooNjQySQLDJ643HWfZZ7UN2EmLEvix)</source>
<translation>Εισάγετε μια διεύθυνση O2ocoin (π.χ. Qi1NooNjQySQLDJ643HWfZZ7UN2EmLEvix)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Κάντε κλικ στο "Υπογραφή Μηνύματος" για να λάβετε την υπογραφή</translation>
</message>
<message>
<location line="+3"/>
<source>Enter O2ocoin signature</source>
<translation>Εισαγωγή υπογραφής O2ocoin</translation>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>Η διεύθυνση που εισήχθη είναι λάθος.</translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>Παρακαλούμε ελέγξτε την διεύθυνση και δοκιμάστε ξανά.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>Η διεύθυνση που έχει εισαχθεί δεν αναφέρεται σε ένα πλήκτρο.</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>το ξεκλείδωμα του πορτοφολιού απέτυχε</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>Το προσωπικό κλειδί εισαγμενης διευθυνσης δεν είναι διαθέσιμο.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Η υπογραφή του μηνύματος απέτυχε.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Μήνυμα υπεγράφη.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>Η υπογραφή δεν μπόρεσε να αποκρυπτογραφηθεί.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>Παρακαλούμε ελέγξτε την υπογραφή και δοκιμάστε ξανά.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>Η υπογραφή δεν ταιριάζει με το μήνυμα. </translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>Η επιβεβαίωση του μηνύματος απέτυχε</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Μήνυμα επιβεβαιώθηκε.</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The O2ocoin developers</source>
<translation>Οι O2ocoin προγραμματιστές </translation>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>Ανοιχτό μέχρι %1</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation>%1/χωρίς σύνδεση;</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/χωρίς επιβεβαίωση</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 επιβεβαιώσεις</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>Κατάσταση</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>, έχει μεταδοθεί μέσω %n κόμβων</numerusform><numerusform>, έχει μεταδοθεί μέσω %n κόμβων</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Ημερομηνία</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Πηγή</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Δημιουργία </translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>Από</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>Προς</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation> δική σας διεύθυνση </translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>eπιγραφή</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Πίστωση </translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation><numerusform>ωρίμανση σε %n επιπλέον μπλοκ</numerusform><numerusform>ωρίμανση σε %n επιπλέον μπλοκ</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>μη αποδεκτό</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Debit</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Τέλος συναλλαγής </translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Καθαρό ποσό</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Μήνυμα</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Σχόλιο:</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>ID Συναλλαγής:</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 80 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>Πρέπει να περιμένετε 80 μπλοκ πριν μπορέσετε να χρησιμοποιήσετε τα νομίσματα που έχετε δημιουργήσει. Το μπλοκ που δημιουργήσατε μεταδόθηκε στο δίκτυο για να συμπεριληφθεί στην αλυσίδα των μπλοκ. Αν δεν μπει σε αυτή θα μετατραπεί σε "μη αποδεκτό" και δε θα μπορεί να καταναλωθεί. Αυτό συμβαίνει σπάνια όταν κάποιος άλλος κόμβος δημιουργήσει ένα μπλοκ λίγα δευτερόλεπτα πριν από εσάς.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Πληροφορίες αποσφαλμάτωσης</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Συναλλαγή</translation>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation>εισροές </translation>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Ποσό</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>αληθής</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>αναληθής </translation>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, δεν έχει ακόμα μεταδοθεί μ' επιτυχία</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Ανοιχτό για %n μπλοκ</numerusform><numerusform>Ανοιχτό για %n μπλοκ</numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>άγνωστο</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Λεπτομέρειες συναλλαγής</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Αυτό το παράθυρο δείχνει μια λεπτομερή περιγραφή της συναλλαγής</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>Ημερομηνία</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Τύπος</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Διεύθυνση</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Ποσό</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Ανοιχτό για %n μπλοκ</numerusform><numerusform>Ανοιχτό για %n μπλοκ</numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>Ανοιχτό μέχρι %1</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>Χωρίς σύνδεση (%1 επικυρώσεις)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>Χωρίς επιβεβαίωση (%1 από %2 επικυρώσεις)</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Επικυρωμένη (%1 επικυρώσεις)</translation>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation><numerusform>Το υπόλοιπο από την εξόρυξη θα είναι διαθέσιμο μετά από %n μπλοκ</numerusform><numerusform>Το υπόλοιπο από την εξόρυξη θα είναι διαθέσιμο μετά από %n μπλοκ</numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Αυτό το μπλοκ δεν έχει παραληφθεί από κανέναν άλλο κόμβο και κατά πάσα πιθανότητα θα απορριφθεί!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Δημιουργήθηκε αλλά απορρίφθηκε</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>Παραλαβή με</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Ελήφθη από</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Αποστολή προς</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Πληρωμή προς εσάς</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Εξόρυξη</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(δ/α)</translation>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Κατάσταση συναλλαγής. Πηγαίνετε το ποντίκι πάνω από αυτό το πεδίο για να δείτε τον αριθμό των επικυρώσεων</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Ημερομηνία κι ώρα λήψης της συναλλαγής.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Είδος συναλλαγής.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Διεύθυνση αποστολής της συναλλαγής.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Ποσό που αφαιρέθηκε ή προστέθηκε στο υπόλοιπο.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>Όλα</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Σήμερα</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Αυτή την εβδομάδα</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Αυτόν τον μήνα</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Τον προηγούμενο μήνα</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Αυτό το έτος</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Έκταση...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Ελήφθη με</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Απεστάλη προς</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Προς εσάς</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Εξόρυξη</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Άλλο</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Αναζήτηση με βάση τη διεύθυνση ή την επιγραφή</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Ελάχιστο ποσό</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Αντιγραφή διεύθυνσης</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Αντιγραφή επιγραφής</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Αντιγραφή ποσού</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>Αντιγραφη του ID Συναλλαγής</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Επεξεργασία επιγραφής</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Εμφάνιση λεπτομερειών συναλλαγής</translation>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation>Εξαγωγή Στοιχείων Συναλλαγών</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Αρχείο οριοθετημένο με κόμματα (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Επικυρωμένες</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Ημερομηνία</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Τύπος</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Επιγραφή</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Διεύθυνση</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Ποσό</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Σφάλμα εξαγωγής</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Αδυναμία εγγραφής στο αρχείο %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Έκταση:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>έως</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation>Αποστολή νομισμάτων</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation>&Εξαγωγή</translation>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation>Εξαγωγή δεδομένων καρτέλας σε αρχείο</translation>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation>Αντίγραφο ασφαλείας του πορτοφολιού</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>Αρχεία δεδομένων πορτοφολιού (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>Αποτυχία κατά τη δημιουργία αντιγράφου</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>Παρουσιάστηκε σφάλμα κατά την αποθήκευση των δεδομένων πορτοφολιού στη νέα τοποθεσία.</translation>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation>Η δημιουργια αντιγραφου ασφαλειας πετυχε</translation>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation>Τα δεδομένα πορτοφόλιου αποθηκεύτηκαν με επιτυχία στη νέα θέση. </translation>
</message>
</context>
<context>
<name>o2ocoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>O2ocoin version</source>
<translation>Έκδοση O2ocoin</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation>Χρήση:</translation>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or o2ocoind</source>
<translation>Αποστολή εντολής στον εξυπηρετητή ή στο o2ocoind</translation>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>Λίστα εντολών</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>Επεξήγηση εντολής</translation>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>Επιλογές:</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: o2ocoin.conf)</source>
<translation>Ορίστε αρχείο ρυθμίσεων (προεπιλογή: o2ocoin.conf)</translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: o2ocoind.pid)</source>
<translation>Ορίστε αρχείο pid (προεπιλογή: o2ocoind.pid)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Ορισμός φακέλου δεδομένων</translation>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Όρισε το μέγεθος της βάσης προσωρινής αποθήκευσης σε megabytes(προεπιλογή:25)</translation>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 8333 or testnet: 18333)</source>
<translation>Εισερχόμενες συνδέσεις στη θύρα <port> (προεπιλογή: 8333 ή στο testnet: 18333)</translation>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Μέγιστες αριθμός συνδέσεων με τους peers <n> (προεπιλογή: 125)</translation>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Σύνδεση σε έναν κόμβο για την ανάκτηση διευθύνσεων από ομοτίμους, και αποσυνδέσh</translation>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation>Διευκρινίστε τη δικιά σας δημόσια διεύθυνση.</translation>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Όριο αποσύνδεσης προβληματικών peers (προεπιλογή: 100)</translation>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Δευτερόλεπτα πριν επιτραπεί ξανά η σύνδεση των προβληματικών peers (προεπιλογή: 86400)</translation>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation>Ένα σφάλμα συνέβη καθώς προετοιμαζόταν η πόρτα RPC %u για αναμονή IPv4: %s</translation>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 8332 or testnet: 18332)</source>
<translation>Εισερχόμενες συνδέσεις JSON-RPC στη θύρα <port> (προεπιλογή: 8332 or testnet: 18332)</translation>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Αποδοχή εντολών κονσόλας και JSON-RPC</translation>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Εκτέλεση στο παρασκήνιο κι αποδοχή εντολών</translation>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation>Χρήση του δοκιμαστικού δικτύου</translation>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Να δέχεσαι συνδέσεις από έξω(προεπιλογή:1)</translation>
</message>
<message>
<location line="-80"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=o2ocoinrpc
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 "O2ocoin Alert" admin@foo.com
</source>
<translation>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=o2ocoinrpc
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 "O2ocoin Alert" admin@foo.com
</translation>
</message>
<message>
<location line="+17"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation>Ένα σφάλμα συνέβη καθώς προετοιμαζόταν η υποδοχη RPC %u για αναμονη του IPv6, επεσε πισω στο IPv4:%s</translation>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation>Αποθηκευση σε συγκεκριμένη διεύθυνση. Χρησιμοποιήστε τα πλήκτρα [Host] : συμβολισμός θύρα για IPv6</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. O2ocoin is probably already running.</source>
<translation>Αδυναμία κλειδώματος του φακέλου δεδομένων %s. Πιθανώς το O2ocoin να είναι ήδη ενεργό.</translation>
</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>Σφάλμα: Η συναλλαγή απορρίφθηκε.
Αυτό ίσως οφείλεται στο ότι τα νομίσματά σας έχουν ήδη ξοδευτεί, π.χ. με την αντιγραφή του wallet.dat σε άλλο σύστημα και την χρήση τους εκεί, χωρίς η συναλλαγή να έχει καταγραφεί στο παρόν σύστημα.</translation>
</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>Σφάλμα: Αυτή η συναλλαγή απαιτεί αμοιβή συναλλαγής τουλάχιστον %s λόγω του μεγέθους, πολυπλοκότητας ή της χρήσης πρόσφατης παραλαβής κεφαλαίου</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation>Εκτέλεση της εντολής όταν το καλύτερο μπλοκ αλλάξει(%s στην εντολή αντικαθίσταται από το hash του μπλοκ)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Εκτέλεσε την εντολή όταν το καλύτερο μπλοκ αλλάξει(%s στην εντολή αντικαθίσταται από το hash του μπλοκ)</translation>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation>Ορίστε το μέγιστο μέγεθος των high-priority/low-fee συναλλαγων σε bytes (προεπιλογή: 27000)</translation>
</message>
<message>
<location line="+6"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation>Αυτό είναι ένα προ-τεστ κυκλοφορίας - χρησιμοποιήστε το με δική σας ευθύνη - δεν χρησιμοποιείτε για εξόρυξη ή για αλλες εφαρμογές</translation>
</message>
<message>
<location line="+5"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Προειδοποίηση: Η παράμετρος -paytxfee είναι πολύ υψηλή. Πρόκειται για την αμοιβή που θα πληρώνετε για κάθε συναλλαγή που θα στέλνετε.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation>Προειδοποίηση: Εμφανίσεις συναλλαγων δεν μπορεί να είναι σωστες! Μπορεί να χρειαστεί να αναβαθμίσετε, ή άλλοι κόμβοι μπορεί να χρειαστεί να αναβαθμίστουν. </translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong O2ocoin will not work properly.</source>
<translation>Προειδοποίηση: Παρακαλώ βεβαιωθείτε πως η ημερομηνία κι ώρα του συστήματός σας είναι σωστές. Αν το ρολόι του υπολογιστή σας πάει λάθος, ενδέχεται να μη λειτουργεί σωστά το O2ocoin.</translation>
</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>Προειδοποίηση : Σφάλμα wallet.dat κατα την ανάγνωση ! Όλα τα κλειδιά αναγνωρισθηκαν σωστά, αλλά τα δεδομένα των συναλλαγών ή καταχωρήσεις στο βιβλίο διευθύνσεων μπορεί να είναι ελλιπείς ή λανθασμένα. </translation>
</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>Προειδοποίηση : το αρχειο wallet.dat ειναι διεφθαρμένο, τα δεδομένα σώζονται ! Original wallet.dat αποθηκεύονται ως πορτοφόλι { timestamp } bak στο % s ? . . Αν το υπόλοιπο του ή τις συναλλαγές σας, είναι λάθος θα πρέπει να επαναφέρετε από ένα αντίγραφο ασφαλείας</translation>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>Προσπάθεια για ανακτησει ιδιωτικων κλειδιων από ενα διεφθαρμένο αρχειο wallet.dat </translation>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation>Αποκλεισμός επιλογων δημιουργίας: </translation>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation>Σύνδεση μόνο με ορισμένους κόμβους</translation>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation>Εντοπισθηκε διεφθαρμενη βαση δεδομενων των μπλοκ</translation>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Ανακαλύψτε την δικη σας IP διεύθυνση (προεπιλογή: 1 όταν ακούει και δεν - externalip) </translation>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation>Θελετε να δημιουργηθει τωρα η βαση δεδομενων του μπλοκ? </translation>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation>Σφάλμα κατά την ενεργοποίηση της βάσης δεδομένων μπλοκ</translation>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation>Σφάλμα κατά την ενεργοποίηση της βάσης δεδομένων πορτοφόλιου %s!</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation>Σφάλμα φορτωσης της βασης δεδομενων των μπλοκ</translation>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation>Σφάλμα φορτωσης της βασης δεδομενων των μπλοκ</translation>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation>Προειδοποίηση: Χαμηλός χώρος στο δίσκο </translation>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation>Σφάλμα: το πορτοφόλι είναι κλειδωμένο, δεν μπορεί να δημιουργηθεί συναλλαγή</translation>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation>Λάθος: λάθος συστήματος:</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>ταλαιπωρηθειτε για να ακούσετε σε οποιαδήποτε θύρα. Χρήση - ακούστε = 0 , αν θέλετε αυτό.</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation>Αποτυχία αναγνωσης των block πληροφοριων</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation>Η αναγνωση του μπλοκ απετυχε</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation>Ο συγχρονισμος του μπλοκ ευρετηριου απετυχε</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation>Η δημιουργια του μπλοκ ευρετηριου απετυχε</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation>Η δημιουργια των μπλοκ πληροφοριων απετυχε</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation>Η δημιουργια του μπλοκ απετυχε</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation>Αδυναμία εγγραφής πληροφοριων αρχειου</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation>Αποτυχία εγγραφής στη βάση δεδομένων νομίσματος</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation>Αποτυχία εγγραφής δείκτη συναλλαγών </translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation>Αποτυχία εγγραφής αναίρεσης δεδομένων </translation>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation>Βρες ομότιμους υπολογιστές χρησιμοποιώντας αναζήτηση DNS(προεπιλογή:1)</translation>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation>Δημιουργία νομισμάτων (προκαθορισμος: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation>Πόσα μπλοκ να ελέγχθουν κατά την εκκίνηση (προεπιλογή:288,0=όλα)</translation>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation>Πόσο εξονυχιστική να είναι η επιβεβαίωση του μπλοκ(0-4, προεπιλογή:3)</translation>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation>Δεν ειναι αρκετες περιγραφες αρχείων διαθέσιμες.</translation>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation>Εισαγωγή μπλοκ από εξωτερικό αρχείο blk000?.dat</translation>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation>Ορίσμος του αριθμόυ θεματων στην υπηρεσία κλήσεων RPC (προεπιλογή: 4) </translation>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation>Επαλήθευση των μπλοκ... </translation>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation>Επαλήθευση πορτοφολιου... </translation>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation>Εισαγωγή μπλοκ από εξωτερικό αρχείο blk000?.dat</translation>
</message>
<message>
<location line="-76"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation>Ορίσμος του αριθμό των νημάτων ελέγχου σεναρίου (μέχρι 16, 0 = auto, <0 = αφήνουν τους πολλους πυρήνες δωρεάν, default: 0)</translation>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation>Πληροφορία</translation>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation>Δεν είναι έγκυρη η διεύθυνση διαμεσολαβητή: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation>Μη έγκυρο ποσό για την παράμετρο -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation>Μη έγκυρο ποσό για την παράμετρο -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation>Διατηρήση ένος πλήρες ευρετήριου συναλλαγών (προεπιλογή: 0) </translation>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Μέγιστος buffer λήψης ανά σύνδεση, <n>*1000 bytes (προεπιλογή: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Μέγιστος buffer αποστολής ανά σύνδεση, <n>*1000 bytes (προεπιλογή: 1000)</translation>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation>Μονο αποδοχη αλυσίδας μπλοκ που ταιριάζει με τα ενσωματωμένα σημεία ελέγχου (προεπιλογή: 1) </translation>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation> Συνδέση μόνο σε κόμβους του δικτύου <net> (IPv4, IPv6 ή Tor) </translation>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation>Έξοδος επιπλέον πληροφοριών εντοπισμού σφαλμάτων</translation>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation>Έξοδος επιπλέον πληροφοριών εντοπισμού σφαλμάτων</translation>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation>Χρονοσφραγίδα πληροφοριών εντοπισμού σφαλμάτων</translation>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the O2ocoin Wiki for SSL setup instructions)</source>
<translation>Ρυθμίσεις SSL: (ανατρέξτε στο O2ocoin Wiki για οδηγίες ρυθμίσεων SSL)</translation>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation>Επιλέξτε την έκδοση του διαμεσολαβητη για να χρησιμοποιήσετε (4-5 , προεπιλογή: 5)</translation>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Αποστολή πληροφοριών εντοπισμού σφαλμάτων στην κονσόλα αντί του αρχείου debug.log</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>Αποστολή πληροφοριών εντοπισμού σφαλμάτων στον debugger</translation>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation>Ορίσμος του μέγιστου μέγεθος block σε bytes (προεπιλογή: 250000)</translation>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Ορίστε το μέγιστο μέγεθος block σε bytes (προεπιλογή: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Συρρίκνωση του αρχείο debug.log κατα την εκκίνηση του πελάτη (προεπιλογή: 1 όταν δεν-debug)</translation>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation>Η υπογραφή συναλλαγής απέτυχε </translation>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Ορισμός λήξης χρονικού ορίου σε χιλιοστά του δευτερολέπτου(προεπιλογή:5000)</translation>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation>Λάθος Συστήματος:</translation>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation>Το ποσό της συναλλαγής είναι πολύ μικρο </translation>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation>Τα ποσά των συναλλαγών πρέπει να είναι θετικα</translation>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation>Η συναλλαγή ειναι πολύ μεγάλη </translation>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Χρησιμοποίηση του UPnP για την χρήση της πόρτας αναμονής (προεπιλογή:0)</translation>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Χρησιμοποίηση του UPnP για την χρήση της πόρτας αναμονής (προεπιλογή:1)</translation>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation>Χρήση διακομιστή μεσολάβησης για την επίτευξη των Tor κρυμμένων υπηρεσιων (προεπιλογή: ίδιο με το-proxy) </translation>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation>Όνομα χρήστη για τις συνδέσεις JSON-RPC</translation>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation>Προειδοποίηση</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Προειδοποίηση: Αυτή η έκδοση είναι ξεπερασμένη, απαιτείται αναβάθμιση </translation>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation>Θα πρέπει να ξαναχτίστουν οι βάσεις δεδομένων που χρησιμοποιούντε-Αναδημιουργία αλλάγων-txindex </translation>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>Το αρχειο wallet.dat ειναι διεφθαρμένο, η διάσωση απέτυχε</translation>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation>Κωδικός για τις συνδέσεις JSON-RPC</translation>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Αποδοχή συνδέσεων JSON-RPC από συγκεκριμένη διεύθυνση IP</translation>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Αποστολή εντολών στον κόμβο <ip> (προεπιλογή: 127.0.0.1)</translation>
</message>
<message>
<location line="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Εκτέλεσε την εντολή όταν το καλύτερο μπλοκ αλλάξει(%s στην εντολή αντικαθίσταται από το hash του μπλοκ)</translation>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation>Αναβάθμισε το πορτοφόλι στην τελευταία έκδοση</translation>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Όριο πλήθους κλειδιών pool <n> (προεπιλογή: 100)</translation>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Επανέλεγχος της αλυσίδας μπλοκ για απούσες συναλλαγές</translation>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Χρήση του OpenSSL (https) για συνδέσεις JSON-RPC</translation>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Αρχείο πιστοποιητικού του διακομιστή (προεπιλογή: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Προσωπικό κλειδί του διακομιστή (προεπιλογή: server.pem)</translation>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Αποδεκτά κρυπτογραφήματα (προεπιλογή: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation>Αυτό το κείμενο βοήθειας</translation>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Αδύνατη η σύνδεση με τη θύρα %s αυτού του υπολογιστή (bind returned error %d, %s) </translation>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation>Σύνδεση μέσω διαμεσολαβητή socks</translation>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Να επιτρέπονται οι έλεγχοι DNS για προσθήκη και σύνδεση κόμβων</translation>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>Φόρτωση διευθύνσεων...</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Σφάλμα φόρτωσης wallet.dat: Κατεστραμμένο Πορτοφόλι</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of O2ocoin</source>
<translation>Σφάλμα φόρτωσης wallet.dat: Το Πορτοφόλι απαιτεί μια νεότερη έκδοση του O2ocoin</translation>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart O2ocoin to complete</source>
<translation>Απαιτείται η επανεγγραφή του Πορτοφολιού, η οποία θα ολοκληρωθεί στην επανεκκίνηση του O2ocoin</translation>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation>Σφάλμα φόρτωσης αρχείου wallet.dat</translation>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Δεν είναι έγκυρη η διεύθυνση διαμεσολαβητή: '%s'</translation>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Άγνωστo δίκτυο ορίζεται σε onlynet: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>Άγνωστo δίκτυο ορίζεται: %i</translation>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>Δεν μπορώ να γράψω την προεπιλεγμένη διεύθυνση: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>Δεν μπορώ να γράψω την προεπιλεγμένη διεύθυνση: '%s'</translation>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Μη έγκυρο ποσό για την παράμετρο -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation>Λάθος ποσότητα</translation>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation>Ανεπαρκές κεφάλαιο</translation>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>Φόρτωση ευρετηρίου μπλοκ...</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Προσέθεσε ένα κόμβο για σύνδεση και προσπάθησε να κρατήσεις την σύνδεση ανοιχτή</translation>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. O2ocoin is probably already running.</source>
<translation>Αδύνατη η σύνδεση με τη θύρα %s αυτού του υπολογιστή. Το O2ocoin είναι πιθανώς ήδη ενεργό.</translation>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Αμοιβή ανά KB που θα προστίθεται στις συναλλαγές που στέλνεις</translation>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>Φόρτωση πορτοφολιού...</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation>Δεν μπορώ να υποβαθμίσω το πορτοφόλι</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation>Δεν μπορώ να γράψω την προεπιλεγμένη διεύθυνση</translation>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation>Ανίχνευση...</translation>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>Η φόρτωση ολοκληρώθηκε</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation>Χρήση της %s επιλογής</translation>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation>Σφάλμα</translation>
</message>
<message>
<location line="-31"/>
<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>Πρέπει να βάλεις ένα κωδικό στο αρχείο παραμέτρων: %s
Εάν το αρχείο δεν υπάρχει, δημιούργησε το με δικαιώματα μόνο για ανάγνωση από τον δημιουργό</translation>
</message>
</context>
</TS> | mit |
zetian/ltl_sampling | src/tests/test_cbba_v2.cpp | 9775 |
#include <stdio.h>
#include <vector>
#include <ctime>
#include <tuple>
#include <algorithm>
#include <bitset>
// opencv
#include "trans_sys/cbba_Agent_sampling.h"
#include "trans_sys/ltl_formula_sampling.h"
#include "sampling/cbba_sampling.h"
using namespace acel;
int main(int argc, char** argv )
{
srand(time(NULL));
lcm::LCM lcm;
double EPSILON = 8;
double RADIUS = 16;
double radius_L = 20;
double radius_R = 20;
int iteration_cbba = 800;
double work_space_size_x = 150;
double work_space_size_y = 150;
/************************************************************************************************************/
/********************************* Initialize: Map *****************************************/
/************************************************************************************************************/
LTLFormula Global_LTL;
// Define the position of Target (p2,p3,p4,...)
// Global_LTL.task_info = {{"p2",2},{"p3",3},{"p4",4},
// {"p5",5},{"p6",6},{"p7",7},{"p8",8}};
Global_LTL.task_info = {{"p0",0}, {"p1",1}, {"p2",2}, {"p3",3}, {"p4",4}, {"p5",5}, {"p6",6}, {"p7",7}};
// Decompose the global LTL_expression
// std::string safty = "([]!p0)";
std::string safty = "";
// std::string liveness = "(<>p0) && (<>p1) && (<>p2)";
// std::string liveness = "(<>p0) && (<>p1) && (<>p2) && (<>p3) && (<>p4) && (<>p5 && (<>p6)) && (<>p7)";
std::string liveness = "(<>p0) && (<>p1) && (<>p2) && (<>p3) && (<>p4) && (<>p5) && (<>p6) && (<>p7)";
LTLDecomposition::get_safety_properties(Global_LTL, safty);
LTLDecomposition::get_liveness_properties(Global_LTL, liveness);
Global_LTL = LTLDecomposition::GlobalLTLDecomposition(Global_LTL);
/*** 4. Initialize agents ***/
std::vector<float> y_0;
std::vector<int> z_0;
std::cout << "Global_LTL.Num_Tasks: " <<Global_LTL.Num_Tasks <<std::endl;
for (int i = 0; i < Global_LTL.Num_Tasks; i++){
y_0.push_back(0);
z_0.push_back(-1);
}
std::vector<std::vector<float>> y_his_0 = {y_0};
std::vector<std::vector<int>> z_his_0 = {z_0};
std::vector<cbba_Agent> all_agent = {cbba_Agent(0,{1,0,1,0},y_0,z_0,y_his_0,z_his_0),
cbba_Agent(1,{0,1,0,1},y_0,z_0,y_his_0,z_his_0),
cbba_Agent(2,{1,0,1,1},y_0,z_0,y_his_0,z_his_0),
cbba_Agent(3,{0,1,1,1},y_0,z_0,y_his_0,z_his_0)};
// std::vector<cbba_Agent> all_agent = {cbba_Agent(0,{1,1},y_0,z_0,y_his_0,z_his_0), cbba_Agent(1,{1,1},y_0,z_0,y_his_0,z_his_0)};
// sampling::sample_data node_data;
all_agent[0].init_state_ = {10, 10, M_PI/2};
all_agent[0].radius_L_ = radius_L;
all_agent[0].radius_R_ = radius_R;
// node_data.state[0] = all_agent[0].init_state_[0];
// node_data.state[1] = all_agent[0].init_state_[1];
// lcm.publish("SAMPLE", &node_data);
all_agent[1].init_state_ = {140, 10, M_PI};
all_agent[1].radius_L_ = radius_L;
all_agent[1].radius_R_ = radius_R;
// node_data.state[0] = all_agent[1].init_state_[0];
// node_data.state[1] = all_agent[1].init_state_[1];
// lcm.publish("SAMPLE", &node_data);
all_agent[2].init_state_ = {10, 140, 0};
all_agent[2].radius_L_ = radius_L;
all_agent[2].radius_R_ = radius_R;
// node_data.state[0] = all_agent[2].init_state_[0];
// node_data.state[1] = all_agent[2].init_state_[1];
// lcm.publish("SAMPLE", &node_data);
all_agent[3].init_state_ = {140, 140, M_PI*3/2};
all_agent[3].radius_L_ = radius_L;
all_agent[3].radius_R_ = radius_R;
// node_data.state[0] = all_agent[3].init_state_[0];
// node_data.state[1] = all_agent[3].init_state_[1];
// lcm.publish("SAMPLE", &node_data);
int num_tasks = Global_LTL.task_info.size();
// Initialize the awards
for (int i = 0; i < all_agent.size(); i++){
for (int j = 0; j < num_tasks; j++){
all_agent[i].cbba_award.push_back(-1);
}
}
std::vector<std::string> buchi_regions;
buchi_regions.push_back("p0");
buchi_regions.push_back("p1");
buchi_regions.push_back("p2");
buchi_regions.push_back("p3");
buchi_regions.push_back("p4");
buchi_regions.push_back("p5");
buchi_regions.push_back("p6");
buchi_regions.push_back("p7");
std::vector<int> indep_set = {0, 1, 2, 3, 4, 5, 6, 7};
// LTL_SamplingDubins ltl_sampling_dubins;
CBBA_sampling cbba_sampling;
for (int i = 0; i < all_agent.size(); i++) {
cbba_sampling.add_agent(all_agent[i]);
}
cbba_sampling.set_global_ltl(Global_LTL);
cbba_sampling.set_buchi_regions(buchi_regions);
cbba_sampling.set_indep_set(indep_set);
cbba_sampling.init_workspace(work_space_size_x, work_space_size_y);
cbba_sampling.init_parameter(iteration_cbba, EPSILON, RADIUS);
// Add region of interests
std::pair <double, double> position_x (0, 20);
std::pair <double, double> position_y (100, 120);
cbba_sampling.set_interest_region(position_x, position_y, 0);
sampling::region_data r_data;
r_data.position_x[0] = position_x.first;
r_data.position_x[1] = position_x.second;
r_data.position_y[0] = position_y.first;
r_data.position_y[1] = position_y.second;
lcm.publish("REGION", &r_data);
position_x = std::make_pair(0, 20);
position_y = std::make_pair(50, 70);
cbba_sampling.set_interest_region(position_x, position_y, 1);
r_data.position_x[0] = position_x.first;
r_data.position_x[1] = position_x.second;
r_data.position_y[0] = position_y.first;
r_data.position_y[1] = position_y.second;
lcm.publish("REGION", &r_data);
position_x = std::make_pair(40, 60);
position_y = std::make_pair(20, 40);
cbba_sampling.set_interest_region(position_x, position_y, 2);
r_data.position_x[0] = position_x.first;
r_data.position_x[1] = position_x.second;
r_data.position_y[0] = position_y.first;
r_data.position_y[1] = position_y.second;
lcm.publish("REGION", &r_data);
position_x = std::make_pair(130, 150);
position_y = std::make_pair(40, 60);
cbba_sampling.set_interest_region(position_x, position_y, 3);
r_data.position_x[0] = position_x.first;
r_data.position_x[1] = position_x.second;
r_data.position_y[0] = position_y.first;
r_data.position_y[1] = position_y.second;
lcm.publish("REGION", &r_data);
position_x = std::make_pair(90, 110);
position_y = std::make_pair(30, 50);
cbba_sampling.set_interest_region(position_x, position_y, 4);
r_data.position_x[0] = position_x.first;
r_data.position_x[1] = position_x.second;
r_data.position_y[0] = position_y.first;
r_data.position_y[1] = position_y.second;
lcm.publish("REGION", &r_data);
position_x = std::make_pair(80, 100);
position_y = std::make_pair(60, 80);
cbba_sampling.set_interest_region(position_x, position_y, 5);
r_data.position_x[0] = position_x.first;
r_data.position_x[1] = position_x.second;
r_data.position_y[0] = position_y.first;
r_data.position_y[1] = position_y.second;
lcm.publish("REGION", &r_data);
position_x = std::make_pair(40, 60);
position_y = std::make_pair(70, 90);
cbba_sampling.set_interest_region(position_x, position_y, 6);
r_data.position_x[0] = position_x.first;
r_data.position_x[1] = position_x.second;
r_data.position_y[0] = position_y.first;
r_data.position_y[1] = position_y.second;
lcm.publish("REGION", &r_data);
position_x = std::make_pair(90, 110);
position_y = std::make_pair(110, 130);
cbba_sampling.set_interest_region(position_x, position_y, 7);
r_data.position_x[0] = position_x.first;
r_data.position_x[1] = position_x.second;
r_data.position_y[0] = position_y.first;
r_data.position_y[1] = position_y.second;
lcm.publish("REGION", &r_data);
// Add obstacles
position_x = std::make_pair(0, 40);
position_y = std::make_pair(70, 90);
cbba_sampling.set_obstacle(position_x, position_y);
r_data.position_x[0] = position_x.first;
r_data.position_x[1] = position_x.second;
r_data.position_y[0] = position_y.first;
r_data.position_y[1] = position_y.second;
lcm.publish("OBSTACLE", &r_data);
position_x = std::make_pair(20, 40);
position_y = std::make_pair(40, 70);
cbba_sampling.set_obstacle(position_x, position_y);
r_data.position_x[0] = position_x.first;
r_data.position_x[1] = position_x.second;
r_data.position_y[0] = position_y.first;
r_data.position_y[1] = position_y.second;
lcm.publish("OBSTACLE", &r_data);
position_x = std::make_pair(0, 70);
position_y = std::make_pair(120, 130);
cbba_sampling.set_obstacle(position_x, position_y);
r_data.position_x[0] = position_x.first;
r_data.position_x[1] = position_x.second;
r_data.position_y[0] = position_y.first;
r_data.position_y[1] = position_y.second;
lcm.publish("OBSTACLE", &r_data);
position_x = std::make_pair(90, 150);
position_y = std::make_pair(20, 30);
cbba_sampling.set_obstacle(position_x, position_y);
r_data.position_x[0] = position_x.first;
r_data.position_x[1] = position_x.second;
r_data.position_y[0] = position_y.first;
r_data.position_y[1] = position_y.second;
lcm.publish("OBSTACLE", &r_data);
position_x = std::make_pair(110, 120);
position_y = std::make_pair(80, 150);
cbba_sampling.set_obstacle(position_x, position_y);
r_data.position_x[0] = position_x.first;
r_data.position_x[1] = position_x.second;
r_data.position_y[0] = position_y.first;
r_data.position_y[1] = position_y.second;
lcm.publish("OBSTACLE", &r_data);
cbba_sampling.start_cbba();
cbba_sampling.get_solution();
sampling::sample_draw draw;
draw.if_draw = true;
lcm.publish("DRAW_SAMPLE", &draw);
return 0;
}
| mit |
cassubian/plutonium | src/qt/bitcoinunits.cpp | 4299 | #include "bitcoinunits.h"
#include <QStringList>
BitcoinUnits::BitcoinUnits(QObject *parent):
QAbstractListModel(parent),
unitlist(availableUnits())
{
}
QList<BitcoinUnits::Unit> BitcoinUnits::availableUnits()
{
QList<BitcoinUnits::Unit> unitlist;
unitlist.append(PUK);
unitlist.append(mPUK);
unitlist.append(uPUK);
return unitlist;
}
bool BitcoinUnits::valid(int unit)
{
switch(unit)
{
case PUK:
case mPUK:
case uPUK:
return true;
default:
return false;
}
}
QString BitcoinUnits::name(int unit)
{
switch(unit)
{
case PUK: return QString("PUK");
case mPUK: return QString("mPUK");
case uPUK: return QString::fromUtf8("μPUK");
default: return QString("???");
}
}
QString BitcoinUnits::description(int unit)
{
switch(unit)
{
case PUK: return QString("PlutoniumKoins");
case mPUK: return QString("Milli-PlutoniumKoins (1 / 1,000)");
case uPUK: return QString("Micro-PlutoniumKoins (1 / 1,000,000)");
default: return QString("???");
}
}
qint64 BitcoinUnits::factor(int unit)
{
switch(unit)
{
case PUK: return 100000000;
case mPUK: return 100000;
case uPUK: return 100;
default: return 100000000;
}
}
int BitcoinUnits::amountDigits(int unit)
{
switch(unit)
{
case PUK: return 8; // 21,000,000 (# digits, without commas)
case mPUK: return 11; // 21,000,000,000
case uPUK: return 14; // 21,000,000,000,000
default: return 0;
}
}
int BitcoinUnits::decimals(int unit)
{
switch(unit)
{
case PUK: return 8;
case mPUK: return 5;
case uPUK: return 2;
default: return 0;
}
}
QString BitcoinUnits::format(int unit, qint64 n, bool fPlus)
{
// Note: not using straight sprintf here because we do NOT want
// localized number formatting.
if(!valid(unit))
return QString(); // Refuse to format invalid unit
qint64 coin = factor(unit);
int num_decimals = decimals(unit);
qint64 n_abs = (n > 0 ? n : -n);
qint64 quotient = n_abs / coin;
qint64 remainder = n_abs % coin;
QString quotient_str = QString::number(quotient);
QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0');
// Right-trim excess zeros after the decimal point
int nTrim = 0;
for (int i = remainder_str.size()-1; i>=2 && (remainder_str.at(i) == '0'); --i)
++nTrim;
remainder_str.chop(nTrim);
if (n < 0)
quotient_str.insert(0, '-');
else if (fPlus && n > 0)
quotient_str.insert(0, '+');
return quotient_str + QString(".") + remainder_str;
}
QString BitcoinUnits::formatWithUnit(int unit, qint64 amount, bool plussign)
{
return format(unit, amount, plussign) + QString(" ") + name(unit);
}
bool BitcoinUnits::parse(int unit, const QString &value, qint64 *val_out)
{
if(!valid(unit) || value.isEmpty())
return false; // Refuse to parse invalid unit or empty string
int num_decimals = decimals(unit);
QStringList parts = value.split(".");
if(parts.size() > 2)
{
return false; // More than one dot
}
QString whole = parts[0];
QString decimals;
if(parts.size() > 1)
{
decimals = parts[1];
}
if(decimals.size() > num_decimals)
{
return false; // Exceeds max precision
}
bool ok = false;
QString str = whole + decimals.leftJustified(num_decimals, '0');
if(str.size() > 18)
{
return false; // Longer numbers will exceed 63 bits
}
qint64 retvalue = str.toLongLong(&ok);
if(val_out)
{
*val_out = retvalue;
}
return ok;
}
int BitcoinUnits::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return unitlist.size();
}
QVariant BitcoinUnits::data(const QModelIndex &index, int role) const
{
int row = index.row();
if(row >= 0 && row < unitlist.size())
{
Unit unit = unitlist.at(row);
switch(role)
{
case Qt::EditRole:
case Qt::DisplayRole:
return QVariant(name(unit));
case Qt::ToolTipRole:
return QVariant(description(unit));
case UnitRole:
return QVariant(static_cast<int>(unit));
}
}
return QVariant();
}
| mit |
cmachler/aws-lambda-ebs-backups | lambda-ebs-backup.py | 4357 | import boto3
import collections
import datetime
import base64
import os
import json
import itertools
base64_region = os.environ['aws_regions']
aws_sns_arn = os.getenv('aws_sns_arn', None)
def send_to_sns(subject, message):
if aws_sns_arn is None:
return
print "Sending notification to: %s" % aws_sns_arn
client = boto3.client('sns')
response = client.publish(
TargetArn=aws_sns_arn,
Message=message,
Subject=subject)
if 'MessageId' in response:
print "Notification sent with message id: %s" % response['MessageId']
else:
print "Sending notification failed with response: %s" % str(response)
def lambda_handler(event, context):
decoded_regions = base64.b64decode(base64_region)
regions = decoded_regions.split(',')
print "Backing up instances in regions: %s" % regions
for region in regions:
ec = boto3.client('ec2', region_name=region)
reservations = ec.describe_instances(
Filters=[
{'Name': 'tag-key', 'Values': ['backup', 'Backup']},
]
).get(
'Reservations', []
)
instances = sum(
[
[i for i in r['Instances']]
for r in reservations
], [])
print "Found %d instances that need backing up in region %s" % (len(instances), region)
to_tag_retention = collections.defaultdict(list)
to_tag_mount_point = collections.defaultdict(list)
for instance in instances:
try:
retention_days = [
int(t.get('Value')) for t in instance['Tags']
if t['Key'] == 'Retention'][0]
except IndexError:
retention_days = 7
try:
skip_volumes = [
str(t.get('Value')).split(',') for t in instance['Tags']
if t['Key'] == 'Skip_Backup_Volumes']
except Exception:
pass
from itertools import chain
skip_volumes_list = list(chain.from_iterable(skip_volumes))
for dev in instance['BlockDeviceMappings']:
if dev.get('Ebs', None) is None:
continue
vol_id = dev['Ebs']['VolumeId']
if vol_id in skip_volumes_list:
print "Volume %s is set to be skipped, not backing up" % (vol_id)
continue
dev_attachment = dev['DeviceName']
print "Found EBS volume %s on instance %s attached to %s" % (
vol_id, instance['InstanceId'], dev_attachment)
instance_name = ''
try:
instance_name = [ x['Value'] for x in instance['Tags'] if x['Key'] == 'Name' ][0]
except IndexError:
pass
snap = ec.create_snapshot(
VolumeId=vol_id,
Description='{} {}'.format(instance_name, instance['InstanceId'])
)
to_tag_retention[retention_days].append(snap['SnapshotId'])
to_tag_mount_point[vol_id].append(snap['SnapshotId'])
print "Retaining snapshot %s of volume %s from instance %s for %d days" % (
snap['SnapshotId'],
vol_id,
instance['InstanceId'],
retention_days,
)
ec.create_tags(
Resources=to_tag_mount_point[vol_id],
Tags=[
{'Key': 'Name', 'Value': dev_attachment},
]
)
for retention_days in to_tag_retention.keys():
delete_date = datetime.date.today() + datetime.timedelta(days=retention_days)
delete_fmt = delete_date.strftime('%Y-%m-%d')
print "Will delete %d snapshots on %s" % (len(to_tag_retention[retention_days]), delete_fmt)
ec.create_tags(
Resources=to_tag_retention[retention_days],
Tags=[
{'Key': 'DeleteOn', 'Value': delete_fmt},
]
)
message = "{} instances have been backed up in region {}".format(len(instances), region)
send_to_sns('EBS Backups', message)
| mit |
simpleci/simpleci | src/frontend/src/AppBundle/System/Utils.php | 635 | <?php
namespace AppBundle\System;
use Doctrine\ORM\EntityManagerInterface;
class Utils
{
public static function disableSqlLogger(EntityManagerInterface $em)
{
$em->getConnection()->getConfiguration()->setSQLLogger(null);
}
public static function className($classFullName) {
$reflection = new \ReflectionClass($classFullName);
return self::underscore($reflection->getShortName());
}
public static function underscore($id)
{
return strtolower(preg_replace(array('/([A-Z]+)([A-Z][a-z])/', '/([a-z\d])([A-Z])/'), array('\\1_\\2', '\\1_\\2'), strtr($id, '_', '.')));
}
} | mit |
lacroixdesign/rail_pass | spec/dummy/config/application.rb | 2558 | require File.expand_path('../boot', __FILE__)
require 'rails/all'
Bundler.require
require "rail_pass"
module Dummy
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable escaping HTML in JSON.
config.active_support.escape_html_entities_in_json = true
# Use SQL instead of Active Record's schema dumper when creating the database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Enforce whitelist mode for mass assignment.
# This will create an empty whitelist of attributes available for mass-assignment for all models
# in your app. As such, your models will need to explicitly whitelist or blacklist accessible
# parameters by using an attr_accessible or attr_protected declaration.
config.active_record.whitelist_attributes = true
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
end
end
| mit |
suits-at/suits_at | components/scripts/velocity.js | 44 | var velocity = require('velocity-animate');
| mit |
concord-consortium/rigse | rails/db/migrate/20180424185006_drop_biologica_tables.rb | 1140 | class DropBiologicaTables < ActiveRecord::Migration[5.1]
def remove_table(name)
drop_table name.to_sym if ApplicationRecord.connection.tables.include?(name)
end
def up
[
"embeddable_biologica_breed_offsprings",
"embeddable_biologica_chromosome_zooms",
"embeddable_biologica_chromosome_zooms_organisms",
"embeddable_biologica_chromosomes",
"embeddable_biologica_meiosis_views",
"embeddable_biologica_multiple_organisms",
"embeddable_biologica_multiple_organisms_organisms",
"embeddable_biologica_organisms",
"embeddable_biologica_organisms_pedigrees",
"embeddable_biologica_pedigrees",
"embeddable_biologica_static_organisms",
"embeddable_biologica_worlds"
].each { |table| self.remove_table(table) }
execute "delete from saveable_external_links where embeddable_type like '%Biologica%'"
execute "delete from page_elements where embeddable_type like '%Biologica%'"
execute "delete from portal_offering_embeddable_metadata where embeddable_type like '%Biologica%'"
end
def down
raise ActiveRecord::IrreversibleMigration
end
end
| mit |
voxsoftware/vox-core | submodules/vox-core-moment/dist/locale/ar-ma.js | 1664 | var $mod$350 = core.VW.Ecma2015.Utils.module(require('../moment'));
exports.default = $mod$350.default.defineLocale('ar-ma', {
months: 'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split('_'),
monthsShort: 'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split('_'),
weekdays: 'الأحد_الإتنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'),
weekdaysShort: 'احد_اتنين_ثلاثاء_اربعاء_خميس_جمعة_سبت'.split('_'),
weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'),
weekdaysParseExact: true,
longDateFormat: {
LT: 'HH:mm',
LTS: 'HH:mm:ss',
L: 'DD/MM/YYYY',
LL: 'D MMMM YYYY',
LLL: 'D MMMM YYYY HH:mm',
LLLL: 'dddd D MMMM YYYY HH:mm'
},
calendar: {
sameDay: '[اليوم على الساعة] LT',
nextDay: '[غدا على الساعة] LT',
nextWeek: 'dddd [على الساعة] LT',
lastDay: '[أمس على الساعة] LT',
lastWeek: 'dddd [على الساعة] LT',
sameElse: 'L'
},
relativeTime: {
future: 'في %s',
past: 'منذ %s',
s: 'ثوان',
m: 'دقيقة',
mm: '%d دقائق',
h: 'ساعة',
hh: '%d ساعات',
d: 'يوم',
dd: '%d أيام',
M: 'شهر',
MM: '%d أشهر',
y: 'سنة',
yy: '%d سنوات'
},
week: {
dow: 6,
doy: 12
}
}); | mit |
boomcms/boom-installer | src/install.php | 212 | <?php
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
require __DIR__.'/views/boomcms/installer/install.php';
exit;
} elseif ($installer->databaseNeedsInstall()) {
$installer->installDatabase($_POST);
}
| mit |
jackdempsey/beet | lib/beet/recipes/rails/clean_files.rb | 98 | run "rm README"
run "rm public/index.html"
run "rm public/favicon.ico"
run "rm public/robots.txt"
| mit |
aleh/jpegator | src/Source.cs | 4139 | // JPEGator .NET Compact Framework Library.
// Copyright (C) 2005-2009, Aleh Dzenisiuk. All Rights Reserved.
// http://dzenisiuk.info/jpegator/
//
// When redistributing JPEGator source code the above copyright notice and
// this messages should be left intact. In case changes are made by you in
// this source code it should be clearly indicated in the beginning of each
// changed file.
using System;
using System.Runtime.InteropServices;
using System.IO;
using System.Diagnostics;
namespace JPEGator
{
/// <summary>
/// Wrapper over the data source for JPEG decompressor.
/// </summary>
internal sealed class Source : NativeStruct
{
private const int StructureSize = 7 * 4;
private const int BufferSize = 65536;
private NativeStruct buffer;
private NativeCallback initSource;
private NativeCallback fillInputBuffer;
private NativeCallback skipInputData;
private NativeCallback resyncToRestart;
private NativeCallback termSource;
public Source()
: base(StructureSize)
{
initSource = new NativeCallback(1, new NativeCallbackHandler(InitSource));
fillInputBuffer = new NativeCallback(1, new NativeCallbackHandler(FillInputBuffer));
skipInputData = new NativeCallback(2, new NativeCallbackHandler(SkipInputData));
resyncToRestart = new NativeCallback(2, new NativeCallbackHandler(ResyncToRestart));
termSource = new NativeCallback(1, new NativeCallbackHandler(TermSource));
int[] buf = new int[] {
0,
0,
initSource,
fillInputBuffer,
skipInputData,
resyncToRestart,
termSource
};
Marshal.Copy(buf, 0, Ptr, buf.Length);
}
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
initSource.Dispose();
fillInputBuffer.Dispose();
skipInputData.Dispose();
resyncToRestart.Dispose();
termSource.Dispose();
if (buffer != null)
buffer.Dispose();
if (autoClose && stream != null)
{
stream.Close();
stream = null;
}
}
}
finally
{
base.Dispose(disposing);
}
}
private Stream stream;
private bool autoClose;
public void SetStream(Stream s, bool autoClose)
{
this.stream = s;
this.autoClose = autoClose;
}
private int InitSource(int[] paramList)
{
buffer = new NativeStruct(BufferSize);
Marshal.WriteInt32(Ptr, 0, (int)buffer.Ptr);
Marshal.WriteInt32(Ptr, 4, 0);
return 0;
}
private int FillInputBuffer(int[] paramList)
{
byte[] buf = new byte[buffer.Size];
int bytesRead = stream.Read(buf, 0, buffer.Size);
Marshal.Copy(buf, 0, buffer.Ptr, bytesRead);
Marshal.WriteInt32(Ptr, 0, (int)buffer.Ptr);
Marshal.WriteInt32(Ptr, 4, bytesRead);
return 1;
}
private int SkipInputData(int[] paramList)
{
Debug.WriteLine(string.Format("Skipping {0} bytes", paramList[1]));
int numBytes = paramList[1];
if (numBytes <= 0)
return 0;
int bytesInBuffer = Marshal.ReadInt32(Ptr, 4);
if (numBytes <= bytesInBuffer)
{
int dataPtr = Marshal.ReadInt32(Ptr);
Marshal.WriteInt32(Ptr, 0, dataPtr + numBytes);
Marshal.WriteInt32(Ptr, 4, bytesInBuffer - numBytes);
}
else
{
int moveTo = numBytes - bytesInBuffer;
if (stream.CanSeek)
stream.Seek(moveTo, SeekOrigin.Current);
else
{
byte[] buf = new byte[BufferSize];
int bytesRead = 0;
while (bytesRead < moveTo)
{
int readNow = stream.Read(buf, 0, Math.Min(moveTo - bytesRead, buf.Length));
if (readNow == 0)
break;
bytesRead += readNow;
}
}
FillInputBuffer(paramList);
}
return 0;
}
private int ResyncToRestart(int[] paramList)
{
return JpegDll.ResyncToRestart((IntPtr)paramList[0], paramList[1]) ? 1 : 0;
}
private int TermSource(int[] paramList)
{
buffer.Dispose();
buffer = null;
if (autoClose)
stream.Close();
stream = null;
return 0;
}
}
}
| mit |
Azure/azure-sdk-for-java | sdk/resourcemanagerhybrid/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/fluent/GroupsClient.java | 35920 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.authorization.fluent;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.http.rest.PagedFlux;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.Response;
import com.azure.core.util.Context;
import com.azure.resourcemanager.authorization.fluent.models.ADGroupInner;
import com.azure.resourcemanager.authorization.fluent.models.CheckGroupMembershipResultInner;
import com.azure.resourcemanager.authorization.fluent.models.DirectoryObjectInner;
import com.azure.resourcemanager.authorization.models.AddOwnerParameters;
import com.azure.resourcemanager.authorization.models.CheckGroupMembershipParameters;
import com.azure.resourcemanager.authorization.models.GroupAddMemberParameters;
import com.azure.resourcemanager.authorization.models.GroupCreateParameters;
import com.azure.resourcemanager.authorization.models.GroupGetMemberGroupsParameters;
import com.azure.resourcemanager.resources.fluentcore.collection.InnerSupportsDelete;
import reactor.core.publisher.Mono;
/** An instance of this class provides access to all the operations defined in GroupsClient. */
public interface GroupsClient extends InnerSupportsDelete<Void> {
/**
* Checks whether the specified user, group, contact, or service principal is a direct or transitive member of the
* specified group.
*
* @param tenantId The tenant ID.
* @param parameters The check group membership parameters.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return server response for IsMemberOf API call.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<CheckGroupMembershipResultInner>> isMemberOfWithResponseAsync(
String tenantId, CheckGroupMembershipParameters parameters);
/**
* Checks whether the specified user, group, contact, or service principal is a direct or transitive member of the
* specified group.
*
* @param tenantId The tenant ID.
* @param parameters The check group membership parameters.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return server response for IsMemberOf API call.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<CheckGroupMembershipResultInner> isMemberOfAsync(String tenantId, CheckGroupMembershipParameters parameters);
/**
* Checks whether the specified user, group, contact, or service principal is a direct or transitive member of the
* specified group.
*
* @param tenantId The tenant ID.
* @param parameters The check group membership parameters.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return server response for IsMemberOf API call.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
CheckGroupMembershipResultInner isMemberOf(String tenantId, CheckGroupMembershipParameters parameters);
/**
* Checks whether the specified user, group, contact, or service principal is a direct or transitive member of the
* specified group.
*
* @param tenantId The tenant ID.
* @param parameters The check group membership parameters.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return server response for IsMemberOf API call.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Response<CheckGroupMembershipResultInner> isMemberOfWithResponse(
String tenantId, CheckGroupMembershipParameters parameters, Context context);
/**
* Remove a member from a group.
*
* @param groupObjectId The object ID of the group from which to remove the member.
* @param memberObjectId Member object id.
* @param tenantId The tenant ID.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<Void>> removeMemberWithResponseAsync(String groupObjectId, String memberObjectId, String tenantId);
/**
* Remove a member from a group.
*
* @param groupObjectId The object ID of the group from which to remove the member.
* @param memberObjectId Member object id.
* @param tenantId The tenant ID.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Void> removeMemberAsync(String groupObjectId, String memberObjectId, String tenantId);
/**
* Remove a member from a group.
*
* @param groupObjectId The object ID of the group from which to remove the member.
* @param memberObjectId Member object id.
* @param tenantId The tenant ID.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
void removeMember(String groupObjectId, String memberObjectId, String tenantId);
/**
* Remove a member from a group.
*
* @param groupObjectId The object ID of the group from which to remove the member.
* @param memberObjectId Member object id.
* @param tenantId The tenant ID.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the response.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Response<Void> removeMemberWithResponse(
String groupObjectId, String memberObjectId, String tenantId, Context context);
/**
* Add a member to a group.
*
* @param groupObjectId The object ID of the group to which to add the member.
* @param tenantId The tenant ID.
* @param parameters The URL of the member object, such as
* https://graph.windows.net/0b1f9851-1bf0-433f-aec3-cb9272f093dc/directoryObjects/f260bbc4-c254-447b-94cf-293b5ec434dd.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<Void>> addMemberWithResponseAsync(
String groupObjectId, String tenantId, GroupAddMemberParameters parameters);
/**
* Add a member to a group.
*
* @param groupObjectId The object ID of the group to which to add the member.
* @param tenantId The tenant ID.
* @param parameters The URL of the member object, such as
* https://graph.windows.net/0b1f9851-1bf0-433f-aec3-cb9272f093dc/directoryObjects/f260bbc4-c254-447b-94cf-293b5ec434dd.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Void> addMemberAsync(String groupObjectId, String tenantId, GroupAddMemberParameters parameters);
/**
* Add a member to a group.
*
* @param groupObjectId The object ID of the group to which to add the member.
* @param tenantId The tenant ID.
* @param parameters The URL of the member object, such as
* https://graph.windows.net/0b1f9851-1bf0-433f-aec3-cb9272f093dc/directoryObjects/f260bbc4-c254-447b-94cf-293b5ec434dd.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
void addMember(String groupObjectId, String tenantId, GroupAddMemberParameters parameters);
/**
* Add a member to a group.
*
* @param groupObjectId The object ID of the group to which to add the member.
* @param tenantId The tenant ID.
* @param parameters The URL of the member object, such as
* https://graph.windows.net/0b1f9851-1bf0-433f-aec3-cb9272f093dc/directoryObjects/f260bbc4-c254-447b-94cf-293b5ec434dd.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the response.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Response<Void> addMemberWithResponse(
String groupObjectId, String tenantId, GroupAddMemberParameters parameters, Context context);
/**
* Create a group in the directory.
*
* @param tenantId The tenant ID.
* @param parameters The parameters for the group to create.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return active Directory group information.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<ADGroupInner>> createWithResponseAsync(String tenantId, GroupCreateParameters parameters);
/**
* Create a group in the directory.
*
* @param tenantId The tenant ID.
* @param parameters The parameters for the group to create.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return active Directory group information.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<ADGroupInner> createAsync(String tenantId, GroupCreateParameters parameters);
/**
* Create a group in the directory.
*
* @param tenantId The tenant ID.
* @param parameters The parameters for the group to create.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return active Directory group information.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
ADGroupInner create(String tenantId, GroupCreateParameters parameters);
/**
* Create a group in the directory.
*
* @param tenantId The tenant ID.
* @param parameters The parameters for the group to create.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return active Directory group information.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Response<ADGroupInner> createWithResponse(String tenantId, GroupCreateParameters parameters, Context context);
/**
* Gets list of groups for the current tenant.
*
* @param tenantId The tenant ID.
* @param filter The filter to apply to the operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return list of groups for the current tenant.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedFlux<ADGroupInner> listAsync(String tenantId, String filter);
/**
* Gets list of groups for the current tenant.
*
* @param tenantId The tenant ID.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return list of groups for the current tenant.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedFlux<ADGroupInner> listAsync(String tenantId);
/**
* Gets list of groups for the current tenant.
*
* @param tenantId The tenant ID.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return list of groups for the current tenant.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedIterable<ADGroupInner> list(String tenantId);
/**
* Gets list of groups for the current tenant.
*
* @param tenantId The tenant ID.
* @param filter The filter to apply to the operation.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return list of groups for the current tenant.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedIterable<ADGroupInner> list(String tenantId, String filter, Context context);
/**
* Gets the members of a group.
*
* @param objectId The object ID of the group whose members should be retrieved.
* @param tenantId The tenant ID.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the members of a group.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedFlux<DirectoryObjectInner> getGroupMembersAsync(String objectId, String tenantId);
/**
* Gets the members of a group.
*
* @param objectId The object ID of the group whose members should be retrieved.
* @param tenantId The tenant ID.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the members of a group.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedIterable<DirectoryObjectInner> getGroupMembers(String objectId, String tenantId);
/**
* Gets the members of a group.
*
* @param objectId The object ID of the group whose members should be retrieved.
* @param tenantId The tenant ID.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the members of a group.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedIterable<DirectoryObjectInner> getGroupMembers(String objectId, String tenantId, Context context);
/**
* Gets group information from the directory.
*
* @param objectId The object ID of the user for which to get group information.
* @param tenantId The tenant ID.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return group information from the directory.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<ADGroupInner>> getWithResponseAsync(String objectId, String tenantId);
/**
* Gets group information from the directory.
*
* @param objectId The object ID of the user for which to get group information.
* @param tenantId The tenant ID.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return group information from the directory.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<ADGroupInner> getAsync(String objectId, String tenantId);
/**
* Gets group information from the directory.
*
* @param objectId The object ID of the user for which to get group information.
* @param tenantId The tenant ID.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return group information from the directory.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
ADGroupInner get(String objectId, String tenantId);
/**
* Gets group information from the directory.
*
* @param objectId The object ID of the user for which to get group information.
* @param tenantId The tenant ID.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return group information from the directory.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Response<ADGroupInner> getWithResponse(String objectId, String tenantId, Context context);
/**
* Delete a group from the directory.
*
* @param objectId The object ID of the group to delete.
* @param tenantId The tenant ID.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<Void>> deleteWithResponseAsync(String objectId, String tenantId);
/**
* Delete a group from the directory.
*
* @param objectId The object ID of the group to delete.
* @param tenantId The tenant ID.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Void> deleteAsync(String objectId, String tenantId);
/**
* Delete a group from the directory.
*
* @param objectId The object ID of the group to delete.
* @param tenantId The tenant ID.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
void delete(String objectId, String tenantId);
/**
* Delete a group from the directory.
*
* @param objectId The object ID of the group to delete.
* @param tenantId The tenant ID.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the response.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Response<Void> deleteWithResponse(String objectId, String tenantId, Context context);
/**
* Gets a collection of object IDs of groups of which the specified group is a member.
*
* @param objectId The object ID of the group for which to get group membership.
* @param tenantId The tenant ID.
* @param parameters Group filtering parameters.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a collection of object IDs of groups of which the specified group is a member.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedFlux<String> getMemberGroupsAsync(String objectId, String tenantId, GroupGetMemberGroupsParameters parameters);
/**
* Gets a collection of object IDs of groups of which the specified group is a member.
*
* @param objectId The object ID of the group for which to get group membership.
* @param tenantId The tenant ID.
* @param parameters Group filtering parameters.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a collection of object IDs of groups of which the specified group is a member.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedIterable<String> getMemberGroups(String objectId, String tenantId, GroupGetMemberGroupsParameters parameters);
/**
* Gets a collection of object IDs of groups of which the specified group is a member.
*
* @param objectId The object ID of the group for which to get group membership.
* @param tenantId The tenant ID.
* @param parameters Group filtering parameters.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a collection of object IDs of groups of which the specified group is a member.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedIterable<String> getMemberGroups(
String objectId, String tenantId, GroupGetMemberGroupsParameters parameters, Context context);
/**
* The owners are a set of non-admin users who are allowed to modify this object.
*
* @param objectId The object ID of the group for which to get owners.
* @param tenantId The tenant ID.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return directoryObject list operation result.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedFlux<DirectoryObjectInner> listOwnersAsync(String objectId, String tenantId);
/**
* The owners are a set of non-admin users who are allowed to modify this object.
*
* @param objectId The object ID of the group for which to get owners.
* @param tenantId The tenant ID.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return directoryObject list operation result.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedIterable<DirectoryObjectInner> listOwners(String objectId, String tenantId);
/**
* The owners are a set of non-admin users who are allowed to modify this object.
*
* @param objectId The object ID of the group for which to get owners.
* @param tenantId The tenant ID.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return directoryObject list operation result.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedIterable<DirectoryObjectInner> listOwners(String objectId, String tenantId, Context context);
/**
* Add an owner to a group.
*
* @param objectId The object ID of the application to which to add the owner.
* @param tenantId The tenant ID.
* @param parameters The URL of the owner object, such as
* https://graph.windows.net/0b1f9851-1bf0-433f-aec3-cb9272f093dc/directoryObjects/f260bbc4-c254-447b-94cf-293b5ec434dd.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<Void>> addOwnerWithResponseAsync(String objectId, String tenantId, AddOwnerParameters parameters);
/**
* Add an owner to a group.
*
* @param objectId The object ID of the application to which to add the owner.
* @param tenantId The tenant ID.
* @param parameters The URL of the owner object, such as
* https://graph.windows.net/0b1f9851-1bf0-433f-aec3-cb9272f093dc/directoryObjects/f260bbc4-c254-447b-94cf-293b5ec434dd.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Void> addOwnerAsync(String objectId, String tenantId, AddOwnerParameters parameters);
/**
* Add an owner to a group.
*
* @param objectId The object ID of the application to which to add the owner.
* @param tenantId The tenant ID.
* @param parameters The URL of the owner object, such as
* https://graph.windows.net/0b1f9851-1bf0-433f-aec3-cb9272f093dc/directoryObjects/f260bbc4-c254-447b-94cf-293b5ec434dd.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
void addOwner(String objectId, String tenantId, AddOwnerParameters parameters);
/**
* Add an owner to a group.
*
* @param objectId The object ID of the application to which to add the owner.
* @param tenantId The tenant ID.
* @param parameters The URL of the owner object, such as
* https://graph.windows.net/0b1f9851-1bf0-433f-aec3-cb9272f093dc/directoryObjects/f260bbc4-c254-447b-94cf-293b5ec434dd.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the response.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Response<Void> addOwnerWithResponse(
String objectId, String tenantId, AddOwnerParameters parameters, Context context);
/**
* Remove a member from owners.
*
* @param objectId The object ID of the group from which to remove the owner.
* @param ownerObjectId Owner object id.
* @param tenantId The tenant ID.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<Void>> removeOwnerWithResponseAsync(String objectId, String ownerObjectId, String tenantId);
/**
* Remove a member from owners.
*
* @param objectId The object ID of the group from which to remove the owner.
* @param ownerObjectId Owner object id.
* @param tenantId The tenant ID.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Void> removeOwnerAsync(String objectId, String ownerObjectId, String tenantId);
/**
* Remove a member from owners.
*
* @param objectId The object ID of the group from which to remove the owner.
* @param ownerObjectId Owner object id.
* @param tenantId The tenant ID.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
void removeOwner(String objectId, String ownerObjectId, String tenantId);
/**
* Remove a member from owners.
*
* @param objectId The object ID of the group from which to remove the owner.
* @param ownerObjectId Owner object id.
* @param tenantId The tenant ID.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.models.GraphErrorException thrown if the request is rejected by
* server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the response.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Response<Void> removeOwnerWithResponse(String objectId, String ownerObjectId, String tenantId, Context context);
}
| mit |
shuxinqin/Chloe | src/ChloeDemo/DbFunctions.cs | 629 | using Chloe.Annotations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ChloeDemo
{
public static class DbFunctions
{
[Chloe.Annotations.DbFunctionAttribute()]
public static string MyFunction(int value)
{
throw new NotImplementedException();
}
public static bool StringLike(this string str, string value)
{
return str.Contains(value);
}
public static bool GroupConcat<T>(T field)
{
throw new NotSupportedException("Using in lambda only.");
}
}
}
| mit |
slashhuang/slide-swipe | src/index.js | 294 | /**
* Created by slashhuang on 16/5/22.
* 主程序入口
*/
import Slider from './Slider.js';
import GestureEvent from './GestureEvent.js';
(function(root){
root.Slider=Slider;
}(typeof window !== "undefined" ? window : this));
Slider.GestureEvent=GestureEvent;
module.exports=Slider;
| mit |
Microsoft/Telemetry-Client-for-Android | AndroidCll/src/main/java/com/microsoft/cll/android/AbstractSettings.java | 6981 | package com.microsoft.cll.android;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;
import javax.net.ssl.HttpsURLConnection;
/**
* This is a base class for all calls to OneSettings
*/
public abstract class AbstractSettings {
protected String endpoint;
protected final ClientTelemetry clientTelemetry;
protected final ILogger logger;
protected String TAG = "AbstractSettings";
protected SettingsStore.Settings ETagSettingName;
private final PartA partA;
protected boolean disableUploadOn404 = false;
protected AbstractSettings(ClientTelemetry clientTelemetry, ILogger logger, PartA partA) {
this.clientTelemetry = clientTelemetry;
this.logger = logger;
this.partA = partA;
}
/**
* Retrieves the settings from the url specified
*/
public JSONObject getSettings() {
logger.info(TAG, "Get Settings");
URL url;
try {
url = new URL(endpoint + getQueryParameters());
} catch (MalformedURLException e) {
logger.error(TAG, "Settings URL is invalid");
return null;
}
URLConnection connection = null;
HttpsURLConnection httpConnection;
try {
connection = url.openConnection();
if (connection instanceof HttpsURLConnection) {
clientTelemetry.IncrementSettingsHttpAttempts();
httpConnection = (HttpsURLConnection) connection;
httpConnection.setConnectTimeout(SettingsStore.getCllSettingsAsInt(SettingsStore.Settings.HTTPTIMEOUTINTERVAL));
httpConnection.setRequestMethod("GET");
httpConnection.setRequestProperty("Accept", "application/json");
httpConnection.setRequestProperty("If-None-Match", SettingsStore.getCllSettingsAsString(ETagSettingName));
long start = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.US).getTimeInMillis();
httpConnection.connect();
long finish = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.US).getTimeInMillis();
long diff = finish - start;
clientTelemetry.SetAvgSettingsLatencyMs((int) diff);
clientTelemetry.SetMaxSettingsLatencyMs((int) diff);
if(httpConnection.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND && disableUploadOn404) {
// Disable sending events if user gives us an iKey that doesn't follow an allowed format.
logger.info(TAG, "Your iKey is invalid. Your events will not be sent!");
SettingsStore.updateCllSetting(SettingsStore.Settings.UPLOADENABLED, "false");
} else if(httpConnection.getResponseCode() != HttpURLConnection.HTTP_NOT_FOUND && disableUploadOn404) {
// We need this so that we are not permanently disabled after one 404.
// Only re-enable if host settings returns non 404. If we didn't check for disableUploadOn404 then
// the cll settings sync would end up re-enabling upload when we don't want it to.
logger.info(TAG, "Your iKey is valid.");
SettingsStore.updateCllSetting(SettingsStore.Settings.UPLOADENABLED, "true");
}
// Check for success (Only 200 and 304 are considered successful)
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK || httpConnection.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
String ETag = httpConnection.getHeaderField("ETAG");
if(ETag != null && !ETag.isEmpty()) {
SettingsStore.updateCllSetting(ETagSettingName, ETag);
}
} else {
clientTelemetry.IncrementSettingsHttpFailures(httpConnection.getResponseCode());
}
// Close the connection if this was not a success or there are no new settings
if(httpConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
httpConnection.disconnect();
httpConnection = null;
// set connection to null so we don't try/catch every time we
// make a valid connection
connection = null;
return null;
}
BufferedReader input = new BufferedReader(
new InputStreamReader(httpConnection.getInputStream()));
StringBuilder result = new StringBuilder();
String line;
while ((line = input.readLine()) != null) {
result.append(line);
}
input.close();
httpConnection.disconnect();
httpConnection = null;
// set connection to null so we don't try/catch every time we
// make a valid connection
connection = null;
return new JSONObject(result.toString());
}
} catch (IOException e) {
logger.error(TAG, e.getMessage());
clientTelemetry.IncrementSettingsHttpFailures(-1);
} catch (JSONException e) {
logger.error(TAG, e.getMessage());
} finally {
// close connection if it's still open
if (connection != null)
{
try
{
connection.getInputStream().close();
}
catch (Exception e)
{
// swallow exception
logger.error(TAG, e.getMessage());
}
}
}
return null;
}
/**
* Set the query parameters for the settings request
* @return
*/
protected String getQueryParameters() {
StringBuilder builder = new StringBuilder();
builder.append('?');
builder.append("os=");
builder.append(partA.osName);
builder.append("&osVer=");
builder.append(partA.osVer);
builder.append("&deviceClass=");
builder.append(partA.deviceExt.getDeviceClass());
builder.append("&deviceId=");
builder.append(partA.deviceExt.getLocalId());
return builder.toString();
}
/**
* Set the endpoint of where to get Settings from
*/
public void setSettingsEndpoint(String endpoint) {
this.endpoint = endpoint;
}
/**
* Parses the retrieved settings
*/
public abstract void ParseSettings(JSONObject resultJson);
}
| mit |
ninianne98/CarrotCakeCMS-MVC | CMSCore/ConfigHelper/CMSConfigHelper.cs | 37278 | using Carrotware.CMS.Data;
using Carrotware.Web.UI.Components;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Caching;
using System.Web.UI;
using System.Xml.Serialization;
/*
* CarrotCake CMS (MVC5)
* http://www.carrotware.com/
*
* Copyright 2015, Samantha Copeland
* Dual licensed under the MIT or GPL Version 3 licenses.
*
* Date: August 2015
*/
namespace Carrotware.CMS.Core {
public class CMSConfigHelper : IDisposable {
private CarrotCMSDataContext db = CarrotCMSDataContext.Create();
public CMSConfigHelper() { }
private enum CMSConfigFileType {
AdminMod,
SkinDef,
PublicCtrl,
SiteTextWidgets,
SiteMapping
}
#region IDisposable Members
public void Dispose() {
if (db != null) {
db.Dispose();
}
}
#endregion IDisposable Members
private static string keyAdminMenuModules = "cms_AdminMenuModules";
private static string keyAdminToolboxModules = "cms_AdminToolboxModules";
private static string keyDynamicSite = "cms_DynamicSite";
private static string keyTemplateFiles = "cms_TemplateFiles";
private static string keyTemplates = "cms_Templates";
private static string keyTxtWidgets = "cms_TxtWidgets";
private static string keyDynSite = "cms_DynSite_";
public static string keyAdminContent = "cmsAdminContent";
public static string keyAdminWidget = "cmsAdminWidget";
public void ResetConfigs() {
HttpContext.Current.Cache.Remove(keyAdminMenuModules);
HttpContext.Current.Cache.Remove(keyAdminToolboxModules);
HttpContext.Current.Cache.Remove(keyDynamicSite);
HttpContext.Current.Cache.Remove(keyTemplates);
HttpContext.Current.Cache.Remove(keyTxtWidgets);
HttpContext.Current.Cache.Remove(keyTemplateFiles);
string ModuleKey = keyDynSite + DomainName;
HttpContext.Current.Cache.Remove(ModuleKey);
try {
//VirtualDirectory.RegisterRoutes(true);
if (SiteData.CurretSiteExists) {
SiteData.CurrentSite.LoadTextWidgets();
}
} catch (Exception ex) { }
if (SiteData.CurrentTrustLevel == AspNetHostingPermissionLevel.Unrestricted) {
System.Web.HttpRuntime.UnloadAppDomain();
}
}
private static Page CachedPage {
get {
if (_CachedPage == null) {
_CachedPage = new Page();
_CachedPage.AppRelativeVirtualPath = "~/";
}
return _CachedPage;
}
}
private static Page _CachedPage;
public static string GetWebResourceUrl(Type type, string resource) {
string sPath = String.Empty;
try {
sPath = CachedPage.ClientScript.GetWebResourceUrl(type, resource);
sPath = HttpUtility.HtmlEncode(sPath);
} catch { }
return sPath;
}
public static string GetWebResourceUrl(Control X, Type type, string resource) {
string sPath = String.Empty;
if (X != null && X.Page != null) {
sPath = X.Page.ClientScript.GetWebResourceUrl(type, resource);
} else {
sPath = GetWebResourceUrl(type, resource);
}
try {
sPath = HttpUtility.HtmlEncode(sPath);
} catch { }
return sPath;
}
public static string DomainName {
get {
var domName = HttpContext.Current.Request.ServerVariables["HTTP_HOST"];
if ((domName.IndexOf(":") > 0) && (domName.EndsWith(":80") || domName.EndsWith(":443"))) {
domName = domName.Substring(0, domName.IndexOf(":"));
}
return domName.ToLowerInvariant();
}
}
public static bool HasAdminModules() {
using (CMSConfigHelper cmsHelper = new CMSConfigHelper()) {
return cmsHelper.AdminModules.Any();
}
}
public static FileDataHelper GetFileDataHelper() {
string fileTypes = null;
CarrotCakeConfig config = CarrotCakeConfig.GetConfig();
if (config.FileManagerConfig != null && !String.IsNullOrEmpty(config.FileManagerConfig.BlockedExtensions)) {
fileTypes = config.FileManagerConfig.BlockedExtensions;
}
return new FileDataHelper(fileTypes);
}
private static DataSet ReadDataSetConfig(CMSConfigFileType cfg, string sPath) {
string sPlugCfg = "default.config";
string sRealPath = HttpContext.Current.Server.MapPath(sPath);
CarrotCakeConfig config = CarrotCakeConfig.GetConfig();
int iExpectedTblCount = 1;
switch (cfg) {
case CMSConfigFileType.SiteTextWidgets:
sPlugCfg = sRealPath + config.ConfigFileLocation.TextContentProcessors;
break;
case CMSConfigFileType.SiteMapping:
sPlugCfg = sRealPath + config.ConfigFileLocation.SiteMapping;
break;
case CMSConfigFileType.AdminMod:
sPlugCfg = sRealPath + "Admin.config";
iExpectedTblCount = 2;
break;
case CMSConfigFileType.PublicCtrl:
sPlugCfg = sRealPath + "Public.config";
break;
case CMSConfigFileType.SkinDef:
sPlugCfg = sRealPath + "Skin.config";
break;
default:
sPlugCfg = sRealPath + "default.config";
iExpectedTblCount = -1;
break;
}
DataSet ds = new DataSet();
if (File.Exists(sPlugCfg) && iExpectedTblCount > 0) {
ds.ReadXml(sPlugCfg);
}
if (ds == null) {
ds = new DataSet();
}
int iTblCount = ds.Tables.Count;
// if dataset has wrong # of tables, build out more tables
if (iTblCount < iExpectedTblCount) {
for (int t = iTblCount; t <= iExpectedTblCount; t++) {
ds.Tables.Add(new DataTable());
ds.AcceptChanges();
}
}
if (iExpectedTblCount > 0) {
iTblCount = ds.Tables.Count;
string table1Name = String.Empty;
List<string> reqCols0 = new List<string>();
List<string> reqCols1 = new List<string>();
switch (cfg) {
case CMSConfigFileType.AdminMod:
reqCols0.Add("caption");
reqCols0.Add("area");
table1Name = "pluginlist";
reqCols1.Add("area");
reqCols1.Add("pluginlabel");
reqCols1.Add("menuorder");
reqCols1.Add("action");
reqCols1.Add("controller");
reqCols1.Add("usepopup");
reqCols1.Add("visible");
break;
case CMSConfigFileType.PublicCtrl:
//case CMSConfigFileType.PublicControls:
reqCols0.Add("filepath");
reqCols0.Add("crtldesc");
table1Name = "ctrlfile";
break;
case CMSConfigFileType.SkinDef:
reqCols0.Add("templatefile");
reqCols0.Add("filedesc");
table1Name = "pagenames";
break;
case CMSConfigFileType.SiteTextWidgets:
reqCols0.Add("pluginassembly");
reqCols0.Add("pluginname");
table1Name = "plugin";
break;
case CMSConfigFileType.SiteMapping:
reqCols0.Add("domname");
reqCols0.Add("siteid");
table1Name = "sitedetail";
break;
default:
reqCols0.Add("caption");
reqCols0.Add("pluginid");
table1Name = "none";
break;
}
if (ds.Tables.Contains(table1Name)) {
//validate that the dataset has the right table configuration
DataTable dt0 = ds.Tables[table1Name];
foreach (string c in reqCols0) {
if (!dt0.Columns.Contains(c)) {
DataColumn dc = new DataColumn(c);
dc.DataType = System.Type.GetType("System.String"); // add if not found
dt0.Columns.Add(dc);
dt0.AcceptChanges();
}
}
for (int iTbl = 1; iTbl < iTblCount; iTbl++) {
DataTable dt = ds.Tables[iTbl];
foreach (string c in reqCols1) {
if (!dt.Columns.Contains(c)) {
DataColumn dc = new DataColumn(c);
dc.DataType = System.Type.GetType("System.String"); // add if not found
dt.Columns.Add(dc);
dt.AcceptChanges();
}
}
}
}
}
return ds;
}
public static DateTime CalcNearestFiveMinTime(DateTime dateIn) {
dateIn = dateIn.AddMinutes(-2);
int iMin = 5 * (dateIn.Minute / 5);
DateTime dateOut = dateIn.AddMinutes(0 - dateIn.Minute).AddMinutes(iMin);
return dateOut;
}
public string GetFolderPrefix(string sDirPath) {
return FileDataHelper.MakeWebFolderPath(sDirPath);
}
public List<CMSAdminModule> AdminModules {
get {
var _modules = new List<CMSAdminModule>();
bool bCached = false;
try {
_modules = (List<CMSAdminModule>)HttpContext.Current.Cache[keyAdminMenuModules];
if (_modules != null) {
bCached = true;
}
} catch {
bCached = false;
}
if (!bCached) {
List<CMSAdminModuleMenu> _ctrls = new List<CMSAdminModuleMenu>();
_modules = new List<CMSAdminModule>();
foreach (var p in _modules) {
p.PluginMenus = (from c in _ctrls
where c.AreaKey == p.AreaKey
orderby c.Caption, c.SortOrder
select c).ToList();
}
_modules = _modules.Union(GetModulesByDirectory()).ToList();
HttpContext.Current.Cache.Insert(keyAdminMenuModules, _modules, null, DateTime.Now.AddMinutes(5), Cache.NoSlidingExpiration);
}
return _modules.OrderBy(m => m.PluginName).ToList();
}
}
private List<CMSPlugin> GetPluginsByDirectory() {
var _plugins = new List<CMSPlugin>();
CarrotCakeConfig config = CarrotCakeConfig.GetConfig();
string sPlugCfg = HttpContext.Current.Server.MapPath(config.ConfigFileLocation.PluginPath);
if (Directory.Exists(sPlugCfg)) {
string[] subdirs;
try {
subdirs = Directory.GetDirectories(sPlugCfg);
} catch {
subdirs = null;
}
if (subdirs != null) {
foreach (string theDir in subdirs) {
string sTplDef = theDir + @"\Public.config";
if (File.Exists(sTplDef)) {
string sPathPrefix = GetFolderPrefix(theDir);
DataSet ds = ReadDataSetConfig(CMSConfigFileType.PublicCtrl, sPathPrefix);
var _p2 = (from d in ds.Tables[0].AsEnumerable()
select new CMSPlugin {
SortOrder = 100,
FilePath = d.Field<string>("filepath"),
Caption = d.Field<string>("crtldesc")
}).Where(x => x.FilePath.Contains(":")).ToList();
foreach (var p in _p2.Where(x => x.FilePath.ToLowerInvariant().EndsWith("html")).Select(x => x)) {
string[] path = p.FilePath.Split(':');
if (path.Length > 2 && !String.IsNullOrEmpty(path[2])
&& (path[2].ToLowerInvariant().EndsWith(".cshtml") || path[2].ToLowerInvariant().EndsWith(".vbhtml"))) {
path[2] = "~" + sPathPrefix + path[2];
p.FilePath = String.Join(":", path);
}
}
var _p3 = (from d in ds.Tables[0].AsEnumerable()
select new CMSPlugin {
SortOrder = 100,
FilePath = "~" + sPathPrefix + d.Field<string>("filepath"),
Caption = d.Field<string>("crtldesc")
}).Where(x => !x.FilePath.Contains(":")).ToList();
_plugins = _plugins.Union(_p2).Union(_p3).ToList();
}
}
}
}
_plugins.Where(x => x.FilePath.StartsWith("~~/")).ToList().ForEach(r => r.FilePath = r.FilePath.Replace("~~/", "~/"));
_plugins.Where(x => x.FilePath.Contains("//")).ToList().ForEach(r => r.FilePath = r.FilePath.Replace("//", "/"));
return _plugins;
}
public List<CMSPlugin> GetPluginsInFolder(string sPathPrefix) {
var _plugins = new List<CMSPlugin>();
if (!sPathPrefix.EndsWith("/")) {
sPathPrefix = sPathPrefix + "/";
}
if (!String.IsNullOrEmpty(sPathPrefix)) {
DataSet ds = ReadDataSetConfig(CMSConfigFileType.PublicCtrl, sPathPrefix);
_plugins = (from d in ds.Tables[0].AsEnumerable()
select new CMSPlugin {
SortOrder = 100,
FilePath = "~" + sPathPrefix + d.Field<string>("filepath"),
Caption = d.Field<string>("crtldesc")
}).ToList();
}
_plugins.Where(x => x.FilePath.StartsWith("~~/")).ToList().ForEach(r => r.FilePath = r.FilePath.Replace("~~/", "~/"));
return _plugins;
}
public CMSAdminModuleMenu GetCurrentAdminModuleControl() {
HttpRequest request = HttpContext.Current.Request;
string pf = String.Empty;
CMSAdminModuleMenu cc = null;
if (request.QueryString["pf"] != null) {
pf = request.QueryString["pf"].ToString();
CMSAdminModule mod = (from m in AdminModules
where m.AreaKey == PluginAreaPath
select m).FirstOrDefault();
cc = (from m in mod.PluginMenus
orderby m.Caption, m.SortOrder
where m.Action == pf
select m).FirstOrDefault();
}
return cc;
}
public static string PluginAreaPath {
get {
string path = HttpContext.Current.Request.ServerVariables["SCRIPT_NAME"];
int i1 = path.IndexOf("/") + 1;
int i2 = path.IndexOf("/", 2) - 1;
return path.Substring(i1, i2);
}
}
public List<CMSAdminModuleMenu> GetCurrentAdminModuleControlList() {
HttpRequest request = HttpContext.Current.Request;
string pf = String.Empty;
CMSAdminModule mod = (from m in AdminModules
where m.AreaKey == PluginAreaPath
select m).FirstOrDefault();
return (from m in mod.PluginMenus
orderby m.Caption, m.SortOrder
select m).ToList();
}
public void GetFile(string sRemoteFile, string sLocalFile) {
Uri remoteFile = new Uri(sRemoteFile);
string sServerPath = HttpContext.Current.Server.MapPath(sLocalFile);
bool bExists = File.Exists(sServerPath);
if (!bExists) {
using (WebClient webClient = new WebClient()) {
try {
webClient.DownloadFile(remoteFile, sServerPath);
//webClient.DownloadFileAsync(remoteFile, sServerPath);
} catch (Exception ex) {
if (ex is WebException) {
WebException webException = (WebException)ex;
var resp = (HttpWebResponse)webException.Response;
if (!(resp.StatusCode == HttpStatusCode.NotFound)) {
throw;
}
} else {
throw;
}
}
}
}
}
private List<CMSAdminModule> GetModulesByDirectory() {
var _plugins = new List<CMSAdminModule>();
CarrotCakeConfig config = CarrotCakeConfig.GetConfig();
string sPlugCfg = HttpContext.Current.Server.MapPath(config.ConfigFileLocation.PluginPath);
if (Directory.Exists(sPlugCfg)) {
string[] subdirs;
try {
subdirs = Directory.GetDirectories(sPlugCfg);
} catch {
subdirs = null;
}
if (subdirs != null) {
foreach (string theDir in subdirs) {
string sTplDef = theDir + @"\Admin.config";
if (File.Exists(sTplDef)) {
string sPathPrefix = GetFolderPrefix(theDir);
DataSet ds = ReadDataSetConfig(CMSConfigFileType.AdminMod, sPathPrefix);
var _modules = (from d in ds.Tables[0].AsEnumerable()
select new CMSAdminModule {
PluginName = d.Field<string>("caption"),
AreaKey = d.Field<string>("area")
}).OrderBy(x => x.PluginName).ToList();
var _ctrls = (from d in ds.Tables[1].AsEnumerable()
select new CMSAdminModuleMenu {
Caption = d.Field<string>("pluginlabel"),
SortOrder = String.IsNullOrEmpty(d.Field<string>("menuorder")) ? -1 : int.Parse(d.Field<string>("menuorder")),
Action = d.Field<string>("action"),
Controller = d.Field<string>("controller"),
UsePopup = String.IsNullOrEmpty(d.Field<string>("usepopup")) ? false : Convert.ToBoolean(d.Field<string>("usepopup")),
IsVisible = String.IsNullOrEmpty(d.Field<string>("visible")) ? false : Convert.ToBoolean(d.Field<string>("visible")),
AreaKey = d.Field<string>("area")
}).OrderBy(x => x.Caption).OrderBy(x => x.SortOrder).ToList();
foreach (var p in _modules) {
p.PluginMenus = (from c in _ctrls
where c.AreaKey == p.AreaKey
orderby c.Caption, c.SortOrder
select c).ToList();
}
_plugins = _plugins.Union(_modules).ToList();
}
}
}
}
return _plugins;
}
public List<CMSTextWidgetPicker> GetAllWidgetSettings(Guid siteID) {
List<TextWidget> lstPreferenced = TextWidget.GetSiteTextWidgets(siteID);
List<string> lstInUse = lstPreferenced.Select(x => x.TextWidgetAssembly).Distinct().ToList();
List<string> lstAvail = TextWidgets.Select(x => x.AssemblyString).Distinct().ToList();
List<CMSTextWidgetPicker> lstExisting = (from p in lstPreferenced
join t in TextWidgets on p.TextWidgetAssembly equals t.AssemblyString
select new CMSTextWidgetPicker {
TextWidgetPickerID = p.TextWidgetID,
AssemblyString = p.TextWidgetAssembly,
DisplayName = t.DisplayName,
ProcessBody = p.ProcessBody,
ProcessPlainText = p.ProcessPlainText,
ProcessHTMLText = p.ProcessHTMLText,
ProcessComment = p.ProcessComment,
ProcessSnippet = p.ProcessSnippet,
}).ToList();
List<CMSTextWidgetPicker> lstConfigured1 = (from t in TextWidgets
where !lstInUse.Contains(t.AssemblyString)
select new CMSTextWidgetPicker {
TextWidgetPickerID = Guid.NewGuid(),
AssemblyString = t.AssemblyString,
DisplayName = t.DisplayName,
ProcessBody = false,
ProcessPlainText = false,
ProcessHTMLText = false,
ProcessComment = false,
ProcessSnippet = false,
}).ToList();
lstExisting = lstExisting.Union(lstConfigured1).ToList();
List<CMSTextWidgetPicker> lstConfigured2 = (from p in lstPreferenced
where !lstAvail.Contains(p.TextWidgetAssembly)
select new CMSTextWidgetPicker {
TextWidgetPickerID = p.TextWidgetID,
AssemblyString = p.TextWidgetAssembly,
DisplayName = String.Empty,
ProcessBody = p.ProcessBody,
ProcessPlainText = p.ProcessPlainText,
ProcessHTMLText = p.ProcessHTMLText,
ProcessComment = p.ProcessComment,
ProcessSnippet = p.ProcessSnippet,
}).ToList();
lstExisting = lstExisting.Union(lstConfigured2).ToList();
return lstExisting;
}
public List<CMSPlugin> ToolboxPlugins {
get {
var _plugins = new List<CMSPlugin>();
bool bCached = false;
try {
_plugins = (List<CMSPlugin>)HttpContext.Current.Cache[keyAdminToolboxModules];
if (_plugins != null) {
bCached = true;
}
} catch {
bCached = false;
}
if (!bCached) {
int iSortOrder = 0;
List<CMSPlugin> _p1 = new List<CMSPlugin>();
_p1.Add(new CMSPlugin { SystemPlugin = true, SortOrder = iSortOrder++, Caption = "Generic HTML", FilePath = "CLASS:Carrotware.CMS.UI.Components.ContentRichText, Carrotware.CMS.UI.Components" });
_p1.Add(new CMSPlugin { SystemPlugin = true, SortOrder = iSortOrder++, Caption = "Plain Text", FilePath = "CLASS:Carrotware.CMS.UI.Components.ContentPlainText, Carrotware.CMS.UI.Components" });
_p1.Add(new CMSPlugin { SystemPlugin = true, SortOrder = iSortOrder++, Caption = "Content Snippet", FilePath = "CLASS:Carrotware.CMS.UI.Components.ContentSnippetText, Carrotware.CMS.UI.Components" });
_p1.Add(new CMSPlugin { SystemPlugin = true, SortOrder = iSortOrder++, Caption = "Child Navigation", FilePath = "CLASS:Carrotware.CMS.UI.Components.ChildNavigation, Carrotware.CMS.UI.Components" });
_p1.Add(new CMSPlugin { SystemPlugin = true, SortOrder = iSortOrder++, Caption = "Second Level/ Sibling Navigation", FilePath = "CLASS:Carrotware.CMS.UI.Components.SecondLevelNavigation, Carrotware.CMS.UI.Components" });
_p1.Add(new CMSPlugin { SystemPlugin = true, SortOrder = iSortOrder++, Caption = "Most Recent Updated", FilePath = "CLASS:Carrotware.CMS.UI.Components.MostRecentUpdated, Carrotware.CMS.UI.Components" });
_p1.Add(new CMSPlugin { SystemPlugin = true, SortOrder = iSortOrder++, Caption = "Multi Level Nav List", FilePath = "CLASS:Carrotware.CMS.UI.Components.MultiLevelNavigation, Carrotware.CMS.UI.Components" });
_p1.Add(new CMSPlugin { SystemPlugin = true, SortOrder = iSortOrder++, Caption = "IFRAME content wrapper", FilePath = "CLASS:Carrotware.CMS.UI.Components.IFrameWidgetWrapper, Carrotware.CMS.UI.Components" });
_plugins = _p1.Union(GetPluginsByDirectory()).ToList();
_plugins.Where(x => x.FilePath.StartsWith("~~/")).ToList().ForEach(r => r.FilePath = r.FilePath.Replace("~~/", "~/"));
HttpContext.Current.Cache.Insert(keyAdminToolboxModules, _plugins, null, DateTime.Now.AddMinutes(5), Cache.NoSlidingExpiration);
}
return _plugins.OrderBy(p => p.SystemPlugin).OrderBy(p => p.Caption).OrderBy(p => p.SortOrder).ToList();
}
}
private List<CMSTemplate> GetTemplatesByDirectory() {
var _plugins = new List<CMSTemplate>();
CarrotCakeConfig config = CarrotCakeConfig.GetConfig();
string sPlugCfg = HttpContext.Current.Server.MapPath(config.ConfigFileLocation.TemplatePath);
if (Directory.Exists(sPlugCfg)) {
string[] subdirs;
try {
subdirs = Directory.GetDirectories(sPlugCfg);
} catch {
subdirs = null;
}
if (subdirs != null) {
foreach (string theDir in subdirs) {
string sTplDef = theDir + @"\Skin.config";
if (File.Exists(sTplDef)) {
string sPathPrefix = GetFolderPrefix(theDir);
DataSet ds = ReadDataSetConfig(CMSConfigFileType.SkinDef, sPathPrefix);
var _p2 = (from d in ds.Tables[0].AsEnumerable()
select new CMSTemplate {
TemplatePath = "~/" + (sPathPrefix + d.Field<string>("templatefile").ToLowerInvariant()).ToLowerInvariant(),
EncodedPath = String.Empty,
Caption = d.Field<string>("filedesc")
}).ToList();
_plugins = _plugins.Union(_p2).ToList();
_plugins.Where(x => x.TemplatePath.StartsWith("~~/")).ToList()
.ForEach(r => r.TemplatePath = r.TemplatePath.Replace("~~/", "~/"));
_plugins.Where(x => x.TemplatePath.Contains("//")).ToList()
.ForEach(r => r.TemplatePath = r.TemplatePath.Replace("//", "/"));
_plugins.ForEach(r => r.EncodedPath = EncodeBase64(r.TemplatePath));
}
}
}
}
return _plugins;
}
public List<CMSTemplate> Templates {
get {
List<CMSTemplate> _plugins = null;
string sDefTemplate = SiteData.DefaultTemplateFilename.ToLowerInvariant();
bool bCached = false;
try {
_plugins = (List<CMSTemplate>)HttpContext.Current.Cache[keyTemplates];
if (_plugins != null) {
bCached = true;
}
} catch {
bCached = false;
}
if (!bCached) {
_plugins = new List<CMSTemplate>();
CMSTemplate t = new CMSTemplate();
t.TemplatePath = sDefTemplate;
t.EncodedPath = EncodeBase64(sDefTemplate);
t.Caption = " Black 'n White - Plain L-R-C Content [*] ";
_plugins.Add(t);
}
if (!bCached) {
var _p2 = GetTemplatesByDirectory();
_plugins = _plugins.Union(_p2.Where(t => t.TemplatePath.ToLowerInvariant() != sDefTemplate)).ToList();
HttpContext.Current.Cache.Insert(keyTemplates, _plugins, null, DateTime.Now.AddMinutes(5), Cache.NoSlidingExpiration);
}
return _plugins.OrderBy(t => t.Caption).ToList();
}
}
public List<CMSTextWidget> TextWidgets {
get {
List<CMSTextWidget> _plugins = null;
bool bCached = false;
try {
_plugins = (List<CMSTextWidget>)HttpContext.Current.Cache[keyTxtWidgets];
if (_plugins != null) {
bCached = true;
}
} catch {
bCached = false;
}
if (!bCached) {
_plugins = new List<CMSTextWidget>();
}
if (!bCached) {
DataSet ds = ReadDataSetConfig(CMSConfigFileType.SiteTextWidgets, "~/");
_plugins = (from d in ds.Tables[0].AsEnumerable()
select new CMSTextWidget {
AssemblyString = d.Field<string>("pluginassembly"),
DisplayName = d.Field<string>("pluginname")
}).ToList();
HttpContext.Current.Cache.Insert(keyTxtWidgets, _plugins, null, DateTime.Now.AddMinutes(5), Cache.NoSlidingExpiration);
}
return _plugins.OrderBy(t => t.DisplayName).ToList();
}
}
public static List<DynamicSite> SiteList {
get {
var _sites = new List<DynamicSite>();
bool bCached = false;
try {
_sites = (List<DynamicSite>)HttpContext.Current.Cache[keyDynamicSite];
if (_sites != null) {
bCached = true;
}
} catch {
bCached = false;
}
if (!bCached) {
DataSet ds = ReadDataSetConfig(CMSConfigFileType.SiteMapping, "~/");
_sites = (from d in ds.Tables[0].AsEnumerable()
select new DynamicSite {
DomainName = String.IsNullOrEmpty(d.Field<string>("domname")) ? String.Empty : d.Field<string>("domname").ToLowerInvariant(),
SiteID = new Guid(d.Field<string>("siteid"))
}).ToList();
HttpContext.Current.Cache.Insert(keyDynamicSite, _sites, null, DateTime.Now.AddMinutes(5), Cache.NoSlidingExpiration);
}
return _sites;
}
}
public static DynamicSite DynSite {
get {
DynamicSite _site = new DynamicSite();
string ModuleKey = keyDynSite + DomainName;
bool bCached = false;
try {
_site = (DynamicSite)HttpContext.Current.Cache[ModuleKey];
if (_site != null) {
bCached = true;
}
} catch {
bCached = false;
}
if ((SiteList.Any()) && !bCached) {
_site = (from ss in SiteList
where ss.DomainName == DomainName
select ss).FirstOrDefault();
HttpContext.Current.Cache.Insert(ModuleKey, _site, null, DateTime.Now.AddMinutes(5), Cache.NoSlidingExpiration);
}
return _site;
}
}
public static bool CheckRequestedFileExistence(string templateFileName, Guid siteID) {
var _tmplts = GetTmplateStatus();
CMSFilePath tmp = _tmplts.Where(x => x.TemplateFile.ToLowerInvariant() == templateFileName.ToLowerInvariant() && x.SiteID == siteID).FirstOrDefault();
if (tmp == null) {
tmp = new CMSFilePath(templateFileName, siteID);
_tmplts.Add(tmp);
#if DEBUG
Debug.WriteLine(" ================ " + DateTime.UtcNow.ToString() + " ================");
Debug.WriteLine("Grabbed file : CheckRequestedFileExistence(string templateFileName, Guid siteID) " + templateFileName);
#endif
}
SaveTmplateStatus(_tmplts);
return tmp.FileExists;
}
public static bool CheckFileExistence(string templateFileName) {
var _tmplts = GetTmplateStatus();
CMSFilePath tmp = _tmplts.Where(x => x.TemplateFile.ToLowerInvariant() == templateFileName.ToLowerInvariant() && x.SiteID == Guid.Empty).FirstOrDefault();
if (tmp == null) {
tmp = new CMSFilePath(templateFileName);
_tmplts.Add(tmp);
#if DEBUG
Debug.WriteLine(" ================ " + DateTime.UtcNow.ToString() + " ================");
Debug.WriteLine("Grabbed file : CheckFileExistence(string templateFileName) " + templateFileName);
#endif
}
SaveTmplateStatus(_tmplts);
return tmp.FileExists;
}
private static void SaveTmplateStatus(List<CMSFilePath> fileState) {
HttpContext.Current.Cache.Insert(keyTemplateFiles, fileState, null, DateTime.Now.AddMinutes(10), Cache.NoSlidingExpiration);
}
private static List<CMSFilePath> GetTmplateStatus() {
var _tmplts = new List<CMSFilePath>();
try { _tmplts = (List<CMSFilePath>)HttpContext.Current.Cache[keyTemplateFiles]; } catch { }
if (_tmplts == null) {
_tmplts = new List<CMSFilePath>();
}
_tmplts.RemoveAll(x => x.DateChecked < DateTime.UtcNow.AddSeconds(-30));
_tmplts.RemoveAll(x => x.DateChecked < DateTime.UtcNow.AddSeconds(-10) && x.SiteID != Guid.Empty);
return _tmplts;
}
//=========================
public static TimeZoneInfo GetLocalTimeZoneInfo() {
TimeZoneInfo oTZ = TimeZoneInfo.Local;
return oTZ;
}
public static TimeZoneInfo GetSiteTimeZoneInfo(string timeZoneIdentifier) {
TimeZoneInfo oTZ = GetLocalTimeZoneInfo();
if (!String.IsNullOrEmpty(timeZoneIdentifier)) {
try { oTZ = TimeZoneInfo.FindSystemTimeZoneById(timeZoneIdentifier); } catch { }
}
return oTZ;
}
public static DateTime ConvertUTCToSiteTime(DateTime dateUTC, string timeZoneIdentifier) {
TimeZoneInfo oTZ = GetSiteTimeZoneInfo(timeZoneIdentifier);
return TimeZoneInfo.ConvertTimeFromUtc(dateUTC, oTZ);
}
public static DateTime ConvertSiteTimeToUTC(DateTime dateSite, string timeZoneIdentifier) {
TimeZoneInfo oTZ = GetSiteTimeZoneInfo(timeZoneIdentifier);
return TimeZoneInfo.ConvertTimeToUtc(dateSite, oTZ);
}
//===================
public static string InactivePagePrefix {
get {
return "☒ ";
}
}
public static string RetiredPagePrefix {
get {
return "♻ ";
}
}
public static string UnreleasedPagePrefix {
get {
return "⚠ ";
}
}
public static string PendingDeletePrefix {
get {
return "⛔ ";
}
}
public static SiteNav IdentifyLinkAsInactive(SiteNav nav) {
if (nav != null) {
if (!nav.PageActive) {
nav.NavMenuText = InactivePagePrefix + nav.NavMenuText;
nav.PageHead = InactivePagePrefix + nav.PageHead;
nav.TitleBar = InactivePagePrefix + nav.TitleBar;
}
if (nav.IsRetired) {
nav.NavMenuText = RetiredPagePrefix + nav.NavMenuText;
nav.PageHead = RetiredPagePrefix + nav.PageHead;
nav.TitleBar = RetiredPagePrefix + nav.TitleBar;
}
if (nav.IsUnReleased) {
nav.NavMenuText = UnreleasedPagePrefix + nav.NavMenuText;
nav.PageHead = UnreleasedPagePrefix + nav.PageHead;
nav.TitleBar = UnreleasedPagePrefix + nav.TitleBar;
}
}
return nav;
}
public static ContentPage IdentifyLinkAsInactive(ContentPage cp) {
if (cp != null) {
if (!cp.PageActive) {
cp.NavMenuText = InactivePagePrefix + cp.NavMenuText;
cp.PageHead = InactivePagePrefix + cp.PageHead;
cp.TitleBar = InactivePagePrefix + cp.TitleBar;
}
if (cp.IsRetired) {
cp.NavMenuText = RetiredPagePrefix + cp.NavMenuText;
cp.PageHead = RetiredPagePrefix + cp.PageHead;
cp.TitleBar = RetiredPagePrefix + cp.TitleBar;
}
if (cp.IsUnReleased) {
cp.NavMenuText = UnreleasedPagePrefix + cp.NavMenuText;
cp.PageHead = UnreleasedPagePrefix + cp.PageHead;
cp.TitleBar = UnreleasedPagePrefix + cp.TitleBar;
}
}
return cp;
}
public static PostComment IdentifyLinkAsInactive(PostComment pc) {
if (pc != null) {
if (!pc.IsApproved) {
pc.CommenterName = InactivePagePrefix + pc.CommenterName;
}
if (pc.IsSpam) {
pc.CommenterName = RetiredPagePrefix + pc.CommenterName;
}
}
return pc;
}
//=====================
public static string DecodeBase64(string ValIn) {
return Utils.DecodeBase64(ValIn);
}
public static string EncodeBase64(string ValIn) {
return Utils.EncodeBase64(ValIn);
}
public void OverrideKey(Guid guidContentID) {
filePage = null;
using (ContentPageHelper pageHelper = new ContentPageHelper()) {
filePage = pageHelper.FindContentByID(SiteData.CurrentSiteID, guidContentID);
}
}
public void OverrideKey(string sPageName) {
filePage = null;
using (ContentPageHelper pageHelper = new ContentPageHelper()) {
filePage = pageHelper.FindByFilename(SiteData.CurrentSiteID, sPageName);
}
}
protected ContentPage filePage = null;
protected void LoadGuids() {
if (filePage == null) {
using (ContentPageHelper pageHelper = new ContentPageHelper()) {
if (SiteData.IsPageSampler && filePage == null) {
filePage = ContentPageHelper.GetSamplerView();
} else {
if (SiteData.CurrentScriptName.ToLowerInvariant().StartsWith(SiteData.AdminFolderPath)) {
Guid guidPage = Guid.Empty;
if (!String.IsNullOrEmpty(HttpContext.Current.Request.QueryString["pageid"])) {
guidPage = new Guid(HttpContext.Current.Request.QueryString["pageid"].ToString());
}
filePage = pageHelper.FindContentByID(SiteData.CurrentSiteID, guidPage);
} else {
filePage = pageHelper.FindByFilename(SiteData.CurrentSiteID, SiteData.CurrentScriptName);
}
}
}
}
}
public ContentPage cmsAdminContent {
get {
ContentPage c = null;
try {
string sXML = GetSerialized(keyAdminContent);
if (!String.IsNullOrEmpty(sXML)) {
XmlSerializer xmlSerializer = new XmlSerializer(typeof(ContentPage));
Object genpref = null;
using (StringReader stringReader = new StringReader(sXML)) {
genpref = xmlSerializer.Deserialize(stringReader);
}
c = genpref as ContentPage;
}
} catch (Exception ex) { }
return c;
}
set {
if (value == null) {
ClearSerialized(keyAdminContent);
} else {
XmlSerializer xmlSerializer = new XmlSerializer(typeof(ContentPage));
string sXML = String.Empty;
using (StringWriter stringWriter = new StringWriter()) {
xmlSerializer.Serialize(stringWriter, value);
sXML = stringWriter.ToString();
}
SaveSerialized(keyAdminContent, sXML);
}
}
}
public List<Widget> cmsAdminWidget {
get {
List<Widget> c = null;
string sXML = GetSerialized(keyAdminWidget);
if (!String.IsNullOrEmpty(sXML)) {
XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Widget>));
Object genpref = null;
using (StringReader stringReader = new StringReader(sXML)) {
genpref = xmlSerializer.Deserialize(stringReader);
}
c = genpref as List<Widget>;
}
return c;
}
set {
if (value == null) {
ClearSerialized(keyAdminWidget);
} else {
XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Widget>));
string sXML = String.Empty;
using (StringWriter stringWriter = new StringWriter()) {
xmlSerializer.Serialize(stringWriter, value);
sXML = stringWriter.ToString();
}
SaveSerialized(keyAdminWidget, sXML);
}
}
}
public static void SaveSerialized(Guid itemID, string sKey, string sData) {
using (CarrotCMSDataContext _db = CarrotCMSDataContext.Create()) {
bool bAdd = false;
carrot_SerialCache itm = CompiledQueries.SearchSeriaCache(_db, itemID, sKey);
if (itm == null) {
bAdd = true;
itm = new carrot_SerialCache();
itm.SerialCacheID = Guid.NewGuid();
itm.SiteID = SiteData.CurrentSiteID;
itm.ItemID = itemID;
itm.EditUserId = SecurityData.CurrentUserGuid;
itm.KeyType = sKey;
}
itm.SerializedData = sData;
itm.EditDate = DateTime.UtcNow;
if (bAdd) {
_db.carrot_SerialCaches.InsertOnSubmit(itm);
}
_db.SubmitChanges();
}
}
public static string GetSerialized(Guid itemID, string sKey) {
string sData = String.Empty;
using (CarrotCMSDataContext _db = CarrotCMSDataContext.Create()) {
carrot_SerialCache itm = CompiledQueries.SearchSeriaCache(_db, itemID, sKey);
if (itm != null) {
sData = itm.SerializedData;
}
}
return sData;
}
public static bool ClearSerialized(Guid itemID, string sKey) {
bool bRet = false;
using (CarrotCMSDataContext _db = CarrotCMSDataContext.Create()) {
carrot_SerialCache itm = CompiledQueries.SearchSeriaCache(_db, itemID, sKey);
if (itm != null) {
_db.carrot_SerialCaches.DeleteOnSubmit(itm);
_db.SubmitChanges();
bRet = true;
}
}
return bRet;
}
private void SaveSerialized(string sKey, string sData) {
LoadGuids();
if (filePage != null) {
CMSConfigHelper.SaveSerialized(filePage.Root_ContentID, sKey, sData);
}
}
private string GetSerialized(string sKey) {
string sData = String.Empty;
LoadGuids();
if (filePage != null) {
sData = CMSConfigHelper.GetSerialized(filePage.Root_ContentID, sKey);
}
return sData;
}
private bool ClearSerialized(string sKey) {
LoadGuids();
if (filePage != null) {
return CMSConfigHelper.ClearSerialized(filePage.Root_ContentID, sKey);
} else {
return false;
}
}
public static void CleanUpSerialData() {
using (CarrotCMSDataContext _db = CarrotCMSDataContext.Create()) {
IQueryable<carrot_SerialCache> lst = (from c in _db.carrot_SerialCaches
where c.EditDate < DateTime.UtcNow.AddHours(-6)
select c);
_db.carrot_SerialCaches.BatchDelete(lst);
_db.SubmitChanges();
}
}
}
} | mit |
bmesuere/uni-test | backend/src/test/java/org/unipept/xml/UniprotHandlerTest.java | 1863 | package org.unipept.xml;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.junit.Assert;
import org.junit.Test;
import org.xml.sax.SAXException;
public class UniprotHandlerTest extends Assert {
private class Stats implements UniprotObserver {
public int entries;
public int sequences;
public void handleEntry(UniprotEntry e) {
entries++;
sequences++;
}
public void close() {
}
}
public UniprotHandlerTest() {
}
@Test
public void testHandlerSwissProt_1() {
Stats s = new Stats();
runHandler(new UniprotHandler(5, 50, "swissprot"), s, "../../../uniprot_sprot_1.xml");
assertEquals(s.entries, 1);
assertEquals(s.sequences, 1);
}
@Test
public void testHandlerSwissProt_3() {
Stats s = new Stats();
runHandler(new UniprotHandler(5, 50, "swissprot"), s, "../../../uniprot_sprot_3.xml");
assertEquals(s.entries, 3);
assertEquals(s.sequences, 3);
}
public void runHandler(UniprotHandler handler, UniprotObserver s, String path) {
try {
InputStream in = this.getClass().getResourceAsStream(path);
handler.addObserver(s);
SAXParser xmlParser = SAXParserFactory.newInstance().newSAXParser();
xmlParser.parse(in, handler);
} catch (ParserConfigurationException e) {
e.printStackTrace();
assertTrue(false);
} catch (SAXException e) {
e.printStackTrace();
assertTrue(false);
} catch (IOException e) {
e.printStackTrace();
assertTrue(false);
}
}
}
| mit |
parablesoft/ember-invoicing | tests/integration/components/invoice-summary-test.js | 670 | import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
moduleForComponent('invoice-summary', 'Integration | Component | invoice summary', {
integration: true
});
test('it renders', function(assert) {
// Set any properties with this.set('myProperty', 'value');
// Handle any actions with this.on('myAction', function(val) { ... });
this.render(hbs`{{invoice-summary}}`);
assert.equal(this.$().text().trim(), '');
// Template block usage:
this.render(hbs`
{{#invoice-summary}}
template block text
{{/invoice-summary}}
`);
assert.equal(this.$().text().trim(), 'template block text');
});
| mit |
lindsayad/programming | cpp/switch_case.cpp | 280 | #include <iostream>
using namespace std;
int main () {
int a = 10;
const int b = 10;
const int c = 20;
switch ( a ) {
case b:
cout << a << endl;
break;
case c:
cout << a << endl;
break;
default:
cout << a << endl;
break;
}
return 0;
}
| mit |
camcima/mundipagg-php-client | src/MundiPagg/Entity/Enum/EmailUpdateToBuyerEnum.php | 345 | <?php
namespace MundiPagg\Entity\Enum;
/**
* Email Update To Buyer Enum
*
* @author Carlos Cima
*/
class EmailUpdateToBuyerEnum
{
/**
* Email Update To Buyer Enumerator
*/
const YES = 'Yes';
const NO = 'No';
const YES_IF_AUTHORIZED = 'YesIfAuthorized';
const YES_IF_NOT_AUTHORIZED = 'YesIfNotAuthorized';
}
| mit |
tekulvw/Squid-Plugins | tickets/tickets.py | 6513 | from discord.ext import commands
from cogs.utils.dataIO import fileIO
from cogs.utils import checks
from __main__ import send_cmd_help
import os
class Tickets:
def __init__(self, bot):
self.bot = bot
self.tickets = fileIO("data/tickets/tickets.json", "load")
self.settings = fileIO("data/tickets/settings.json", "load")
@property
def ticket_limit(self):
num = self.settings.get("TICKETS_PER_USER", -1)
if num == -1:
self.ticket_limit = 0
num = 0
return num
@ticket_limit.setter
def ticket_limit(self, num):
self.settings["TICKETS_PER_USER"] = num
fileIO("data/tickets/settings.json", "save", self.settings)
@property
def keep_on_read(self):
ret = self.settings.get("KEEP_ON_READ")
if ret is None:
self.keep_on_read = False
ret = False
return ret
@keep_on_read.setter
def keep_on_read(self, value):
self.settings["KEEP_ON_READ"] = bool(value)
fileIO("data/tickets/settings.json", "save", self.settings)
@property
def reply_to_user(self):
ret = self.settings.get("REPLY_TO_USER")
if ret is None:
ret = False
self.reply_to_user = ret
return ret
@reply_to_user.setter
def reply_to_user(self, val):
self.settings["REPLY_TO_USER"] = val
fileIO("data/tickets/settings.json", "save", self.settings)
def _get_ticket(self):
if len(self.tickets) > 0:
ticket = self.tickets[0]
for idnum in ticket:
ret = ticket[idnum].get(
"name", "no_name") + ": " + \
ticket[idnum].get("message", "no_message")
if not self.keep_on_read:
self.tickets = self.tickets[1:]
fileIO("data/tickets/tickets.json", "save", self.tickets)
return ret
else:
return "No more tickets!"
def _get_number_tickets(self, author):
idnum = author.id
num = len([x for ticket in self.tickets for x in ticket if x == idnum])
return num
def _add_ticket(self, author, message):
self.tickets.append(
{author.id: {"name": author.name, "message": message}})
fileIO("data/tickets/tickets.json", "save", self.tickets)
@commands.command(aliases=["nt"], pass_context=True)
@checks.mod_or_permissions(manage_messages=True)
async def nextticket(self, ctx):
"""Gets the next ticket"""
if self.reply_to_user:
reply = ctx.message.author
else:
reply = ctx.message.channel
await self.bot.send_message(reply, self._get_ticket())
@commands.command(pass_context=True)
async def ticket(self, ctx, *, message):
"""Adds ticket.
Example: [p]ticket The quick brown fox? -> adds ticket"""
if self.ticket_limit != 0 and \
self._get_number_tickets(ctx.message.author) >= \
self.ticket_limit:
await self.bot.say("{}, you've reached the ticket limit!".format(
ctx.message.author.mention))
return
self._add_ticket(ctx.message.author, message)
await self.bot.say("{}, ticket added.".format(
ctx.message.author.mention))
@commands.command(aliases=['ct'])
@checks.mod_or_permissions(manage_messages=True)
async def cleartickets(self):
"""Clears all tickets"""
self.tickets = []
fileIO("data/tickets/tickets.json", "save", self.tickets)
await self.bot.say("Tickets cleared.")
@commands.command(aliases=["dt"], pass_context=True)
@checks.mod_or_permissions(manage_messages=True)
async def deleteticket(self, ctx, num: int=1):
"""Deletes any number of tickets, default = 1"""
if num < 0:
await send_cmd_help(ctx)
return
if num > len(self.tickets):
num = len(self.tickets)
self.tickets = []
else:
self.tickets = self.tickets[num:]
fileIO("data/tickets/tickets.json", "save", self.tickets)
await self.bot.say("{} tickets deleted.\n{} tickets remaining.".format(
num, len(self.tickets)))
@commands.group(pass_context=True)
@checks.admin_or_permissions(manage_server=True)
async def ticketset(self, ctx):
"""Ticket cog settings"""
if ctx.invoked_subcommand is None:
await send_cmd_help(ctx)
msg = "```"
for k, v in self.settings.items():
msg += str(k) + ": " + str(v) + "\n"
msg += "```"
await self.bot.say(msg)
@ticketset.command(name="limit", pass_context=True)
async def tickets_per_user(self, ctx, num: int):
"""Limits the number of tickets a user can have 0 = infinite."""
if num < 0:
await send_cmd_help(ctx)
return
self.settings["TICKETS_PER_USER"] = num
fileIO("data/tickets/settings.json", "save", self.settings)
await self.bot.say("Tickets per user set to {}".format(num))
@ticketset.command(name="keep", pass_context=True)
async def _keep_on_read(self, ctx, val: bool):
"""Determines whether the ticket is kept after it has been read.
- True/False"""
self.keep_on_read = val
await self.bot.say("Keep on read set to {}".format(val))
@ticketset.command(name="pm")
async def reply_to(self, boolvar: bool):
"""Determines whether !nextticket replies in a pm or not
- True/False"""
if boolvar:
self.reply_to_user = True
else:
self.reply_to_user = False
await self.bot.say("PM set to {}".format(boolvar))
def check_folder():
if not os.path.exists("data/tickets"):
print("Creating data/tickets folder...")
os.makedirs("data/tickets")
def check_file():
tickets = []
settings = {"TICKETS_PER_USER": 1,
"REPLY_TO_USER": False, "KEEP_ON_READ": False}
f = "data/tickets/tickets.json"
if not fileIO(f, "check"):
print("Creating default tickets's tickets.json...")
fileIO(f, "save", tickets)
f = "data/tickets/settings.json"
if not fileIO(f, "check"):
print("Creating default tickets's settings.json...")
fileIO(f, "save", settings)
def setup(bot):
check_folder()
check_file()
n = Tickets(bot)
bot.add_cog(n)
| mit |
hosim/configue | spec/samples/base_namespace_conf.rb | 199 | # coding: utf-8
require "configue"
class BaseNamespaceConf < Configue::Container
config.source_dir "#{File.dirname(__FILE__)}/namespace"
config.base_namespace :base
config.namespace :test
end
| mit |
int32bit/mistral-actions | tools/install_venv.py | 2434 | # Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2010 OpenStack Foundation
# Copyright 2013 IBM Corp.
#
# 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.
from __future__ import print_function
import os
import sys
import install_venv_common as install_venv
def print_help(venv, root):
help = """
Mistral development environment setup is complete.
Mistral development uses virtualenv to track and manage Python dependencies
while in development and testing.
To activate the Mistral virtualenv for the extent of your current shell
session you can run:
$ source %s/bin/activate
Or, if you prefer, you can run commands in the virtualenv on a case by case
basis by running:
$ %s/tools/with_venv.sh <your command>
Also, make test will automatically use the virtualenv.
"""
print(help % (venv, root))
def main(argv):
root = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
if os.environ.get('tools_path'):
root = os.environ['tools_path']
venv = os.path.join(root, '.venv')
if os.environ.get('venv'):
venv = os.environ['venv']
pip_requires = os.path.join(root, 'requirements.txt')
test_requires = os.path.join(root, 'test-requirements.txt')
py_version = "python%s.%s" % (sys.version_info[0], sys.version_info[1])
project = 'Mistral'
install = install_venv.InstallVenv(root, venv, pip_requires, test_requires,
py_version, project)
options = install.parse_args(argv)
install.check_python_version()
install.check_dependencies()
install.create_virtualenv(no_site_packages=options.no_site_packages)
install.install_dependencies()
print_help(venv, root)
if __name__ == '__main__':
sys.exit(main(sys.argv))
| mit |
cyplp/chaton | chaton/models/comment.py | 280 | import couchdbkit
class Comment(couchdbkit.Document):
"""
"""
owner = couchdbkit.StringProperty()
userid = couchdbkit.StringProperty()
content = couchdbkit.StringProperty()
created = couchdbkit.DateTimeProperty()
videoid = couchdbkit.StringProperty()
| mit |
mkpetrov/CSharpAdvanced | StacksAndQueues/Truck Tour/TruckTour.cs | 1114 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TruckTour_06
{
public class TruckTour
{
public static void Main(string[] args)
{
decimal n = decimal.Parse(Console.ReadLine());
decimal startPump = 0;
decimal fuelLeft = 0;
for (decimal i = 0; i < n; i++)
{
List<decimal> pair = Console.ReadLine()
.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Select(decimal.Parse)
.ToList();
decimal gasPump = pair[0];
decimal distanceToNext = pair[1];
fuelLeft += gasPump;
if (fuelLeft >= distanceToNext)
{
fuelLeft -= distanceToNext;
}
else
{
startPump = i + 1;
fuelLeft = 0;
}
}
Console.WriteLine($"{startPump}");
}
}
} | mit |
apps-m/inapphelp-android | InapphelpExample/src/com/example/inapphelpexample/MainActivity.java | 2144 | package com.example.inapphelpexample;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import com.example.inapphelpexample.R;
import ru.appsm.inapphelp.IAHHelpDesk;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setDisplayUseLogoEnabled(false);
getSupportActionBar().setIcon(R.color.iah_transparent_color);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
rootView.findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
IAHHelpDesk.showHelp(getActivity());
}
});
return rootView;
}
}
}
| mit |
linder0209/zhaopai | app/scripts/views/index.js | 485 | (function (view) {
'use strict';
view.index = {};
//首页 脚本
$.extend(view.index, {
init: function () {
this.flexSlider();
},
flexSlider: function(){
// The slider being synced must be initialized first
$('#flexSlider').flexslider({
slideshowSpeed: 3500,
animationSpeed: 300,
animation: 'slide',
controlNav: 'thumbnails',
controlsContainer: '#controlsContainer'
});
}
});
})(hopeView);
| mit |
thoughtbot/cocaine | lib/cocaine.rb | 341 | # coding: UTF-8
require 'terrapin'
Cocaine = Terrapin
$stderr.puts [
"===========================================\n",
"DEPRECATION: The cocaine gem is deprecated.",
"Please upgrade to terrapin.",
"See https://github.com/thoughtbot/terrapin/ for further instructions.",
"\n==========================================="
].join(" ")
| mit |
puaykai/noodles | target/work/plugins/spring-security-core-2.0.0/src/java/grails/plugin/springsecurity/web/access/expression/WebExpressionConfigAttribute.java | 1692 | /* Copyright 2006-2015 the original author or authors.
*
* 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.
*/
package grails.plugin.springsecurity.web.access.expression;
import org.springframework.expression.Expression;
import org.springframework.security.access.ConfigAttribute;
/**
* Simple expression configuration attribute for use in web request authorizations.
* Based on the class of the same name in Spring Security which is package-default.
*
* @author Luke Taylor
* @author <a href='mailto:burt@burtbeckwith.com'>Burt Beckwith</a>
*/
public class WebExpressionConfigAttribute implements ConfigAttribute {
private static final long serialVersionUID = 1;
protected final Expression expression;
/**
* Constructor.
* @param authorizeExpression the expression
*/
public WebExpressionConfigAttribute(final Expression authorizeExpression) {
expression = authorizeExpression;
}
/**
* Accessor for the expression.
* @return the expression
*/
public Expression getAuthorizeExpression() {
return expression;
}
public String getAttribute() {
return null;
}
@Override
public String toString() {
return expression.getExpressionString();
}
}
| mit |
sanjaymandadi/mozu-java | mozu-javaasync-core/src/main/java/com/mozu/api/clients/platform/TenantExtensionsClient.java | 5550 | /**
* This code was auto-generated by a Codezu.
*
* Changes to this file may cause incorrect behavior and will be lost if
* the code is regenerated.
*/
package com.mozu.api.clients.platform;
import java.util.List;
import java.util.ArrayList;
import com.mozu.api.MozuClient;
import com.mozu.api.MozuClientFactory;
import com.mozu.api.MozuUrl;
import com.mozu.api.Headers;
import com.mozu.api.AsyncCallback;
import java.util.concurrent.CountDownLatch;
import com.mozu.api.security.AuthTicket;
import org.apache.commons.lang.StringUtils;
/** <summary>
* platform/extensions related resources. DOCUMENT_HERE
* </summary>
*/
public class TenantExtensionsClient {
/**
* platform-extensions Get GetExtensions description DOCUMENT_HERE
* <p><pre><code>
* MozuClient<com.mozu.api.contracts.installedapplications.TenantExtensions> mozuClient=GetExtensionsClient();
* client.setBaseAddress(url);
* client.executeRequest();
* TenantExtensions tenantExtensions = client.Result();
* </code></pre></p>
* @return Mozu.Api.MozuClient <com.mozu.api.contracts.installedapplications.TenantExtensions>
* @see com.mozu.api.contracts.installedapplications.TenantExtensions
*/
public static MozuClient<com.mozu.api.contracts.installedapplications.TenantExtensions> getExtensionsClient() throws Exception
{
return getExtensionsClient( null);
}
/**
* platform-extensions Get GetExtensions description DOCUMENT_HERE
* <p><pre><code>
* MozuClient<com.mozu.api.contracts.installedapplications.TenantExtensions> mozuClient=GetExtensionsClient( responseFields);
* client.setBaseAddress(url);
* client.executeRequest();
* TenantExtensions tenantExtensions = client.Result();
* </code></pre></p>
* @param responseFields A list or array of fields returned for a call. These fields may be customized and may be used for various types of data calls in Mozu. For example, responseFields are returned for retrieving or updating attributes, carts, and messages in Mozu.
* @return Mozu.Api.MozuClient <com.mozu.api.contracts.installedapplications.TenantExtensions>
* @see com.mozu.api.contracts.installedapplications.TenantExtensions
*/
public static MozuClient<com.mozu.api.contracts.installedapplications.TenantExtensions> getExtensionsClient(String responseFields) throws Exception
{
MozuUrl url = com.mozu.api.urls.platform.TenantExtensionsUrl.getExtensionsUrl(responseFields);
String verb = "GET";
Class<?> clz = com.mozu.api.contracts.installedapplications.TenantExtensions.class;
MozuClient<com.mozu.api.contracts.installedapplications.TenantExtensions> mozuClient = (MozuClient<com.mozu.api.contracts.installedapplications.TenantExtensions>) MozuClientFactory.getInstance(clz);
mozuClient.setVerb(verb);
mozuClient.setResourceUrl(url);
return mozuClient;
}
/**
* platform-extensions Put UpdateExtensions description DOCUMENT_HERE
* <p><pre><code>
* MozuClient<com.mozu.api.contracts.installedapplications.TenantExtensions> mozuClient=UpdateExtensionsClient( extensions);
* client.setBaseAddress(url);
* client.executeRequest();
* TenantExtensions tenantExtensions = client.Result();
* </code></pre></p>
* @param extensions Mozu.InstalledApplications.Contracts.TenantExtensions ApiType DOCUMENT_HERE
* @return Mozu.Api.MozuClient <com.mozu.api.contracts.installedapplications.TenantExtensions>
* @see com.mozu.api.contracts.installedapplications.TenantExtensions
* @see com.mozu.api.contracts.installedapplications.TenantExtensions
*/
public static MozuClient<com.mozu.api.contracts.installedapplications.TenantExtensions> updateExtensionsClient(com.mozu.api.contracts.installedapplications.TenantExtensions extensions) throws Exception
{
return updateExtensionsClient( extensions, null);
}
/**
* platform-extensions Put UpdateExtensions description DOCUMENT_HERE
* <p><pre><code>
* MozuClient<com.mozu.api.contracts.installedapplications.TenantExtensions> mozuClient=UpdateExtensionsClient( extensions, responseFields);
* client.setBaseAddress(url);
* client.executeRequest();
* TenantExtensions tenantExtensions = client.Result();
* </code></pre></p>
* @param responseFields A list or array of fields returned for a call. These fields may be customized and may be used for various types of data calls in Mozu. For example, responseFields are returned for retrieving or updating attributes, carts, and messages in Mozu.
* @param extensions Mozu.InstalledApplications.Contracts.TenantExtensions ApiType DOCUMENT_HERE
* @return Mozu.Api.MozuClient <com.mozu.api.contracts.installedapplications.TenantExtensions>
* @see com.mozu.api.contracts.installedapplications.TenantExtensions
* @see com.mozu.api.contracts.installedapplications.TenantExtensions
*/
public static MozuClient<com.mozu.api.contracts.installedapplications.TenantExtensions> updateExtensionsClient(com.mozu.api.contracts.installedapplications.TenantExtensions extensions, String responseFields) throws Exception
{
MozuUrl url = com.mozu.api.urls.platform.TenantExtensionsUrl.updateExtensionsUrl(responseFields);
String verb = "PUT";
Class<?> clz = com.mozu.api.contracts.installedapplications.TenantExtensions.class;
MozuClient<com.mozu.api.contracts.installedapplications.TenantExtensions> mozuClient = (MozuClient<com.mozu.api.contracts.installedapplications.TenantExtensions>) MozuClientFactory.getInstance(clz);
mozuClient.setVerb(verb);
mozuClient.setResourceUrl(url);
mozuClient.setBody(extensions);
return mozuClient;
}
}
| mit |
jnep1009/MapsengerNative | actions/connection.js | 1405 | import {connect, disconnect} from '../services/pubnub';
import {FriendsService} from '../services';
export const CONNECTING = 'CONNECT';
export const CONNECTED = 'CONNECTED';
export const DISCONNECTED = 'DISCONNECTED';
export const STORE_FRIENDS = 'STORE_FRIENDS';
const friendsService = new FriendsService();
export const connectionActions = {
connect(authenticationToken) {
return dispatch => {
dispatch({type: CONNECTING});
let user;
friendsService.getUser(authenticationToken)
.then(res => {
user = res;
// use github id as pubnub uuid
return connect(authenticationToken, user.id)
})
.then(() => {
dispatch({type: CONNECTED, payload: user});
return friendsService.getFriends(authenticationToken);
})
.then(friends => {
dispatch({type: STORE_FRIENDS, payload: friends})
})
.catch(error => {
dispatch({type: DISCONNECTED, payload: {error}});
// Attempt to reconnect on a timer
const reconnect = () => connectionActions.connect(authenticationToken)(dispatch);
setTimeout(reconnect, 1500);
});
};
},
disconnect() {
return dispatch => disconnect()
.then(() => dispatch({type: DISCONNECTED, payload: {}}));
},
failure(error) {
return {type: DISCONNECTED, payload: {error}};
}
};
| mit |
russelljahn/russelljahn.github.io | js/portfolio.js | 13333 | // JavaScript Document
var msnry;
var filters;
var projects = [
// {
// tags: ["programming", "graphics", "opengl", "c++"],
// image: "img/gallery/normalsize_raytracer.jpg",
// thumb: "img/gallery/thumbsize_raytracer.jpg",
// big: "img/gallery/fullsize_raytracer.jpg",
// title: "Graphics Programming: \"Raytracer I\"",
// name: "raytracer1",
// description: "A program that traces light rays to generate an image.",
// },
{
tags: ["gamedev", "programming", "animation", "vfx", "ngui", "mobile", "android", "unity3d", "c#"],
image: "img/kataklysm/kataklysm2.jpg",
title: "Game Development: \"Kataklysm\"",
name: "kataklysm",
description: "Kataklysm is a strategy game for mobile."
},
{
tags: ["gamedev", "programming", "multiplayer", "networking", "graphics", "animation", "vfx", "ngui", "incontrol", "shaders", "unity3d", "c#"],
image: "img/lethal_pursuit/titlescreen_with_menu.jpg",
title: "Game Development: \"Lethal Pursuit\"",
name: "lethal_pursuit",
description: "Lethal Pursuit is a networked multiplayer deathmatch game with spaceships.",
size: "w50"
},
{
tags: ["programming", "graphics", "opengl", "c++", "fltk"],
image: "img/gallery/normalsize_raytracer_grad.jpg",
thumb: "img/gallery/normalsize_raytracer_grad.jpg",
big: "img/gallery/normal_raytracer_grad.jpg",
title: "Graphics Programming: \"Raytracers\"",
name: "raytracer",
description: "A program that traces light rays to generate an image.",
},
{
tags: ["animation", "after effects", "photoshop"],
image: "img/gallery/normalsize_pirate_attack.png",
video: "https://vimeo.com/58861918",
title: "Animation: \"Pirate Attack!\"",
name: "pirate_attack",
description: "This animation was a good chance to explore some of the features of Adobe After Effects. The pirate ship was actually a real Lego ship that I own. I photographed the Lego ship then edited it in Adobe Photoshop so that I could animate it."
},
{
tags: ["gamedev", "programming", "animation", "vfx", "tk2d", "unity3d", "c#"],
image: "img/quantum/quantum1.jpg",
title: "Game Development: \"Quantum\"",
name: "quantum",
description: "Quantum is a side-scrolling puzzle game about a mad scientist who unwittingly breaks his time machine, ending up in the prehistoric past. Professor Quantum must now travel through the space/time rifts he inadvertently created in order to restore his time machine and return home to the present time.",
size: "w50"
},
{
tags: ["animation", "after effects", "photoshop", "opengl", "graphics", "programming", "3d modeling", "flash", "c++"],
image: "img/gallery/normalsize_voyage1.jpg",
video: "https://vimeo.com/64496251",
title: "Animation: \"Voyage\"",
name: "voyage",
description: "This is an abstract animation that explores various color combination strategies.",
size: "w50"
},
{
tags: ["programming", "graphics", "shaders", "animation", "glsl", "opengl", "c++"],
image: "img/shaders/shaders1.jpg",
title: "Graphics Development, GLSL Shaders: \"Stylish Non-Photorealistic Shading\"",
name: "glsl_shaders",
description: "For our final project in Graduate Computer Graphics, my partner and I decided to take 3D models and shade them in cool and artistic ways.",
size: "w50"
},
{
tags: ["programming", "graphics", "opengl", "c++", "fltk"],
image: "img/impressionist/impressionist1.jpg",
title: "Graphics Programming: \"Impressionistic Art\"",
name: "impressionist",
description: "This program provides the user with a variety of brushes to paint over an image, rendering it into impressionistic artwork.",
},
{
tags: ["gamedev", "programming", "vfx", "ngui", "mobile", "android", "unity3d", "c#"],
image: "img/flappy_hunt/flappy_hunt1.jpg",
title: "Game Development: \"Flappy Hunt\"",
name: "flappy_hunt",
description: "Flappy Hunt a web/mobile game where you blast away as many of those infamous Flappy Birds as possible."
},
{
tags: ["animation", "corel painter", "photoshop", "after effects"],
image: "img/gallery/normalsize_rum1.jpg",
video: "https://vimeo.com/62691122",
title: "Animation: \"Rum\"",
name: "rum",
description: "An abstract animation using Corel Painter, Adobe Photoshop, and Adobe After Effects."
},
{
tags: ["programming", "graphics", "animation", "opengl", "c++"],
image: "img/gallery/normalsize_l_system_animated.gif",
thumb: "img/gallery/thumbsize_l_system_animated.gif",
big: "img/gallery/normalsize_l_system_animated.gif",
title: "Graphics Programming: \"Animated Fractal Tree\"",
name: "l_system",
description: "A program that creates animated trees using OpenGL, GLUT, and C++.",
},
// {
// tags: ["animation", "photoshop", "flash"],
// image: "img/gallery/normalsize_magicjar1.png",
// video: "https://vimeo.com/55453100",
// title: "Animation: \"Magic Jar\"",
// name: "magic_jar",
// description: "My first more involved animation project, this piece used the idea of the four classical elements: earth, wind, water, and fire. The initial animation was done using Adobe Flash. Afterwards, each layer was individually tuned up and then composited in Adobe After Effects."
// },
{
tags: ["animation", "flash", "photoshop", "after effects"],
image: "img/gallery/normalsize_shyguy1.jpg",
video: "https://vimeo.com/60533413",
title: "Animation: \"Shy Guy & Fire Elk\"",
name: "shy_guy",
description: "These are part of a trio of animals I did for one of my 2D animation classes. This is actually a Shy Guy from Super Mario that I gave eagle wings. The Shy Guy graphic was created in Adobe Illustrator, while the wing animation was done in Adobe Flash. I then used Adobe After Effects to put the finished Shy Guy in a Super Mario Bros. 2 background, letting him roam free in his natural habitat."
},
// {
// tags: ["gamedev", "programming", "tk2d", "uniwii", "unity3d", "c#"],
// image: "img/sultans_lover/sultans_lover1.png",
// title: "Game Development: \"Sultan's Lover\"",
// name: "sultans_lover",
// description: "Sultan's Lover is a party game created within a 24-hour time span during HackTX 2013."
// },
{
tags: ["art", "photoshop"],
image: "img/abstract_art/thumbsize_psychadelia.jpg",
thumb: "img/abstract_art/thumbsize_psychadelia.jpg",
big: "img/abstract_art/fullsize_psychadelia.jpg",
title: "Photoshop: \"Abstract Designs\"",
name: "abstract_art",
description: "This is a collection of digital art pieces that I created in Adobe Photoshop.",
},
// {
// tags: ["webdev", "programming", "javascript", "jquery", "html", "css", "webdesign"],
// image: "img/wcdb/wcdb1.png",
// title: "Web Development & Design: \"WCDB: World Crisis Database\"",
// name: "wcdb",
// description: "In my Software Engineering class, a team of 5 others and I were tasked to build a Django-powered website to promote awareness of crises in the world.",
// },
];
function hideMasonryItem($item) {
// $item.hide( "fade", { direction: "down" }, "slow" );
$item.hide( "fade", "slow" );
}
function hasTag(projectObject, tagString) {
for (var i = 0; i < projectObject.tags.length; ++i) {
if (projectObject.tags[i] == tagString) {
return true;
}
}
return false;
}
function isTransparentColor(colorString) {
return colorString == "rgba(0, 0, 0, 0)" || colorString == "transparent" || colorString == "rgb(0, 0, 0)";
}
function refilter() {
$projects = $(".masonry_item");
for (var i = 0; i < projects.length; ++i) {
// console.log("i: " + i);
// console.log("projects.length: " + projects.length);
var project = projects[i];
var $project = $projects.eq(i);
var hidProject = false;
// console.log(project);
for (var filterName in filters) {
// console.log(filterName);
var shouldFilter = filters[filterName];
if (shouldFilter) {
// console.log(project);
if (hasTag(project, filterName)) {
// console.log("'" + project.name + "' has tag '" + filterName + "'!");
}
else {
// console.log("'" + project.name + "' DOESN'T have filter tag '" + filterName + "'! Hiding...");
$project.hide("fade", "swing", 400, function() {
msnry.layout();
});
hidProject = true;
break;
}
}
}
/*
At this point, item should be fine to show. Make sure if it was previously
filtered out and hidden, reshow the item.
*/
// console.log($project.is(":visible"));
if (!hidProject && !$project.is(":visible")) {
$project.show("fade", "swing", 400, function() {
msnry.layout();
});
}
}
msnry.layout();
}
function setupMasonry() {
for (var i = 0; i < projects.length; ++i) {
item = projects[i];
if (item["size"] == "w50") {
$(".masonry_container").append('<div class="masonry_item w50"></div>');
}
else {
$(".masonry_container").append('<div class="masonry_item"></div>');
}
}
$(".masonry_item").each(function(index) {
item = projects[index];
if (item["image"] != null) {
textTags = ""
for (var i = 0; i < item.tags.length; ++i) {
textTags += item.tags[i];
if (i != item.tags.length-1) {
textTags += ", ";
}
}
$(this).append(sprintf('<img src="%s" />', item["image"]));
$(this).append(sprintf('<h4 class="text_color_neon_green">%s</h4>', item["title"]));
$(this).append(sprintf('<p class="text_color_sunny_orange">%s</p>', textTags));
}
else {
var r = Math.floor((Math.random() * 255) + 1);
var g = Math.floor((Math.random() * 255) + 1);
var b = Math.floor((Math.random() * 255) + 1);
var a = Math.floor((Math.random() * 255) + 1);
var colorString = sprintf("rgba(%d, %d, %d, %d)", r, g, b, a);
$(this).css("background-color", colorString);
}
});
var foregroundWrapper = $("#foreground_wrapper");
var container = document.querySelector('.masonry_container');
// initialize Masonry after all images have loaded
imagesLoaded( container, function() {
msnry = new Masonry( container );
msnry.layout();
});
console.log("Finished setting up masonry!");
}
// function randomlySizeTags(tagNames, dom) {
// console.log("tagNames: " + tagNames);
// $tags = $(".tags", dom);
// // console.log("$tags: " + $tags);
// // $tagsList = $tags.append("<ul>");
// console.log("$tagsList: " + $tags);
// console.log('tagNames: ' + tagNames);
// for (var i = 0; i < tagNames.length; ++i) {
// var tagName = tagNames[i];
// var randomFontSize = Math.random() * 2 + 1;
// // console.log("randomFontSize: " + randomFontSize);
// var $newTag = $tags.append("<li>" + tagName + "</li>");
// $newTag.css("font-size", randomFontSize + "px");
// console.log("$newTag: " + $newTag);
// }
// // $tags.append("<ul>");
// }
$(document).ready(function() {
setupMasonry();
filters = {};
$filterOptions = $(".filter_option");
$filterOptions.each(function(index, value) {
var filterName = value.textContent;
// console.log(text);
filters[filterName] = false;
});
// console.log(filters);
console.log("Finished setting up filters!");
$(".filter_option").click(function(event) {
var filterName = event.target.textContent;
console.log(filterName);
var $selectedElement = $(this);
var bgColor = $selectedElement.css("background-color");
// console.log(bgColor);
// If enabling filter
if (isTransparentColor(bgColor)) {
$selectedElement.css("background-color", "background:#222;");
filters[filterName] = true;
}
// Else if disabling filter
else {
$selectedElement.css("background-color", "rgba(0, 0, 0, 0);");
filters[filterName] = false;
}
refilter();
});
console.log("Finished setting up filter callbacks!");
var $items = $(".masonry_item");
for (var i = 0; i < $items.length; ++i) {
// console.log("i: " + i);
// console.log("items[i]: " + $items[i]);
// console.log(projects[i].name + '.html');
data = {project: projects[i]};
$items.eq(i).click(data, function(e) {
console.log("e.data.project.name: " + e.data.project.name);
var name = e.data.project.name;
var tagNames = e.data.project.tags;
$.fancybox.open({
href : name + '.html',
type : 'iframe',
// afterLoad : function(current, previous) {
// // randomlySizeTags(e.data.project.tags, $(this));
// console.log("tagNames: " + tagNames);
// $tags = $("#tag_box");
// // console.log("$tags: " + $tags);
// // $tagsList = $tags.append("<ul>");
// console.log("$tagsList: " + $tags);
// // console.log('tagNames: ' + tagNames);
// for (var i = 0; i < tagNames.length; ++i) {
// var tagName = tagNames[i];
// var randomFontSize = Math.random() * 2 + 1;
// // console.log("randomFontSize: " + randomFontSize);
// var $newTag = $tags.append("<li>" + tagName + "</li>");
// $newTag.css("font-size", randomFontSize + "em");
// console.log("$newTag: " + $newTag);
// }
// // $tags.append("<ul>");
// },
padding : 0,
openEffect : 'elastic',
openSpeed : 150,
closeEffect : 'elastic',
closeSpeed : 150,
helpers : {
thumbs : {
width : 50,
height : 50
}
},
arrows: true,
next : 'left',
prev : 'right'
});
});
}
console.log("Finished setting up FancyBox!");
});
| mit |
RalfEggert/phpmagazin.cqrs | module/CQRS/src/CQRS/Command/CommandHandler.php | 922 | <?php
/**
* Zend Framework 2 - PHP-Magazin CQRS
*
* Beispiele für ZF2 & CQRS
*
* @package CQRS
* @author Ralf Eggert <r.eggert@travello.de>
* @link http://www.ralfeggert.de/
*/
/**
* namespace definition and usage
*/
namespace CQRS\Command;
use CQRS\Event\EventHandlerInterface;
/**
* Class CommandHandler
*
* @package CQRS
*/
class CommandHandler implements CommandHandlerInterface
{
/**
* @var EventHandlerInterface
*/
protected $eventHandler;
/**
* @param EventHandlerInterface $eventHandler
*/
public function __construct(EventHandlerInterface $eventHandler)
{
$this->eventHandler = $eventHandler;
}
/**
* @param CommandInterface $command
*/
public function execute(CommandInterface $command)
{
$this->eventHandler->trigger(
$command->getCommandName(), __CLASS__, $command
);
}
} | mit |
sumory/openresty-china | app/routes/auth.lua | 3888 | local pairs = pairs
local ipairs = ipairs
local smatch = string.match
local slower = string.lower
local ssub = string.sub
local slen = string.len
local cjson = require("cjson")
local utils = require("app.libs.utils")
local pwd_secret = require("app.config.config").pwd_secret
local lor = require("lor.index")
local user_model = require("app.model.user")
local auth_router = lor:Router()
auth_router:get("/login", function(req, res, next)
res:render("login")
end)
auth_router:get("/sign_up", function(req, res, next)
res:render("sign_up")
end)
auth_router:post("/sign_up", function(req, res, next)
local username = req.body.username
local password = req.body.password
local pattern = "^[a-zA-Z][0-9a-zA-Z_]+$"
local match, err = smatch(username, pattern)
if not username or not password or username == "" or password == "" then
return res:json({
success = false,
msg = "用户名和密码不得为空."
})
end
local username_len = slen(username)
local password_len = slen(password)
if username_len<4 or username_len>50 then
return res:json({
success = false,
msg = "用户名长度应为4~50位."
})
end
if password_len<6 or password_len>50 then
return res:json({
success = false,
msg = "密码长度应为6~50位."
})
end
if not match then
return res:json({
success = false,
msg = "用户名只能输入字母、下划线、数字,必须以字母开头."
})
end
local result, err = user_model:query_by_username(username)
local isExist = false
if result and not err then
isExist = true
end
if isExist == true then
return res:json({
success = false,
msg = "用户名已被占用,请修改."
})
else
password = utils.encode(password .. "#" .. pwd_secret)
local avatar = ssub(username, 1, 1) .. ".png" --取首字母作为默认头像名
avatar = slower(avatar)
local result, err = user_model:new(username, password, avatar)
if result and not err then
return res:json({
success = true,
msg = "注册成功."
})
else
return res:json({
success = false,
msg = "注册失败."
})
end
end
end)
auth_router:post("/login", function(req, res, next)
local username = req.body.username
local password = req.body.password
if not username or not password or username == "" or password == "" then
return res:json({
success = false,
msg = "用户名和密码不得为空."
})
end
local isExist = false
local userid = 0
password = utils.encode(password .. "#" .. pwd_secret)
local result, err = user_model:query(username, password)
local user = {}
if result and not err then
if result and #result == 1 then
isExist = true
user = result[1]
userid = user.id
end
else
isExist = false
end
if isExist == true then
req.session.set("user", {
username = username,
userid = userid,
create_time = user.create_time or ""
})
return res:json({
success = true,
msg = "登录成功."
})
else
return res:json({
success = false,
msg = "用户名或密码错误,请检查!"
})
end
end)
auth_router:get("/logout", function(req, res, next)
res.locals.login = false
res.locals.username = ""
res.locals.userid = 0
res.locals.create_time = ""
req.session.destroy()
res:redirect("/index")
end)
return auth_router
| mit |
Chris35Wills/Chris35Wills.github.io | courses/examples/Intermediate_python/funcs.py | 269 | def subtract(a,b):
c=a-b
return c
def summate(a,b):
c=a+b
return c
def sumKM(a,b):
c=(a+b)/1000.
return c
def minusX10(a,b):
c = (a-b)*10
return c
def divAdd5(a,b):
c = (a/b)+5
return c
if __name__ == "__main__":
print("Run from import") | mit |
sbis-team/ui-customizer-src | script/src/js/TaskToolbarBtns.js | 13255 | UICustomizerDefine('TaskToolbarBtns', ['Engine'], function (Engine) {
'use strict';
const PARSE_ERROR = 'TaskToolbarBtns: Ошибка разбора карточки задачи';
const ReplaceDocTypeName = {
'Ошибка в разработку': 'Ошибка',
'Задача в разработку': 'Задача'
};
const taskDialogClass = 'edo3-Dialog';
const toolbarClass = '.edo3-Dialog__head-firstLine-buttons';
var property = {
btns: {
TaskURL: {
icon: 'link'
},
BranchName: {
icon: 'git-branch'
},
СommitMsg: {
icon: 'git-commit'
},
PullRequest: {
icon: 'git-pull-request'
}
},
ApplyDocTypeName: ['Ошибка', 'Задача'],
selectors: {
'Print': '.SBIS-UI-Customizer-TaskToolbarBtns-TaskToolbarBtns .controls-Toolbar__item[title="Распечатать"]',
'LinkOld': '.SBIS-UI-Customizer-TaskToolbarBtns-TaskToolbarBtns .controls-Toolbar__item[title="Скопировать в буфер"]',
'Delete': '.SBIS-UI-Customizer-TaskToolbarBtns-TaskToolbarBtns .controls-Toolbar__item[title="Удалить"]'
}
};
var BranchNameUserLogin = '';
var idReadedUserLogin = false;
var modulesProperties = {};
var isListener = false;
var taskChangeCache = new WeakMap();
var toolbarSources = new WeakMap();
return {
applySettings: applySettings,
copyToClipboard: copyToClipboard,
createPullRequest: createPullRequest,
_resolve_edo_dialog_record: _resolve_edo_dialog_record,
_get_doc_number: _get_doc_number,
_get_doc_author: _get_doc_author,
_get_doc_name: _get_doc_name,
_get_doc_date: _get_doc_date,
_get_doc_url: _get_doc_url,
_get_doc_description: _get_doc_description
};
function applySettings(settings, moduleName, moduleProperty) {
var group, css = '';
moduleName = moduleName ? moduleName : 'TaskToolbarBtns';
moduleProperty = moduleProperty ? moduleProperty : property;
group = settings.options.Hide;
for (let name in group.options) {
if (group.options[name].value) {
css += Engine.generateCSS.displayNone(moduleProperty.selectors[name]);
}
}
group = settings.options.Add;
let addExtraButtons = false;
moduleProperty.ExtraButtonsHTML = '';
for (let name in group.options) {
if (group.options[name].value) {
addExtraButtons = true;
let btn = Engine.getHTML(moduleName + '-' + name);
btn = btn.replace(/\{\{icon\}\}/, Engine.getSVG(moduleProperty.btns[name].icon));
moduleProperty.ExtraButtonsHTML += btn;
}
}
if (addExtraButtons) {
let extbtn = Engine.getCSS('TaskToolbarBtns-ExtraButtons');
if (moduleName !== 'TaskToolbarBtns') {
extbtn = extbtn.replace(/TaskToolbarBtns/g, moduleName);
}
css += extbtn;
}
if (css) {
Engine.appendCSS(moduleName, css);
} else {
Engine.removeCSS(moduleName);
}
if (addExtraButtons || !!css) {
modulesProperties[moduleName] = { moduleProperty, addExtraButtons, css: !!css };
} else {
delete modulesProperties[moduleName];
}
if (Object.keys(modulesProperties).length > 0) {
if (!isListener) {
const edo3Dialog = document.querySelector('.' + taskDialogClass);
if (edo3Dialog) {
taskFinderHandler({ srcElement: edo3Dialog });
}
document.addEventListener('DOMNodeInserted', taskFinderHandler);
isListener = true;
}
} else {
if (isListener) {
document.removeEventListener('DOMNodeInserted', taskFinderHandler);
isListener = false;
}
}
}
function taskFinderHandler(event) {
const srcElement = event.srcElement;
if (srcElement && srcElement.classList && srcElement.classList.contains(taskDialogClass)) {
srcElement.addEventListener('DOMNodeRemovedFromDocument', taskRemoverHandler);
srcElement.addEventListener('DOMSubtreeModified', taskModifierHandler);
}
}
function taskRemoverHandler(event) {
const srcElement = event.srcElement;
if (srcElement && srcElement.classList && srcElement.classList.contains(taskDialogClass)) {
srcElement.removeEventListener('DOMNodeRemovedFromDocument', taskRemoverHandler);
srcElement.removeEventListener('DOMSubtreeModified', taskModifierHandler);
}
}
function taskModifierHandler(event) {
const edo3Dialog = event.currentTarget;
if (edo3Dialog.controlNodes && edo3Dialog.controlNodes[0] && edo3Dialog.controlNodes[0].control) {
const control = edo3Dialog.controlNodes[0].control;
const controlRecord = control._options ? control._options.record : null;
if (controlRecord && controlRecord !== taskChangeCache.get(control)) {
taskChangeCache.set(control, controlRecord);
prepareTask(edo3Dialog, control, controlRecord);
}
}
}
function prepareTask(edo3Dialog, control, controlRecord) {
const docName = _get_doc_name(controlRecord);
let moduleName = null;
let moduleProps = null;
for (const _moduleName in modulesProperties) {
const props = modulesProperties[_moduleName];
const moduleProperty = props.moduleProperty;
if (moduleProperty.ApplyDocTypeName && ~moduleProperty.ApplyDocTypeName.indexOf(docName) ||
moduleProperty.ExcludeDocTypeName && !~moduleProperty.ExcludeDocTypeName.indexOf(docName)) {
moduleName = _moduleName;
moduleProps = props;
break;
}
}
const toolbar = edo3Dialog.querySelector(toolbarClass);
const oldBtns = toolbar.querySelector('.SBIS-UI-Customizer-TaskToolbarBtns-ExtraButtons');
if (oldBtns) {
oldBtns.remove();
}
toolbar.classList.forEach(clsName => {
if (clsName.startsWith('SBIS-UI-Customizer-TaskToolbarBtns-')) {
toolbar.classList.remove(clsName);
}
});
if (moduleProps) {
if (moduleProps.addExtraButtons) {
let btns = document.createElement('div');
btns.className = 'SBIS-UI-Customizer-TaskToolbarBtns-ExtraButtons ';
btns.innerHTML = moduleProps.moduleProperty.ExtraButtonsHTML;
btns.setAttribute('data-vdomignore', 'true');
toolbar.insertBefore(btns, toolbar.children[0]);
}
if (moduleProps.css) {
toolbar.classList.add('SBIS-UI-Customizer-TaskToolbarBtns-' + moduleName);
}
}
}
function _get_doc_url(record) {
var uuid = record.get('РП.Документ').get('ИдентификаторПереписки');
return location.protocol + '//' + location.host + '/doc/' + uuid;
}
function _get_doc_name(record) {
var docName = record.get('РП.Документ').get('Регламент').get('Название');
docName = ReplaceDocTypeName[docName] || docName;
return docName;
}
function _get_doc_date(record) {
var doc_date = Engine.getDate(record.get('Документ.Дата'));
return doc_date;
}
function _get_doc_number(record) {
var numb = record.get('Документ.Номер') || record.get('Номер');
return numb;
}
function _get_doc_author(record) {
var author = record.get('Сотрудник.Название');
return author;
}
function _get_doc_version(record) {
var flds = record.get('РП.ПоляДляРендера');
var milestone = ((flds || {})['ВехаДокумента'] || {}).name || '';
var version = milestone.split(' ')[0] || '';
if (!/^[\d.]+$/.test(version)) {
if (!milestone && record.get('РП.ВехаДокумента')) {
const enumerator = record.get('РП.ВехаДокумента').getEnumerator();
while (enumerator.moveNext()) {
milestone = enumerator.getCurrent();
milestone = milestone.get('ДокументРасширение.Название');
const __version = milestone.split(' ')[0] || '';
if (/^[\d.]+$/.test(__version)) {
version = __version;
break;
}
}
}
}
return version || 'dev';
}
function _get_doc_description(record) {
var flds = record.get('РП.ПоляДляРендера');
var description = (flds || {}).Description;
if (!description) {
description = Engine.cutOverflow(Engine.cutTags(record.get('РазличныеДокументы.Информация') || ''), 98, 1024);
}
if (!description) {
description = Engine.cutOverflow(Engine.textFromJSON(record.get('РазличныеДокументы.ИнформацияJSON') || '[]'), 98, 1024);
}
return description;
}
function _get_doc_commit_description(record) {
var docName = _get_doc_name(record);
var docNumber = ' № ' + _get_doc_number(record);
var version = ' веха ' + _get_doc_version(record);
var date = ' от ' + _get_doc_date(record);
var author = ' ' + _get_doc_author(record);
var utl = _get_doc_url(record);
var description = _get_doc_description(record);
return docName + docNumber + version + date + author + '\n' + utl + '\n\n' + description;
}
function _get_doc_branch_name(record) {
var version = _get_doc_version(record);
var prefix = _get_doc_name(record) === 'Ошибка' ? 'bugfix' : 'feature';
var docNumber = _get_doc_number(record);
if (!/^[\d.]+$/.test(version)) {
version = 'dev';
}
return version + '/' + prefix + '/' + (BranchNameUserLogin ? BranchNameUserLogin + '/' : '') + docNumber;
}
function _resolve_edo_dialog(elm) {
var edo3Dialog = elm;
while (edo3Dialog && !edo3Dialog.classList.contains('edo3-Dialog')) {
edo3Dialog = edo3Dialog.parentElement;
}
if (edo3Dialog && edo3Dialog.controlNodes && edo3Dialog.controlNodes[0]) {
edo3Dialog = edo3Dialog.controlNodes[0];
} else {
console.error(PARSE_ERROR);
return false;
}
return edo3Dialog;
}
function _resolve_edo_dialog_record(elm) {
var edo3Dialog = _resolve_edo_dialog(elm);
var record = (edo3Dialog.control || {}).record || (edo3Dialog.options || {}).record;
if (!record) {
console.error(PARSE_ERROR);
return false;
}
return record;
}
function copyToClipboard(elm, action) {
var msg = '';
var text = '';
var record = _resolve_edo_dialog_record(elm);
switch (action) {
case 'СommitMsg':
msg = 'Описание скопировано в буфер обмена';
text = _get_doc_commit_description(record);
break;
case 'TaskURL':
msg = 'Ссылка скопирована в буфер обмена';
text = _get_doc_url(record);
break;
case 'BranchName':
if (!idReadedUserLogin) {
return _readUserLogin(function () {
copyToClipboard(elm, action);
});
}
text = _get_doc_branch_name(record);
msg = 'Имя ветки скопировано в буфер обмена:\n' + text;
if (text.startsWith('dev')) {
msg = 'Не удалось определить версию по вехе, для ветки указан \'dev\'.\n' + msg;
}
break;
}
Engine.copyToClipboard(text);
Engine.openInformationPopup(msg);
}
function createPullRequest(elm) {
var edo3Dialog = _resolve_edo_dialog(elm);
var self = edo3Dialog.control;
var record = self.record;
var id = 'linkedDocuments';
//copyToClipboard(elm, 'BranchName'); // Сделать авто-заполнение вехи в МР
Engine.waitRequire(require => {
require(['EDO3/Document/Toolbar/Source'], ToolbarSource => {
let toolbarSource = toolbarSources.get(self);
if (!toolbarSource) {
toolbarSource = new ToolbarSource({
options: {
linkedDocs: self.linkedDocs,
objectName: record && record.getModelField('РП.Документ/ИмяОбъекта'),
ruleId: record && record.getModelField('ИдРегламента'),
docId: record && record.getModelField('РП.Документ/ИдО'),
isIncoming: record && record.getModelField('РП.Документ/Состояние/Подписание/Входящий'),
id: id
}
});
toolbarSources.set(self, toolbarSource);
}
toolbarSource.query().addCallback(data => {
const enumerator = data.getEnumerator();
while (enumerator.moveNext()) {
const item = enumerator.getCurrent();
if (item.get('title') === 'Merge request') {
self._toolbarItemClickHandler({ target: edo3Dialog }, item);
break;
}
}
});
});
});
}
function _readUserLogin(callback) {
if (!idReadedUserLogin) {
idReadedUserLogin = true;
Engine.rpc.sbis({
service: 'auth',
method: 'САП.ТекущийПользователь',
callback: function (data) {
BranchNameUserLogin = data.getRow().get('ЛогинПользователя');
callback();
}
});
} else {
callback();
}
}
});
| mit |
Yuji-Yamamoto-Recruit/rails-split-demo | app/controllers/stores_controller.rb | 149 | class StoresController < ApplicationController
def index
@ab_string = ab_test(:hoge, 'Hello!', 'goodby!')
render 'stores/index'
end
end
| mit |
s4if/ppdb-mannganjuk | app/views/create.blade.php | 4921 | @section('content')
{{ Form::open() }}
<div class="row">
<div class="col-sm-6">
<fieldset>
<legend>Biodata Calon PDB</legend>
<div class="form-group">
{{ Form::label('no_pendaftaran', 'No. Pendaftaran', array('class' => 'control-label')) }}
{{ Form::text(null, $nomor, array('disabled', 'class' => 'form-control')) }}
{{ Form::hidden('no_pendaftaran', $nomor) }}
</div>
<div class="form-group {{ ! $errors->first('name') ?: 'has-error' }}">
{{ Form::label('name', 'Nama Lengkap', array('class' => 'control-label')) }}
{{ Form::text('name', Input::old('name'), array('autofocus', 'required', 'class' => 'form-control')) }}
@if( $errors->first('name') )
<span class="help-block text-danger">Harus diisi</span>
@endif
</div>
<div class="form-group {{ ! $errors->first('school_name') ?: 'has-error' }}">
{{ Form::label('school_name', 'Asal Sekolah', array('class' => 'control-label')) }}
{{ Form::text('school_name', Input::old('school_name'), array('required', 'class' => 'form-control')) }}
@if( $errors->first('school_name') )
<span class="help-block text-danger">Harus diisi</span>
@endif
</div>
<div class="form-group">
{{ Form::label('program_1', 'Program Pilihan I', array('class' => 'control-label')) }}
<div class="row">
<div class="col-sm-6">
{{ Form::select('program_1', $program, Input::old('program_1'), array('class' => 'form-control')) }}
</div>
<div class="col-sm-6">
{{ Form::select('group_1', array('AGAMA' => 'AGAMA', 'IPA' => 'IPA', 'IPS' => 'IPS'), Input::old('group_1'), array('disabled', 'id' => 'group_1', 'class' => 'form-control')) }}
</div>
</div>
</div>
<div class="form-group">
{{ Form::label('program_2', 'Program Pilihan II', array('class' => 'control-label')) }}
<div class="row">
<div class="col-sm-6">
{{ Form::select('program_2', $program, Input::old('program_2'), array('class' => 'form-control')) }}
</div>
<div class="col-sm-6">
{{ Form::select('group_2', array('AGAMA' => 'AGAMA', 'IPA' => 'IPA', 'IPS' => 'IPS'), Input::old('group_2'), array('disabled', 'id' => 'group_2', 'class' => 'form-control')) }}
</div>
</div>
</div>
</fieldset>
<fieldset>
<legend>Nilai Rata-rata Raport</legend>
<div class="form-group">
<div class="row">
<div class="col-sm-2">
{{ Form::text('raport_pai', Input::old('raport_pai'), array('placeholder' => 'PAI', 'class' => 'form-control')) }}
</div>
<div class="col-sm-2">
{{ Form::text('raport_bin', Input::old('raport_bin'), array('placeholder' => 'BIN', 'class' => 'form-control')) }}
</div>
<div class="col-sm-2">
{{ Form::text('raport_big', Input::old('raport_big'), array('placeholder' => 'BIG', 'class' => 'form-control')) }}
</div>
<div class="col-sm-2">
{{ Form::text('raport_mtk', Input::old('raport_mtk'), array('placeholder' => 'MTK', 'class' => 'form-control')) }}
</div>
<div class="col-sm-2">
{{ Form::text('raport_ipa', Input::old('raport_ipa'), array('placeholder' => 'IPA', 'class' => 'form-control')) }}
</div>
<div class="col-sm-2">
{{ Form::text('raport_ips', Input::old('raport_ips'), array('placeholder' => 'IPS', 'class' => 'form-control')) }}
</div>
</div>
</div>
</fieldset>
<fieldset>
<legend>Nilai UN</legend>
<div class="form-group">
<div class="row">
<div class="col-sm-3">
{{ Form::text('un_bin', Input::old('un_bin'), array('placeholder' => 'BIN', 'class' => 'form-control')) }}
</div>
<div class="col-sm-3">
{{ Form::text('un_big', Input::old('un_big'), array('placeholder' => 'BIG', 'class' => 'form-control')) }}
</div>
<div class="col-sm-3">
{{ Form::text('un_mtk', Input::old('un_mtk'), array('placeholder' => 'MTK', 'class' => 'form-control')) }}
</div>
<div class="col-sm-3">
{{ Form::text('un_ipa', Input::old('un_ipa'), array('placeholder' => 'IPA', 'class' => 'form-control')) }}
</div>
</div>
</div>
</fieldset>
{{ Form::submit('Tambahkan', array('class' => 'btn btn-primary btn-lg pull-right')) }}
</div>
<div class="col-sm-6">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Catatan</h3>
</div>
<ul class="list-group">
<li class="list-group-item">Program pilihan <strong>selain Reguler</strong> secara <strong>otomatis akan dikelompokkan sesuai kelompok peminatannya</strong>.</li>
<li class="list-group-item">Nilai raport menggunakan skala 1-100 dan <strong>desimal dipisah dengan tanda titik</strong>. Jika nilai Calon PDB adalah <strong>8.89</strong>, maka diisi dengan <strong>88.9</strong></li>
<li class="list-group-item">Anda dapat mengosongkan nilai raport dan nilai UN, dan mengisinya nanti.</li>
</ul>
</div>
</div>
</div>
{{ Form::close() }}
@stop | mit |
gkostadinov/webdocs | public/index.php | 4366 | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Webdocs - anonymous collaborative document editing</title>
<meta name="description" content="Anonymous collaborative document editing">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="http://fonts.googleapis.com/css?family=Raleway:400,300,600" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="css/vendor/normalize.css">
<link rel="stylesheet" href="css/vendor/quill.css">
<link rel="stylesheet" href="css/base.css">
<link rel="stylesheet" href="css/app.css">
</head>
<body>
<header>
<div class="container">
<div class="row">
<h2 class="title">Webdocs <sup>beta</sup></h2>
<h5 class="subtitle">
anonymous collaborative document editing
</h5>
</div>
</div>
</header>
<section class="content">
<div class="container">
<section class="box">
<div class="row box-title">
<div class="box-title-text">
<h4 id="title">Untitled</h4>
</div>
<div class="box-title-button">
<a href="javascript:void(0)" class="button" id="share_btn" title="Share for viewing or editing" style="display: none">Share</a>
</div>
</div>
<div class="row box-content small-padding round-bottom">
<div id="toolbar"></div>
<div id="editor"></div>
</div>
</section>
</div>
</section>
<div class="modal" id="modal" data-trigger="#share_btn" data-close="#close_btn">
<section class="box">
<div class="row box-title">
<div class="box-title-text">
<h5>Share the document</h5>
</div>
<div class="box-title-button">
<a href="javascript:void(0)" class="button" id="close_btn" title="Close the modal">Close</a>
</div>
</div>
<div class="row box-content small-padding round-bottom">
<div class="row">
<div class="row">
<h5>Title:</h5>
</div>
<div class="row">
<input id="title_input" class="twelve columns" type="text" value="">
</div>
<div class="row" id="share_confirm" style="margin-top: 20px;">
<a href="javascript:void(0)" class="button" title="Share">Share</a>
</div>
</div>
<div id="next_step" style="display: none">
<div class="row">
<div class="row">
<h5>Link for edit:</h5>
</div>
<div class="row">
<input id="edit_link" class="twelve columns" type="text" onClick="this.setSelectionRange(0, this.value.length)" value="">
</div>
</div>
<div class="row">
<div class="row">
<h5>Link for view:</h5>
</div>
<div class="row">
<input id="view_link" class="twelve columns" type="text" onClick="this.setSelectionRange(0, this.value.length)" value="">
</div>
</div>
</div>
</div>
</section>
</div>
<script src="js/vendor/quill.js"></script>
<script src="js/base.js?v=2"></script>
<script src="js/config.js?v=4"></script>
<script src="js/socket.js?v=2"></script>
<script src="js/modal.js?v=1"></script>
<script src="js/app.js?v=4"></script>
</body>
</html>
| mit |
yogeshsaroya/new-cdnjs | ajax/libs/kendo-ui-core/2014.1.416/js/cultures/kendo.culture.tzm.min.js | 129 | version https://git-lfs.github.com/spec/v1
oid sha256:37308d5846d3a4ee1911bee43cd9a1ffd9a064c9264a053cc3c41b0097f18617
size 1769
| mit |
maur8ino/karma-json2js-preprocessor | lib/json2js.js | 641 | var util = require('util');
var TEMPLATE = '' +
'window.__json__ = window.__json__ || {};\n' +
'window.__json__[\'%s\'] = function() { return %s; };';
var createJson2JsPreprocessor = function(logger, basePath) {
var log = logger.create('preprocessor.json2js');
return function(content, file, done) {
log.debug('Processing "%s".', file.originalPath);
var jsonPath = file.originalPath.replace(basePath + '/', '');
file.path = file.path + '.js';
done(util.format(TEMPLATE, jsonPath, content));
};
};
createJson2JsPreprocessor.$inject = ['logger', 'config.basePath'];
module.exports = createJson2JsPreprocessor;
| mit |
claudiapattison/claudiapattison.github.io | assets/js/global.js | 863 | var cp = cp || {};
cp.header = {
navigation: function() {
var $headerLinks = $('#main-navigation a');
$headerLinks.on('click', function () {
event.preventDefault();
$(this).attr('href','#'+$(this).attr('href').split('#')[1]);
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
});
},
};
cp.animations = {
fade: function() {
$('.capabilities-list li, .about-me-image, .about-me-text, .work-item').addClass("hidden").viewportChecker({
classToAdd: 'visible animated fadeInUp',
offset: 150
});
},
};
$(function() {
var $body = $('body');
/*if ($body.hasClass('home'))
{
cp.header.navigation();
}
//cp.header.banner();*/
cp.animations.fade();
});
| mit |
godds/soundipic | src/app/pick/pick.spec.js | 184 | describe( "pick section", function() {
beforeEach(module("soundipic.pick"));
it("should set up the title", inject(function() {
expect(true).toBeTruthy();
}));
});
| mit |
crckyl/pixplus | src/lib/configui.js | 19866 | _.configui = {
editor: {
open: function(input, type, lang, opts) {
(new this[type](input, lang, opts)).open(_.configui.dom.root, {members: [input], top_left_of: input});
},
register: function(input, type, lang, opts) {
var that = this;
_.listen(input, 'focus', function(ev) {
that.open.call(that, input, type, lang, opts);
});
}
},
tabs: {
__default: function(root, section, lang) {
var tbody = _.e('tbody', null, _.e('table', null, root)), subsection;
section.items.forEach(function(item) {
if (!_.conf.general.debug && item.hide) {
return;
}
if (item.subsection && item.subsection !== subsection) {
_.e('div', {text: lang.pref[section.name + '_' + item.subsection] || item.subsection},
_.e('td', {colspan: 3}, _.e('tr', {cls: 'pp-config-subsection-title'}, tbody)));
subsection = item.subsection;
}
var type = typeof(item.value),
info = (lang.conf[section.name] || {})[item.key] || item.label || item.key,
row = _.e('tr', null, tbody),
desc = _.e('td', null, row),
input_id = 'pp-config-' + section.name + '-' + item.key.replace(/_/g, '-'),
control, control_propname;
if (type === 'boolean') {
var label = _.e('label', null, desc);
control = _.e('input', {type: 'checkbox', id: input_id}, label);
control_propname = 'checked';
label.appendChild(d.createTextNode(info.desc || info));
desc.setAttribute('colspan', '2');
} else {
var value = _.e('td', null, row);
desc.textContent = info.desc || info;
if (info.hint) {
control = _.e('select', {id: input_id}, value);
info.hint.forEach(function(hint, idx) {
var ovalue = hint.value || idx;
var opt = _.e('option', {text: hint.desc || hint, value: ovalue}, control);
});
} else {
control = _.e('input', {id: input_id}, value);
}
control_propname = 'value';
}
control[control_propname] = _.conf[section.name][item.key];
_.listen(control, ['change', 'input'], function() {
var value = control[control_propname];
if (typeof(item.value) === 'number') {
value = g.parseFloat(value);
}
_.conf[section.name][item.key] = value;
});
_.onclick(
_.e('button', {text: lang.pref['default'], id: input_id + '-default'}, row.insertCell(-1)),
function() {
_.conf[section.name][item.key] = item.value;
control[control_propname] = item.value;
}
);
var editor = item.editor || section.editor;
if (editor) {
_.configui.editor.register(control, editor, lang, item.editor_opts);
}
});
},
bookmark: function(root, section, lang) {
_.e('div', {text: lang.conf.bookmark.tag_order, css: 'white-space:pre'}, root);
var tag_order_textarea = _.e('textarea', null, root);
tag_order_textarea.value = _.conf.bookmark.tag_order.map(function(a) {
return a.map(function(tag) {
return tag || '*';
}).join('\n');
}).join('\n-\n');
_.listen(tag_order_textarea, 'input', function() {
var tag_order = [[]];
tag_order_textarea.value.split(/[\r\n]+/).forEach(function(line) {
if (!line) {
return;
}
if (line === '-') {
tag_order.push([]);
} else {
tag_order[tag_order.length - 1].push(line === '*' ? null : line);
}
});
_.conf.bookmark.tag_order = tag_order;
});
_.e('div', {text: lang.conf.bookmark.tag_aliases}, root);
var tag_alias_table = _.e('table', {id: 'pp-config-bookmark-tag-aliases'}, root);
_.onclick(_.e('button', {text: lang.pref.add}, root), function() {
add_row();
});
function save() {
var aliases = { };
g.Array.prototype.forEach.call(tag_alias_table.rows, function(row) {
var inputs = _.qa('input', row);
if (inputs.length === 2 && inputs[0].value) {
aliases[inputs[0].value] = inputs[1].value.split(/\s+/);
}
});
_.conf.bookmark.tag_aliases = aliases;
}
function add_row(tag, list) {
var row = tag_alias_table.insertRow(-1);
_.onclick(_.e('button', {text: '\u2715'}, row.insertCell(-1)), function() {
row.parentNode.removeChild(row);
save();
});
var i_tag = _.e('input', {value: tag || ''}, row.insertCell(-1)),
i_atags = _.e('input', {value: list ? list.join(' ') : ''}, row.insertCell(-1));
_.listen(i_tag, 'input', save);
_.listen(i_atags, 'input', save);
}
var aliases = _.conf.bookmark.tag_aliases;
for(var key in aliases) {
add_row(key, aliases[key]);
}
},
importexport: function(root, section, lang) {
var toolbar = _.e('div', {id: 'pp-config-importexport-toolbar'}, root);
var textarea = _.e('textarea', null, root);
_.onclick(_.e('button', {text: lang.pref['export']}, toolbar), function() {
textarea.value = JSON.stringify(_.conf.__export(''), null, 2);
});
_.onclick(_.e('button', {text: lang.pref['import']}, toolbar), function() {
var data;
try {
data = JSON.parse(textarea.value);
} catch(ex) {
g.alert(ex);
return;
}
_.conf.__import(data);
});
},
about: function(root, section, lang) {
var urls = [
'http://ccl4.info/pixplus/',
'https://github.com/crckyl/pixplus',
'http://ccl4.info/cgit/pixplus.git/',
'http://crckyl.hatenablog.com/',
'http://twitter.com/crckyl'
];
_.e('p', {text: 'pixplus ' + _.version() + ' - ' + _.release_date()}, root);
var info = _.e('dl', null, root);
[
[lang.pref.about_web, function(dd) {
var ul = _.e('ul', null, dd);
urls.forEach(function(url) {
_.e('a', {href: url, text: url}, _.e('li', null, ul));
});
}],
[lang.pref.about_email,
_.e('a', {text: 'crckyl@gmail.com', href: 'mailto:crckyl@gmail.com'})],
[lang.pref.about_license, 'The MIT License']
].forEach(function(p) {
var label = p[0], content = p[1];
_.e('dt', {text: label}, info);
var dd = _.e('dd', null, info);
if (content.nodeName) {
dd.appendChild(content);
} else if (content.call) {
content(dd);
} else {
dd.textContent = content;
}
});
var changelog = _.e('dl', null, root);
_.changelog.forEach(function(release) {
var dt = _.e('dt', {text: release.version + ' - ' + release.date}, changelog);
if (release.releasenote) {
dt.textContent += ' ';
_.e('a', {href: release.releasenote, text: lang.pref.releasenote}, dt);
}
var ul = _.e('ul', null, _.e('dd', null, changelog));
var changes;
if (release.changes_i18n) {
changes = release.changes_i18n[lang.__name__] || release.changes_i18n.en;
} else {
changes = release.changes;
}
changes.forEach(function(change) {
_.e('li', {text: change}, ul);
});
});
},
debug: function(root, sections, lang) {
var that = this;
var make_section = function(name, label) {
var wrapper = _.e('div', {id: 'pp-config-debug-' + name, cls: 'pp-config-debug-section'}, root),
title = _.e('div', {cls: 'pp-config-subsection-title'}, wrapper);
_.e('div', {text: label}, title);
return _.e('div', {cls: 'pp-config-debug-section-content'}, wrapper);
};
sections.forEach(function(section) {
that.__default(make_section(section.name, section.name), section, lang);
});
[
{
name: 'lang',
label: 'Switch UI language',
func: function(content) {
['en', 'ja'].forEach(function(name) {
_.onclick(_.e('button', {text: name}, content), function() {
_.configui.lng = _.i18n[name];
_.configui.dom.root.parentNode.removeChild(_.configui.dom.root);
_.configui.dom = { };
_.configui.show();
});
});
}
},
{
name: 'key',
label: 'Key',
func: function(content) {
var input_line = _.e('div', null, content);
var input = _.e('input', null, input_line);
var cancel_l = _.e('label', null, input_line);
var cancel = _.e('input', {type: 'checkbox', css: 'margin-left:4px;', checked: true}, cancel_l);
var console_l = _.e('label', null, input_line);
var console = _.e('input', {type: 'checkbox', css: 'margin-left:4px;', checked: true}, console_l);
var logger = _.e('table', {css: 'margin-top:4px;border:1px solid #aaa'}, content);
cancel_l.appendChild(d.createTextNode('Cancel'));
console_l.appendChild(d.createTextNode('Console'));
var log_attrs = [
'type',
'keyCode',
'charCode',
'key',
'char',
'keyIdentifier',
'which',
'eventPhase',
'detail',
'timeStamp'
];
function clear() {
input.value = '';
logger.innerHTML = '';
var row = logger.insertRow(0);
row.insertCell(-1).textContent = 'Key';
log_attrs.forEach(function(attr) {
row.insertCell(-1).textContent = attr;
});
}
function log(ev) {
var row = logger.insertRow(1);
var key = _.key.parse_event(ev) || 'None';
row.insertCell(-1).textContent = key;
log_attrs.forEach(function(attr) {
row.insertCell(-1).textContent = ev[attr];
});
if (cancel.checked && key) {
ev.preventDefault();
}
if (console.checked) {
_.debug(ev);
}
}
clear();
_.onclick(_.e('button', {text: 'Clear', css: 'margin-left:4px;'}, input_line), clear);
input.addEventListener('keydown', log, false);
input.addEventListener('keypress', log, false);
}
}
].forEach(function(section) {
section.func(make_section(section.name, section.label));
});
}
},
dom: { },
lng: null,
container: null,
toggle_btn: null,
init: function(container, toggle_btn) {
if (!container) {
return;
}
this.lng = _.lng;
this.container = container;
this.toggle_btn = toggle_btn;
},
create_tab: function(name, create_args) {
var that = this, dom = this.dom, label, content;
label = _.e('label', {text: this.lng.pref[name] || name, cls: 'pp-config-tab',
id: 'pp-config-tab-' + name}, dom.tabbar);
content = _.e('div', {id: 'pp-config-' + name + '-content', cls: 'pp-config-content'});
(this.tabs[name] || this.tabs.__default).call(this.tabs, content, create_args, this.lng);
dom.content.appendChild(content);
dom[name] = {label: label, content: content};
_.onclick(label, function() {
that.activate_tab(dom[name]);
return true;
});
},
create: function() {
var that = this, dom = this.dom;
if (dom.created) {
return;
}
dom.root = _.e('div', {id: 'pp-config', cls: 'pp-toplevel'}, this.container);
dom.tabbar = _.e('div', {id: 'pp-config-tabbar'});
dom.content = _.e('div', {id: 'pp-config-content-wrapper'});
var hidden_sections = [];
_.conf.__schema.forEach(function(section) {
if (section.hide) {
hidden_sections.push(section);
return;
}
that.create_tab(section.name, section);
});
['importexport', 'about'].forEach(this.create_tab.bind(this));
if (_.conf.general.debug) {
that.create_tab('debug', hidden_sections);
}
dom.root.appendChild(dom.tabbar);
dom.root.appendChild(dom.content);
dom.created = true;
this.activate_tab(dom.general);
},
activate_tab: function(tab) {
var lasttab = this.dom.lasttab;
if (lasttab) {
lasttab.label.classList.remove('pp-active');
lasttab.content.classList.remove('pp-active');
}
tab.label.classList.add('pp-active');
tab.content.classList.add('pp-active');
this.dom.lasttab = tab;
},
is_active: function() {
return !!this.dom.root && this.dom.root.classList.contains('pp-show');
},
show: function(center) {
this.create();
this.dom.root.classList.add('pp-show');
if (this.toggle_btn) {
this.toggle_btn.classList.add('pp-active');
var el = this.dom.content, de = d.documentElement, h;
h = de.clientHeight - (center ? 0 : el.getBoundingClientRect().top);
el.style.height = Math.floor(h * 0.7) + 'px';
}
},
hide: function() {
this.dom.root.classList.remove('pp-show');
if (this.toggle_btn) {
this.toggle_btn.classList.remove('pp-active');
}
},
toggle: function() {
if (this.is_active()) {
this.hide();
} else {
this.show();
}
}
};
(function() {
var Base = _.class.create(_.Dialog.prototype, {
init: function(src_input, lang, type) {
Base.super.init.call(this, {cls: 'pp-config-editor pp-config-' + type + '-editor'});
this.src_input = src_input;
this.lang = lang;
this.setup();
this.update(src_input.value);
},
open: function() {
this.src_input.classList.add('pp-active');
Base.super.open.apply(this, arguments);
},
close: function() {
this.src_input.classList.remove('pp-active');
Base.super.close.apply(this, arguments);
},
update: function(value) {
},
change: function(value) {
this.src_input.value = value;
var ev = d.createEvent('Event');
ev.initEvent('input', true, true);
this.src_input.dispatchEvent(ev);
}
});
var Key = _.class.create(Base.prototype, {
init: function(src_input, lang) {
Key.super.init.call(this, src_input, lang, 'key');
},
setup: function() {
var that = this, dom = this.dom;
dom.list = _.e('ul', null, dom.content);
dom.add_input = _.e('input', {'placeholder': 'Grab key', cls: 'pp-config-key-editor-grab'}, dom.content);
_.key.listen(dom.add_input, function(key) {
dom.add_input.value = key;
return true;
});
this.add_action('add', {callback: function() {
that.add(dom.add_input.value);
dom.add_input.value = '';
that.apply();
}});
this.add_action('close');
},
update: function(value) {
_.clear(this.dom.list);
value.split(',').forEach(this.add.bind(this));
},
add: function(key) {
var that = this;
var li = _.e('li', null, this.dom.list);
_.onclick(_.e('button', {text: '\u2715'}, li), function() {
li.parentNode.removeChild(li);
that.apply();
});
_.e('label', {text: key}, li);
},
apply: function() {
var keys = [];
_.qa('li label', this.dom.list).forEach(function(key) {
keys.push(key.textContent);
});
this.change(keys.join(','));
}
});
var Regexp = _.class.create(Base.prototype, {
paths: [
'/',
'/new_illust.php',
'/bookmark_new_illust.php',
'/mypixiv_new_illust.php',
'/ranking.php?mode=daily',
'/ranking_area.php',
'/stacc/p/activity',
'/stacc/p/activity?mode=unify',
'/user_event.php',
'/bookmark.php',
'/bookmark.php?rest=hide',
'/bookmark.php?id=11',
'/member.php?id=11',
'/member_illust.php',
'/member_illust.php?id=11',
'/member_illust.php?mode=medium&illust_id=11437736',
'/response.php?illust_id=11437736',
'/tags.php?tag=pixiv',
'/search.php?s_mode=s_tag&word=pixiv',
'/cate_r18.php',
'/new_illust_r18.php',
'/user_event.php?type=r18',
'/questionnaire_illust.php',
'/search_user.php'
],
init: function(src_input, lang) {
Regexp.super.init.call(this, src_input, lang, 'regexp');
},
setup: function() {
var that = this, dom = this.dom;
dom.textarea = _.e('textarea', {cls: 'pp-config-regexp-editor-textarea'}, dom.content);
_.listen(dom.textarea, 'input', function() {
that.change(dom.textarea.value);
that.check(dom.textarea.value);
});
dom.list = _.e('ul', null, dom.content);
dom.status = _.e('li', {cls: 'pp-config-regexp-editor-status'}, dom.list);
dom.pagecheck_table = _.e('table', null, dom.content);
this.paths.forEach(function(path) {
var row = dom.pagecheck_table.insertRow(-1);
_.e('a', {href: path, text: path, target: '_blank'}, row.insertCell(-1));
var cell = row.insertCell(-1);
cell.className = 'pp-config-regexp-editor-status';
cell.setAttribute('data-path', path);
});
},
update: function(value) {
this.dom.textarea.value = value;
this.check(value);
},
check: function(value) {
var valid = true;
try {
new g.RegExp(value);
} catch(ex) {
valid = false;
}
var dom = this.dom;
dom.status.classList[valid ? 'add' : 'remove']('pp-yes');
dom.status.classList[valid ? 'remove' : 'add']('pp-no');
dom.status.textContent = valid ? this.lang.pref.regex_valid : this.lang.pref.regex_invalid;
_.qa('*[data-path]', dom.pagecheck_table).forEach(function(status) {
var yes = valid && (new g.RegExp(value)).test('https://www.pixiv.net' + status.dataset.path);
status.classList[yes ? 'add' : 'remove']('pp-yes');
status.classList[yes ? 'remove' : 'add']('pp-no');
status.textContent = yes ? '\u25cb' : '\u2715';
});
}
});
var Checklist = _.class.create(Base.prototype, {
init: function(src_input, lang, opts) {
this.valid_values = opts.valid_values;
Checklist.super.init.call(this, src_input, lang, 'checklist');
},
setup: function() {
var that = this, dom = this.dom;
this.checkboxes = [];
dom.list = _.e('ul', null, dom.content);
this.valid_values.forEach(function(url) {
var li = _.e('li', null, dom.list),
label = _.e('label', null, li),
check = _.e('input', {type: 'checkbox'}, label),
text = _.e('span', {text: url}, label);
_.listen(check, 'change', that.apply.bind(that));
that.checkboxes.push({
url: url,
checkbox: check
});
});
},
update: function(value) {
var urls = value.split(',');
this.checkboxes.forEach(function(item) {
item.checkbox.checked = urls.indexOf(item.url) >= 0;
});
},
apply: function() {
var active_values = this.checkboxes.filter(function(item) {
return item.checkbox.checked;
}).map(function(item) {
return item.url;
});
this.change(this.valid_values.filter(function(url) {
return active_values.indexOf(url) >= 0;
}).join(','));
}
});
_.configui.editor.Base = Base;
_.configui.editor.Key = Key;
_.configui.editor.Regexp = Regexp;
_.configui.editor.Checklist = Checklist;
})();
| mit |
theycallmecoach/cagey-engine | cagey-engine/include/cagey/math/MathFwd.hh | 5494 | ////////////////////////////////////////////////////////////////////////////////
//
// cagey-engine - Toy 3D Engine
// Copyright (c) 2014 Kyle Girard <theycallmecoach@gmail.com>
//
// The MIT License (MIT)
//
// 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.
//
////////////////////////////////////////////////////////////////////////////////
/**
* @file
* Forward declarations for the cagey::math namespace
*/
#ifndef CAGEY_MATH_MATH_HH_
#define CAGEY_MATH_MATH_HH_
#include <cstdint>
#include <cstddef>
/**
* Namespace to contain all cagey
*/
namespace cagey {
/**
* Namespace for all Math related classes
*/
namespace math {
template<typename> class Degree;
template<typename> class Radian;
///Shorthand for float Degree template
template<typename T> using Degf = Degree<float>;
///Shorthand for double Degree template
template<typename T> using Degd = Degree<double>;
///Shorthand for float Radian template
template<typename T> using Radf = Radian<float>;
///Shorthand for double Radian template
template<typename T> using Radd = Radian<double>;
template<typename, std::size_t> class Point;
///Shorthand for the two element Point
template<typename T> using Point2 = Point<T,2>;
///Shorthand for the three element Point
template<typename T> using Point3 = Point<T,3>;
///Shorthand for the four element Point
template<typename T> using Point4 = Point<T,4>;
///Shorthand for the two element unsigned Point
using Point2u = Point<std::uint32_t, 2>;
///Shorthand for the two element int Point
using Point2i = Point<std::int32_t, 2>;
///Shorthand for the two element float Point
using Point2f = Point<float, 2>;
///Shorthand for the two element double Point
using Point2d = Point<double, 2>;
///Shorthand for the three element unsigned Point
using Point3u = Point<std::uint32_t, 3>;
///Shorthand for the three element int Point
using Point3i = Point<std::int32_t, 3>;
///Shorthand for the three element float Point
using Point3f = Point<float, 3>;
///Shorthand for the three element double Point
using Point3d = Point<double, 3>;
template<typename, std::size_t> class Vector;
///Shorthand for the two element Vector
template<typename T> using Vec2 = Vector<T,2>;
///Shorthand for the three element Vector
template<typename T> using Vec3 = Vector<T,3>;
///Shorthand for the four element Vector
template<typename T> using Vec4 = Vector<T,4>;
///Shorthand for the two element unsigned Vector
using Vec2u = Vector<std::uint32_t, 2>;
///Shorthand for the two element int Vector
using Vec2i = Vector<std::int32_t, 2>;
///Shorthand for the two element float Vector
using Vec2f = Vector<float, 2>;
///Shorthand for the two element double Vector
using Vec2d = Vector<double, 2>;
///Shorthand for the three element unsigned Vector
using Vec3u = Vector<std::uint32_t, 3>;
///Shorthand for the three element int Vector
using Vec3i = Vector<std::int32_t, 3>;
///Shorthand for the three element float Vector
using Vec3f = Vector<float, 3>;
///Shorthand for the three element double Vector
using Vec3d = Vector<double, 3>;
///Shorthand for the four element unsigned Vector
using Vec4u = Vector<std::uint32_t, 4>;
///Shorthand for the four element int Vector
using Vec4i = Vector<std::int32_t, 4>;
///Shorthand for the four element float Vector
using Vec4f = Vector<float, 4>;
///Shorthand for the four element double Vector
using Vec4d = Vector<double, 4>;
template<typename, std::size_t, std::size_t> class Matrix;
///Shorthand for 2x2 square matrix
template<typename T> using Mat2 = Matrix<T, 2, 2>;
///Shorthand for 3x3 square matrix
template<typename T> using Mat3 = Matrix<T, 3, 3>;
///Shorthand for 4x4 square matrix
template<typename T> using Mat4 = Matrix<T, 4, 4>;
///Shorthand for 2x2 square int matrix
using Mat2i = Matrix<std::int32_t, 2, 2>;
///Shorthand for 2x2 square int matrix
using Mat3i = Matrix<std::int32_t, 3, 3>;
///Shorthand for 2x2 square int matrix
using Mat4i = Matrix<std::int32_t, 4, 4>;
///Shorthand for 2x2 square float matrix
using Mat2f = Matrix<float, 2, 2>;
///Shorthand for 3x3 square float matrix
using Mat3f = Matrix<float, 3, 3>;
///Shorthand for 4x4 square float matrix
using Mat4f = Matrix<float, 4, 4>;
///Shorthand for 2x2 square double matrix
using Mat2d = Matrix<double, 2, 2>;
///Shorthand for 3x3 square double matrix
using Mat3d = Matrix<double, 3, 3>;
///Shorthand for 4x4 square double matrix
using Mat4d = Matrix<double, 4, 4>;
} // namespace math
} // namespace cagey
#endif /* CAGEY_MATH_MATH_HH_ */
| mit |
mathiasbynens/unicode-data | 6.2.0/blocks/Tibetan-symbols.js | 2878 | // All symbols in the Tibetan block as per Unicode v6.2.0:
[
'\u0F00',
'\u0F01',
'\u0F02',
'\u0F03',
'\u0F04',
'\u0F05',
'\u0F06',
'\u0F07',
'\u0F08',
'\u0F09',
'\u0F0A',
'\u0F0B',
'\u0F0C',
'\u0F0D',
'\u0F0E',
'\u0F0F',
'\u0F10',
'\u0F11',
'\u0F12',
'\u0F13',
'\u0F14',
'\u0F15',
'\u0F16',
'\u0F17',
'\u0F18',
'\u0F19',
'\u0F1A',
'\u0F1B',
'\u0F1C',
'\u0F1D',
'\u0F1E',
'\u0F1F',
'\u0F20',
'\u0F21',
'\u0F22',
'\u0F23',
'\u0F24',
'\u0F25',
'\u0F26',
'\u0F27',
'\u0F28',
'\u0F29',
'\u0F2A',
'\u0F2B',
'\u0F2C',
'\u0F2D',
'\u0F2E',
'\u0F2F',
'\u0F30',
'\u0F31',
'\u0F32',
'\u0F33',
'\u0F34',
'\u0F35',
'\u0F36',
'\u0F37',
'\u0F38',
'\u0F39',
'\u0F3A',
'\u0F3B',
'\u0F3C',
'\u0F3D',
'\u0F3E',
'\u0F3F',
'\u0F40',
'\u0F41',
'\u0F42',
'\u0F43',
'\u0F44',
'\u0F45',
'\u0F46',
'\u0F47',
'\u0F48',
'\u0F49',
'\u0F4A',
'\u0F4B',
'\u0F4C',
'\u0F4D',
'\u0F4E',
'\u0F4F',
'\u0F50',
'\u0F51',
'\u0F52',
'\u0F53',
'\u0F54',
'\u0F55',
'\u0F56',
'\u0F57',
'\u0F58',
'\u0F59',
'\u0F5A',
'\u0F5B',
'\u0F5C',
'\u0F5D',
'\u0F5E',
'\u0F5F',
'\u0F60',
'\u0F61',
'\u0F62',
'\u0F63',
'\u0F64',
'\u0F65',
'\u0F66',
'\u0F67',
'\u0F68',
'\u0F69',
'\u0F6A',
'\u0F6B',
'\u0F6C',
'\u0F6D',
'\u0F6E',
'\u0F6F',
'\u0F70',
'\u0F71',
'\u0F72',
'\u0F73',
'\u0F74',
'\u0F75',
'\u0F76',
'\u0F77',
'\u0F78',
'\u0F79',
'\u0F7A',
'\u0F7B',
'\u0F7C',
'\u0F7D',
'\u0F7E',
'\u0F7F',
'\u0F80',
'\u0F81',
'\u0F82',
'\u0F83',
'\u0F84',
'\u0F85',
'\u0F86',
'\u0F87',
'\u0F88',
'\u0F89',
'\u0F8A',
'\u0F8B',
'\u0F8C',
'\u0F8D',
'\u0F8E',
'\u0F8F',
'\u0F90',
'\u0F91',
'\u0F92',
'\u0F93',
'\u0F94',
'\u0F95',
'\u0F96',
'\u0F97',
'\u0F98',
'\u0F99',
'\u0F9A',
'\u0F9B',
'\u0F9C',
'\u0F9D',
'\u0F9E',
'\u0F9F',
'\u0FA0',
'\u0FA1',
'\u0FA2',
'\u0FA3',
'\u0FA4',
'\u0FA5',
'\u0FA6',
'\u0FA7',
'\u0FA8',
'\u0FA9',
'\u0FAA',
'\u0FAB',
'\u0FAC',
'\u0FAD',
'\u0FAE',
'\u0FAF',
'\u0FB0',
'\u0FB1',
'\u0FB2',
'\u0FB3',
'\u0FB4',
'\u0FB5',
'\u0FB6',
'\u0FB7',
'\u0FB8',
'\u0FB9',
'\u0FBA',
'\u0FBB',
'\u0FBC',
'\u0FBD',
'\u0FBE',
'\u0FBF',
'\u0FC0',
'\u0FC1',
'\u0FC2',
'\u0FC3',
'\u0FC4',
'\u0FC5',
'\u0FC6',
'\u0FC7',
'\u0FC8',
'\u0FC9',
'\u0FCA',
'\u0FCB',
'\u0FCC',
'\u0FCD',
'\u0FCE',
'\u0FCF',
'\u0FD0',
'\u0FD1',
'\u0FD2',
'\u0FD3',
'\u0FD4',
'\u0FD5',
'\u0FD6',
'\u0FD7',
'\u0FD8',
'\u0FD9',
'\u0FDA',
'\u0FDB',
'\u0FDC',
'\u0FDD',
'\u0FDE',
'\u0FDF',
'\u0FE0',
'\u0FE1',
'\u0FE2',
'\u0FE3',
'\u0FE4',
'\u0FE5',
'\u0FE6',
'\u0FE7',
'\u0FE8',
'\u0FE9',
'\u0FEA',
'\u0FEB',
'\u0FEC',
'\u0FED',
'\u0FEE',
'\u0FEF',
'\u0FF0',
'\u0FF1',
'\u0FF2',
'\u0FF3',
'\u0FF4',
'\u0FF5',
'\u0FF6',
'\u0FF7',
'\u0FF8',
'\u0FF9',
'\u0FFA',
'\u0FFB',
'\u0FFC',
'\u0FFD',
'\u0FFE',
'\u0FFF'
]; | mit |
ArthurSecretProject/hera | src/app/utils/auth.guard.ts | 514 | import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router) { }
canActivate() {
if (localStorage.getItem('currentUser') && localStorage.getItem('userToken')) {
// logged in so return true
return true;
}
// not logged in so redirect to login page
this.router.navigate(['/home']);
return false;
}
}
| mit |
peteratseneca/dps907fall2013 | Week_05/oct01securitybasic/oct01securitybasic/App_Start/BundleConfig.cs | 2139 | using System.Web;
using System.Web.Optimization;
namespace oct01securitybasic
{
public class BundleConfig
{
// For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
"~/Scripts/jquery-ui-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));
bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
"~/Content/themes/base/jquery.ui.core.css",
"~/Content/themes/base/jquery.ui.resizable.css",
"~/Content/themes/base/jquery.ui.selectable.css",
"~/Content/themes/base/jquery.ui.accordion.css",
"~/Content/themes/base/jquery.ui.autocomplete.css",
"~/Content/themes/base/jquery.ui.button.css",
"~/Content/themes/base/jquery.ui.dialog.css",
"~/Content/themes/base/jquery.ui.slider.css",
"~/Content/themes/base/jquery.ui.tabs.css",
"~/Content/themes/base/jquery.ui.datepicker.css",
"~/Content/themes/base/jquery.ui.progressbar.css",
"~/Content/themes/base/jquery.ui.theme.css"));
}
}
} | mit |
maneeshd/PyTutorial | Basics/TutorialCode/Tut_07.py | 300 | """""""""""""""""""""""""""""
" Created On: 12-Aug-2016 "
" Author: Maneesh D "
"""""""""""""""""""""""""""""
fw = open('sample.txt', 'w', encoding='UTF-8')
fw.write("Hello\tWorld\n")
fw.write('Scram')
fw.close()
fr = open('sample.txt', 'r', encoding='UTF-8')
print(fr.read())
fr.close()
| mit |
technicalpickles/vlad-extras | config/hoe.rb | 2483 | require 'vlad/extras/version'
AUTHOR = 'Josh Nichols' # can also be an array of Authors
EMAIL = "josh@technicalpickles.com"
DESCRIPTION = "Extra tasks for vlad"
GEM_NAME = 'vlad-extras' # what ppl will type to install your gem
RUBYFORGE_PROJECT = 'vlad-extras' # The unix name for your project
HOMEPATH = "http://#{RUBYFORGE_PROJECT}.rubyforge.org"
DOWNLOAD_PATH = "http://rubyforge.org/projects/#{RUBYFORGE_PROJECT}"
@config_file = "~/.rubyforge/user-config.yml"
@config = nil
RUBYFORGE_USERNAME = "unknown"
def rubyforge_username
unless @config
begin
@config = YAML.load(File.read(File.expand_path(@config_file)))
rescue
puts <<-EOS
ERROR: No rubyforge config file found: #{@config_file}
Run 'rubyforge setup' to prepare your env for access to Rubyforge
- See http://newgem.rubyforge.org/rubyforge.html for more details
EOS
exit
end
end
RUBYFORGE_USERNAME.replace @config["username"]
end
REV = nil
# UNCOMMENT IF REQUIRED:
# REV = `svn info`.each {|line| if line =~ /^Revision:/ then k,v = line.split(': '); break v.chomp; else next; end} rescue nil
VERS = Vlad::Extras::VERSION::STRING + (REV ? ".#{REV}" : "")
RDOC_OPTS = ['--quiet', '--title', 'vlad-extras documentation',
"--opname", "index.html",
"--line-numbers",
"--main", "README",
"--inline-source"]
class Hoe
def extra_deps
@extra_deps.reject! { |x| Array(x).first == 'hoe' }
@extra_deps
end
end
# Generate all the Rake tasks
# Run 'rake -T' to see list of generated tasks (from gem root directory)
hoe = Hoe.new(GEM_NAME, VERS) do |p|
p.developer(AUTHOR, EMAIL)
p.description = DESCRIPTION
p.summary = DESCRIPTION
p.url = HOMEPATH
p.rubyforge_name = RUBYFORGE_PROJECT if RUBYFORGE_PROJECT
p.test_globs = ["test/**/test_*.rb"]
p.clean_globs |= ['**/.*.sw?', '*.gem', '.config', '**/.DS_Store'] #An array of file patterns to delete on clean.
# == Optional
p.changes = p.paragraphs_of("History.txt", 0..1).join("\n\n")
p.extra_deps = ['vlad'] # An array of rubygem dependencies [name, version], e.g. [ ['active_support', '>= 1.3.1'] ]
#p.spec_extras = {} # A hash of extra values to set in the gemspec.
end
CHANGES = hoe.paragraphs_of('History.txt', 0..1).join("\\n\\n")
PATH = (RUBYFORGE_PROJECT == GEM_NAME) ? RUBYFORGE_PROJECT : "#{RUBYFORGE_PROJECT}/#{GEM_NAME}"
hoe.remote_rdoc_dir = File.join(PATH.gsub(/^#{RUBYFORGE_PROJECT}\/?/,''), 'rdoc')
hoe.rsync_args = '-av --delete --ignore-errors' | mit |
ScottHolden/azure-sdk-for-net | src/SDKs/StreamAnalytics/Management.StreamAnalytics/Generated/FunctionsOperations.cs | 87844 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.StreamAnalytics
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// FunctionsOperations operations.
/// </summary>
internal partial class FunctionsOperations : IServiceOperations<StreamAnalyticsManagementClient>, IFunctionsOperations
{
/// <summary>
/// Initializes a new instance of the FunctionsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal FunctionsOperations(StreamAnalyticsManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the StreamAnalyticsManagementClient
/// </summary>
public StreamAnalyticsManagementClient Client { get; private set; }
/// <summary>
/// Creates a function or replaces an already existing function under an
/// existing streaming job.
/// </summary>
/// <param name='function'>
/// The definition of the function that will be used to create a new function
/// or replace the existing one under the streaming job.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='jobName'>
/// The name of the streaming job.
/// </param>
/// <param name='functionName'>
/// The name of the function.
/// </param>
/// <param name='ifMatch'>
/// The ETag of the function. Omit this value to always overwrite the current
/// function. Specify the last-seen ETag value to prevent accidentally
/// overwritting concurrent changes.
/// </param>
/// <param name='ifNoneMatch'>
/// Set to '*' to allow a new function to be created, but to prevent updating
/// an existing function. Other values will result in a 412 Pre-condition
/// Failed response.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<Function,FunctionsCreateOrReplaceHeaders>> CreateOrReplaceWithHttpMessagesAsync(Function function, string resourceGroupName, string jobName, string functionName, string ifMatch = default(string), string ifNoneMatch = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (function == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "function");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (jobName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "jobName");
}
if (functionName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "functionName");
}
string apiVersion = "2016-03-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("function", function);
tracingParameters.Add("ifMatch", ifMatch);
tracingParameters.Add("ifNoneMatch", ifNoneMatch);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("jobName", jobName);
tracingParameters.Add("functionName", functionName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CreateOrReplace", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/streamingjobs/{jobName}/functions/{functionName}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{jobName}", System.Uri.EscapeDataString(jobName));
_url = _url.Replace("{functionName}", System.Uri.EscapeDataString(functionName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (ifMatch != null)
{
if (_httpRequest.Headers.Contains("If-Match"))
{
_httpRequest.Headers.Remove("If-Match");
}
_httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch);
}
if (ifNoneMatch != null)
{
if (_httpRequest.Headers.Contains("If-None-Match"))
{
_httpRequest.Headers.Remove("If-None-Match");
}
_httpRequest.Headers.TryAddWithoutValidation("If-None-Match", ifNoneMatch);
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(function != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(function, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Function,FunctionsCreateOrReplaceHeaders>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Function>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Function>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
try
{
_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<FunctionsCreateOrReplaceHeaders>(JsonSerializer.Create(Client.DeserializationSettings));
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Updates an existing function under an existing streaming job. This can be
/// used to partially update (ie. update one or two properties) a function
/// without affecting the rest the job or function definition.
/// </summary>
/// <param name='function'>
/// A function object. The properties specified here will overwrite the
/// corresponding properties in the existing function (ie. Those properties
/// will be updated). Any properties that are set to null here will mean that
/// the corresponding property in the existing function will remain the same
/// and not change as a result of this PATCH operation.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='jobName'>
/// The name of the streaming job.
/// </param>
/// <param name='functionName'>
/// The name of the function.
/// </param>
/// <param name='ifMatch'>
/// The ETag of the function. Omit this value to always overwrite the current
/// function. Specify the last-seen ETag value to prevent accidentally
/// overwritting concurrent changes.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<Function,FunctionsUpdateHeaders>> UpdateWithHttpMessagesAsync(Function function, string resourceGroupName, string jobName, string functionName, string ifMatch = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (function == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "function");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (jobName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "jobName");
}
if (functionName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "functionName");
}
string apiVersion = "2016-03-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("function", function);
tracingParameters.Add("ifMatch", ifMatch);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("jobName", jobName);
tracingParameters.Add("functionName", functionName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/streamingjobs/{jobName}/functions/{functionName}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{jobName}", System.Uri.EscapeDataString(jobName));
_url = _url.Replace("{functionName}", System.Uri.EscapeDataString(functionName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PATCH");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (ifMatch != null)
{
if (_httpRequest.Headers.Contains("If-Match"))
{
_httpRequest.Headers.Remove("If-Match");
}
_httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch);
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(function != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(function, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Function,FunctionsUpdateHeaders>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Function>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
try
{
_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<FunctionsUpdateHeaders>(JsonSerializer.Create(Client.DeserializationSettings));
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes a function from the streaming job.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='jobName'>
/// The name of the streaming job.
/// </param>
/// <param name='functionName'>
/// The name of the function.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string jobName, string functionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (jobName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "jobName");
}
if (functionName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "functionName");
}
string apiVersion = "2016-03-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("jobName", jobName);
tracingParameters.Add("functionName", functionName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/streamingjobs/{jobName}/functions/{functionName}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{jobName}", System.Uri.EscapeDataString(jobName));
_url = _url.Replace("{functionName}", System.Uri.EscapeDataString(functionName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets details about the specified function.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='jobName'>
/// The name of the streaming job.
/// </param>
/// <param name='functionName'>
/// The name of the function.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<Function,FunctionsGetHeaders>> GetWithHttpMessagesAsync(string resourceGroupName, string jobName, string functionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (jobName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "jobName");
}
if (functionName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "functionName");
}
string apiVersion = "2016-03-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("jobName", jobName);
tracingParameters.Add("functionName", functionName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/streamingjobs/{jobName}/functions/{functionName}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{jobName}", System.Uri.EscapeDataString(jobName));
_url = _url.Replace("{functionName}", System.Uri.EscapeDataString(functionName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Function,FunctionsGetHeaders>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Function>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
try
{
_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<FunctionsGetHeaders>(JsonSerializer.Create(Client.DeserializationSettings));
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Lists all of the functions under the specified streaming job.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='jobName'>
/// The name of the streaming job.
/// </param>
/// <param name='select'>
/// The $select OData query parameter. This is a comma-separated list of
/// structural properties to include in the response, or “*” to include all
/// properties. By default, all properties are returned except diagnostics.
/// Currently only accepts '*' as a valid value.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<Function>>> ListByStreamingJobWithHttpMessagesAsync(string resourceGroupName, string jobName, string select = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (jobName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "jobName");
}
string apiVersion = "2016-03-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("select", select);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("jobName", jobName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByStreamingJob", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/streamingjobs/{jobName}/functions").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{jobName}", System.Uri.EscapeDataString(jobName));
List<string> _queryParameters = new List<string>();
if (select != null)
{
_queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(select)));
}
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<Function>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Function>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Tests if the information provided for a function is valid. This can range
/// from testing the connection to the underlying web service behind the
/// function or making sure the function code provided is syntactically
/// correct.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='jobName'>
/// The name of the streaming job.
/// </param>
/// <param name='functionName'>
/// The name of the function.
/// </param>
/// <param name='function'>
/// If the function specified does not already exist, this parameter must
/// contain the full function definition intended to be tested. If the function
/// specified already exists, this parameter can be left null to test the
/// existing function as is or if specified, the properties specified will
/// overwrite the corresponding properties in the existing function (exactly
/// like a PATCH operation) and the resulting function will be tested.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<ResourceTestStatus>> TestWithHttpMessagesAsync(string resourceGroupName, string jobName, string functionName, Function function = default(Function), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse<ResourceTestStatus> _response = await BeginTestWithHttpMessagesAsync(resourceGroupName, jobName, functionName, function, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Retrieves the default definition of a function based on the parameters
/// specified.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='jobName'>
/// The name of the streaming job.
/// </param>
/// <param name='functionName'>
/// The name of the function.
/// </param>
/// <param name='functionRetrieveDefaultDefinitionParameters'>
/// Parameters used to specify the type of function to retrieve the default
/// definition for.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<Function>> RetrieveDefaultDefinitionWithHttpMessagesAsync(string resourceGroupName, string jobName, string functionName, FunctionRetrieveDefaultDefinitionParameters functionRetrieveDefaultDefinitionParameters = default(FunctionRetrieveDefaultDefinitionParameters), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (jobName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "jobName");
}
if (functionName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "functionName");
}
string apiVersion = "2016-03-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("functionRetrieveDefaultDefinitionParameters", functionRetrieveDefaultDefinitionParameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("jobName", jobName);
tracingParameters.Add("functionName", functionName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "RetrieveDefaultDefinition", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/streamingjobs/{jobName}/functions/{functionName}/RetrieveDefaultDefinition").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{jobName}", System.Uri.EscapeDataString(jobName));
_url = _url.Replace("{functionName}", System.Uri.EscapeDataString(functionName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(functionRetrieveDefaultDefinitionParameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(functionRetrieveDefaultDefinitionParameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Function>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Function>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Tests if the information provided for a function is valid. This can range
/// from testing the connection to the underlying web service behind the
/// function or making sure the function code provided is syntactically
/// correct.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='jobName'>
/// The name of the streaming job.
/// </param>
/// <param name='functionName'>
/// The name of the function.
/// </param>
/// <param name='function'>
/// If the function specified does not already exist, this parameter must
/// contain the full function definition intended to be tested. If the function
/// specified already exists, this parameter can be left null to test the
/// existing function as is or if specified, the properties specified will
/// overwrite the corresponding properties in the existing function (exactly
/// like a PATCH operation) and the resulting function will be tested.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ResourceTestStatus>> BeginTestWithHttpMessagesAsync(string resourceGroupName, string jobName, string functionName, Function function = default(Function), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (jobName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "jobName");
}
if (functionName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "functionName");
}
string apiVersion = "2016-03-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("function", function);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("jobName", jobName);
tracingParameters.Add("functionName", functionName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginTest", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/streamingjobs/{jobName}/functions/{functionName}/test").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{jobName}", System.Uri.EscapeDataString(jobName));
_url = _url.Replace("{functionName}", System.Uri.EscapeDataString(functionName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(function != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(function, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ResourceTestStatus>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ResourceTestStatus>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Lists all of the functions under the specified streaming job.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<Function>>> ListByStreamingJobNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByStreamingJobNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<Function>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Function>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| mit |
inaturalist/inaturalist | lib/fake_view.rb | 2338 | # frozen_string_literal: true
#
# Allows access to rendering, helpers, and URL helpers from anywhere. Works by
# including URL helpers and delegating other methods to ApplicationController
#
class FakeView
include Rails.application.routes.url_helpers
def initialize( options = {} )
super()
return unless options[:view_paths]
controller.view_paths += options[:view_paths]
end
def default_url_options
@default_url_options ||= {
host: Site.default ? Site.default.url.sub( "http://", "" ) : "http://localhost",
port: Site.default && URI.parse( Site.default.url ).port != 80 ? URI.parse( Site.default.url ).port : nil,
protocol: URI.parse( Site.default.url ).scheme
}
end
def self.fake_instance
@fake_instance ||= new
end
def self.method_missing( method, *args )
fake_instance.send( method, *args )
end
def self.respond_to_missing?( method, include_private = false )
fake_instance.respond_to?( method, include_private )
end
def controller
@controller ||= ApplicationController
end
def method_missing( method, *args )
controller.send( method, *args )
rescue NoMethodError
controller.helpers.send( method, *args )
end
def respond_to_missing?( method, include_private = false )
controller.respond_to_missing?( method, include_private ) || controller.helpers.respond_to_missing?( method )
end
# Overriding this so that assets we have chosen not to be used with a digest
# don't actually use a digest
def asset_path( source, options = {} )
if source !~ /^http/ && source =~ /#{NonStupidDigestAssets.whitelist.join( "|" )}/
return "/assets/#{source}"
end
super( source, options )
end
def place_geometry_kml_url( options = {} )
place = options[:place] || @place
return "" if place.blank?
place_geometry = options[:place_geometry]
place_geometry ||= place.place_geometry_without_geom if place.association( :place_geometry_without_geom ).loaded?
place_geometry ||= place.place_geometry if place.association( :place_geometry ).loaded?
place_geometry ||= PlaceGeometry.without_geom.where( place_id: place ).first
if place_geometry.blank?
"".html_safe
else
"#{place_geometry_url( place, format: "kml" )}?#{place_geometry.updated_at.to_i}".html_safe
end
end
end
| mit |
cuckata23/wurfl-data | data/philips_x800_ver1.php | 1136 | <?php
return array (
'id' => 'philips_x800_ver1',
'fallback' => 'generic_mobile',
'capabilities' =>
array (
'model_name' => 'X800',
'brand_name' => 'Philips',
'release_date' => '2009_february',
'table_support' => 'true',
'wml_1_1' => 'true',
'wml_1_2' => 'true',
'wml_1_3' => 'true',
'physical_screen_height' => '61',
'columns' => '16',
'physical_screen_width' => '37',
'rows' => '16',
'max_image_width' => '228',
'resolution_width' => '240',
'resolution_height' => '400',
'max_image_height' => '360',
'jpg' => 'true',
'gif' => 'true',
'wbmp' => 'true',
'colors' => '262144',
'max_deck_size' => '32768',
'wap_push_support' => 'true',
'mms_max_size' => '100000',
'mms_max_width' => '640',
'mms_max_height' => '480',
'mms_gif_static' => 'true',
'mms_midi_monophonic' => 'true',
'mms_wbmp' => 'true',
'mms_amr' => 'true',
'mms_jpeg_baseline' => 'true',
'wav' => 'true',
'amr' => 'true',
'midi_monophonic' => 'true',
'streaming_real_media' => 'none',
'xhtml_file_upload' => 'supported',
),
);
| mit |
infsci2560sp16/full-stack-web-project-YichaoChen | src/main/resources/public/js/index.js | 733 | $(function() {
$.ajax({
url : "/api/index",
success : function(result) {
var question = JSON.parse(result);
for ( var i = 0; i < question.length; i++) {
$("div.question_wrapper").append(
'<p class="question" id="' + question[i].id + '">' + question[i].title + '</p>' +
'<p class="para" id="' + question[i].id + '">' + question[i].description + '</p>' +
'<p class="more" id="' + question[i].id + '">' + '<span>' + '<a href="">' + 'MORE' + '</a>' + '</p>' +
'<br/>' +
'<p class="info" id="' + question[i].id + '">' + 'Follow Answers' + '</p>' +
'<br/>' +
'<hr style="border:0.5px #cccccc dashed"/>' +
'<br/>'
);
}
}
});
}); | mit |
rakelley/jakkedweb | src/cms/routes/Testimonialqueue/views/Index.php | 795 | <?php
/**
* @package jakkedweb
* @subpackage cms
*
* All content covered under The MIT License except where included 3rd-party
* vendor files are licensed otherwise.
*
* @license http://opensource.org/licenses/MIT The MIT License
* @author Ryan Kelley
* @copyright 2011-2015 Jakked Hardcore Gym
*/
namespace cms\routes\Testimonialqueue\views;
/**
* QueueIndexView for testimonial queue
*/
class Index extends \rakelley\jhframe\classes\View implements
\rakelley\jhframe\interfaces\view\IRequiresData
{
use \cms\QueueIndexViewTrait;
function __construct(
\main\repositories\TestimonialQueue $testimonials
) {
$this->queueRepo = $testimonials;
$this->queueName = 'Testimonial';
$this->queueController = 'testimonialqueue';
}
}
| mit |
yixianle/google-translate | app/index.js | 1403 | import Koa from 'koa';
import views from 'koa-views';
import convert from 'koa-convert';
import json from 'koa-json';
import bodyParser from 'koa-bodyparser';
import methodOverride from 'koa-methodoverride';
import logger from 'koa-logger';
import path from 'path';
import config from '../config/config';
import router from './routes';
import middlewares from './middlewares';
const app = new Koa();
// console.log(config.secretKeyBase, '-------config.secretKeyBase------')
app.keys = [config.secretKeyBase];
app.use(convert(require('koa-static')(path.join(__dirname + '/../public'))));
app.use(bodyParser());
app.use(methodOverride((req, _res) => {
if (req.body && (typeof req.body === 'object') && ('_method' in req.body)) {
// look in urlencoded POST bodies and delete it
const method = req.body._method;
delete req.body._method;
return method;
}
}));
app.use(convert(json()));
app.use(convert(logger()));
//views with pug
app.use(views(__dirname + '/views', { extension: 'pug' }));
// catch error
// 临时注释
app.use(middlewares.catchError);
app.use(router.routes(), router.allowedMethods());
if (process.argv[2] && process.argv[2][0] == 'c') {
const repl = require('repl');
// global.models = models;
repl.start({
prompt: '> ',
useGlobal: true
}).on('exit', () => { process.exit(); });
}
else {
app.listen(config.port);
}
export default app;
| mit |
huin/chunkymonkey | gamerules/itemtype_loader_test.go | 1635 | package gamerules
import (
"reflect"
"strings"
"testing"
)
const threeItems = ("{\n" +
" \"256\": {\n" +
" \"Name\": \"iron shovel\",\n" +
" \"MaxStack\": 1,\n" +
" \"ToolType\": 1,\n" +
" \"ToolUses\": 251\n" +
" },\n" +
" \"264\": {\n" +
" \"Name\": \"diamond\",\n" +
" \"MaxStack\": 64\n" +
" },\n" +
" \"261\": {\n" +
" \"Name\": \"bow\",\n" +
" \"MaxStack\": 1,\n" +
" \"ToolType\": 11\n" +
" }\n" +
"}")
func assertItemTypeEq(t *testing.T, expected *ItemType, result *ItemType) {
if !reflect.DeepEqual(expected, result) {
t.Error("ItemTypes differed")
t.Logf(" expected %#v", expected)
t.Logf(" result %#v", result)
}
}
func displayItems(t *testing.T, items ItemTypeMap) {
t.Logf("%d items:", len(items))
for id, item := range items {
t.Logf(" [%d] %#v", id, item)
}
}
func TestLoadItemDefs(t *testing.T) {
reader := strings.NewReader(threeItems)
t.Log(threeItems)
items, err := LoadItemDefs(reader)
if err != nil {
t.Fatalf("Expected no error but got %v", err)
}
// All 3 items should be defined.
if len(items) != 3 {
t.Fatalf("Expected 3 item types, but got %d", len(items))
}
assertItemTypeEq(
t,
&ItemType{
Id: 256,
Name: "iron shovel",
MaxStack: 1,
ToolType: 1,
ToolUses: 251,
},
items[256],
)
assertItemTypeEq(
t,
&ItemType{
Id: 264,
Name: "diamond",
MaxStack: 64,
ToolType: 0,
ToolUses: 0,
},
items[264],
)
assertItemTypeEq(
t,
&ItemType{
Id: 261,
Name: "bow",
MaxStack: 1,
ToolType: 11,
ToolUses: 0,
},
items[261],
)
}
| mit |
Matt343/hexdef | Assets/Scripts/HexGridController.cs | 5526 | using UnityEngine;
using System.Collections.Generic;
public class HexGridController : MonoBehaviour {
public int width = 10, height = 10;
public HexController hex;
private HexController[,] grid;
private Vector3 hexSize;
List<Spawner> spawners = new List<Spawner>();
private Vector2 animationPos = Vector2.zero;
private Vector2 redPos = Vector2.zero;
private Vector2 bluePos = Vector2.zero;
private Vector2 greenPos = Vector2.zero;
public float animationScale = .1f;
public float colorScale = .1f;
private float perlinAmount = 0;
public bool animating = true;
public float backOffset = .75f;
// Use this for initialization
void Start () {
}
public static Vector3 getPositionFromGrid(int x, int y, Vector3 hexSize)
{
return new Vector3(y * hexSize.z * .75f, 0, x * hexSize.x * .875f + ((y % 2) * hexSize.x * .45f));
}
// Update is called once per frame
void Update () {
if(perlinAmount < 1)
perlinAmount = Mathf.Min(1, perlinAmount + Time.deltaTime * .5f);
if(animating)
animatePerlin(true, false, new Vector2(.5f, .5f), new Vector2(-.25f, -.25f), new Vector2(-.25f, -.25f), new Vector2(-.25f, -.25f));
}
public void setUpGrid(int w, int h)
{
width = w;
height = h;
grid = new HexController[height, width];
hexSize = hex.size;
Vector3 gridSize = getPositionFromGrid(width - 1, height - 1, hexSize);
//initiallize hex grid
for(int y = 0; y < height; y++)
{
for(int x = 0; x < width; x++)
{
//calculate position on grid
Vector3 position = getPositionFromGrid(x, y, hexSize);
position += transform.position - gridSize / 2;
GameObject newHex = Instantiate(hex.gameObject, position, Quaternion.Euler(new Vector3(270, 30, 0))) as GameObject;
newHex.transform.parent = transform;
grid[y,x] = newHex.GetComponent(typeof(HexController)) as HexController;
grid[y,x].x = x;
grid[y,x].y = y;
grid[y,x].grid = this;
grid[y,x].locked = false;
grid[y,x].defaultHeight = newHex.transform.position.y;
}
}
}
public void clearGrid()
{
if(grid != null)
{
for(int y = 0; y < height; y++)
for(int x = 0; x < width; x++)
if(grid[y,x] != null)
GameObject.Destroy(grid[y,x].gameObject);
width = 0;
height = 0;
grid = new HexController[0,0];
while(spawners.Count > 0)
{
GameObject.Destroy(spawners[spawners.Count - 1].gameObject);
spawners.RemoveAt(spawners.Count - 1);
}
}
}
public void setGridColors(int[,] colorIndices, Color[] colors)
{
for(int y = 0; y < height; y++)
{
for(int x = 0; x < width; x++)
{
grid[y,x].renderer.materials[1].color = colors[colorIndices[y,x]];
}
}
}
public void startPerlin()
{
}
void animatePerlin(bool animation, bool color, Vector2 animationDir, Vector2 redDir, Vector2 greenDir, Vector2 blueDir)
{
animationPos += animationDir * Time.deltaTime;
redPos += redDir * Time.deltaTime;
greenPos += greenDir * Time.deltaTime;
bluePos += blueDir * Time.deltaTime;
if(animation || color)
{
for(int y = 0; y < height; y++)
{
for(int x = 0; x < width; x++)
{
if(animation)
{
float perlin = (Mathf.PerlinNoise((x * animationScale) + animationPos.x, (y * animationScale) + animationPos.y) - .5f);
perlin += Mathf.Lerp(backOffset, 0, y / height);
grid[y,x].startMoving(Mathf.Lerp(0, perlin, perlinAmount), 2, false, true);
}
if(color)
grid[y,x].renderer.materials[1].color = perlinColor(x, y, grid[y,x].renderer.materials[1].color);
}
}
}
}
Color perlinColor(int x, int y, Color current)
{
float red = Mathf.PerlinNoise((x * colorScale) + redPos.x, ((y + height) * colorScale) + redPos.y);
float green = Mathf.PerlinNoise((x * colorScale) + greenPos.x, ((y + height * 2) * colorScale) + greenPos.y);
float blue = Mathf.PerlinNoise((x * colorScale) + bluePos.x, ((y + height * 3) * colorScale) + bluePos.y);
return new Color(Mathf.Lerp(current.r, red, perlinAmount), Mathf.Lerp(current.g, green, perlinAmount), Mathf.Lerp(current.b, blue, perlinAmount), 1);
}
public HexController getHex(Vector2 position)
{
return grid[(int)position.y,(int)position.x];
}
public void loadLevel(LevelAsset level, Spawner start)
{
clearGrid();
setUpGrid(level.gridWidth, level.gridHeight);
for(int y = 0; y < height; y++)
{
for(int x = 0; x < width; x++)
{
grid[y,x].setHeight(level.grid[y][x].height);
grid[y,x].locked = level.grid[y][x].path;
grid[y,x].path = level.grid[y][x].path;
grid[y,x].pathId = level.grid[y][x].pathId;
grid[y,x].setColor(level.colors[level.grid[y][x].color]);
if(level.grid[y][x].start)
{
GameObject newSpawn = Instantiate(start.gameObject, grid[y,x].transform.position + grid[y,x].spawnOffset, Quaternion.identity) as GameObject;
Spawner spawn = newSpawn.GetComponent<Spawner>();
spawn.startNode = grid[y,x];
spawn.setWave(0);
spawners.Add(spawn);
}
grid[y,x].nextNodes = new List<HexController>();
for(int i = 0; i < 6; i++)
{
bool active = ((level.grid[y][x].nextPositions & (1 << i)) != 0);
if(active)
{
Vector2 pathPoint = (y % 2 == 0) ? HexInfo.pathPointsEven[i] : HexInfo.pathPointsOdd[i];
Vector2 next = level.grid[y][x].position + pathPoint;
if(next.x >=0 && next.y >=0 && next.x < width && next.y < height)
{
grid[y,x].nextNodes.Add(grid[(int)next.y, (int)next.x]);
}
}
}
}
}
}
}
| mit |
CS2103JAN2017-F12-B4/main | src/main/java/seedu/bulletjournal/commons/exceptions/DuplicateDataException.java | 291 | package seedu.bulletjournal.commons.exceptions;
/**
* Signals an error caused by duplicate data where there should be none.
*/
public abstract class DuplicateDataException extends IllegalValueException {
public DuplicateDataException(String message) {
super(message);
}
}
| mit |
cstoquer/bob64 | src/FadeTransition.js | 1541 | var TILE_WIDTH = settings.spriteSize[0];
var TILE_HEIGHT = settings.spriteSize[1];
//▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
function FadeTransition() {
this.transitionCount = 0;
this.img = assets.ditherFondu;
this.onFinishCallback = null;
}
module.exports = FadeTransition;
//▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
FadeTransition.prototype.start = function (options, cb) {
options = options || {};
this.img = options.img || assets.ditherFondu;
this.onFinishCallback = cb;
this.transitionCount = -30;
return this;
};
//▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
/** return true if it continues and false when ended */
FadeTransition.prototype.update = function () {
camera(0, 0);
draw(this.img, 0, this.transitionCount * TILE_HEIGHT);
if (++this.transitionCount > 0) {
// this.loadLevel(nextLevel, nextDoor, nextSide);
this.onFinishCallback && this.onFinishCallback();
this.onFinishCallback = null;
return false;
}
return true;
};
| mit |
zzsza/TIL | python/crawling/redis_cache.py | 1650 | import json
import zlib
from datetime import datetime, timedelta
from redis import StrictRedis
class RedisCache:
""" RedisCache helps store urls and their responses to Redis
Initialization components:
client: a Redis client connected to the key-value database for
the webcrawling cache (if not set, a localhost:6379
default connection is used).
expires (datetime.timedelta): timedelta when content will expire
(default: 30 days ago)
encoding (str): character encoding for serialization
compress (bool): boolean indicating whether compression with zlib should be used
"""
def __init__(self, client=None, expires=timedelta(days=30), encoding='utf-8', compress=True):
self.client = (StrictRedis(host='localhost', port=6379, db=0)
if client is None else client)
self.expires = expires
self.encoding = encoding
self.compress = compress
def __getitem__(self, url):
"""Load data from Redis for given URL"""
record = self.client.get(url)
if record:
if self.compress:
record = zlib.decompress(record)
return json.loads(record.decode(self.encoding))
else:
# URL has not yet been cached
raise KeyError(url + ' does not exist')
def __setitem__(self, url, result):
"""Save data to Redis for given url"""
data = bytes(json.dumps(result), self.encoding)
if self.compress:
data = zlib.compress(data)
self.client.setex(url, self.expires, data)
| mit |
autouser/active-classifier | test/active-classifier_test.rb | 321 | require 'test_helper'
class ActiveClassifierTest < ActiveSupport::TestCase
test "truth" do
assert_kind_of Module, ActiveClassifier
end
test "class_tree" do
assert_equal ({"Item"=>{"Device"=>{"Modem"=>{"DummyModem"=>{"Telsey"=>{}}}}}}), ActiveClassifier.class_tree, "should register class_tree"
end
end
| mit |
zzzzRuby/Skuld | src/backend/Audio/XAudio2/XAudio2Sound.cpp | 1029 | #include "XAudio2Device.h"
#include "XAudio2Sound.h"
namespace Skuld
{
namespace Audio
{
Handle<XAudio2Sound> XAudio2Sound::Create(HandleRef<XAudio2Device> mDevice, const Codec::WaveInfo& mInfo, HandleRef<IBuffer> mBuffer)
{
Handle<XAudio2Sound> mRet = NewHandle<XAudio2Sound>(mDevice->GetFactory());
WAVEFORMATEX mInfoEx;
WaveInfoToWAVEFORMATEX(mInfo, mInfoEx);
HRESULT hr = mDevice->XAudio()->CreateSourceVoice(&mRet->mSource, &mInfoEx, 0, 2.0f, mRet.GetPtr());
if (FAILED(hr)) return nullptr;
memset(&mRet->mEmitter, 0, sizeof(mRet->mEmitter));
memset(&mRet->mXB, 0, sizeof(mRet->mXB));
mRet->mXB.AudioBytes = static_cast<UINT32>(mBuffer->size());
mRet->mXB.pAudioData = mBuffer->buffer();
mRet->mXB.Flags = XAUDIO2_END_OF_STREAM;
mRet->mBuffer = mBuffer;
return mRet;
}
void XAudio2Sound::SubmitBuffer()
{
mSource->SubmitSourceBuffer(&mXB);
}
void XAudio2Sound::OnStreamEnd()
{
mState = SoundState::Stopped;
if (mLoop) Play();
else Stop();
}
}
} | mit |
BluestoneEU/TypeGap | LukasKabrt-typelite-076249af9d12/TypeLite/TsModels/TsClass.cs | 4450 | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Reflection;
using TypeLite.Extensions;
namespace TypeLite.TsModels {
/// <summary>
/// Represents a class in the code model.
/// </summary>
[DebuggerDisplay("TsClass - Name: {Name}")]
public class TsClass : TsModuleMember {
/// <summary>
/// Gets collection of properties of the class.
/// </summary>
public ICollection<TsProperty> Properties { get; private set; }
/// <summary>
/// Gets collection of fields of the class.
/// </summary>
public ICollection<TsProperty> Fields { get; private set; }
/// <summary>
/// Gets collection of GenericArguments for this class
/// </summary>
public IList<TsType> GenericArguments { get; private set; }
/// <summary>
/// Gets collection of constants of the class.
/// </summary>
public ICollection<TsProperty> Constants { get; private set; }
/// <summary>
/// Gets base type of the class
/// </summary>
/// <remarks>
/// If the class derives from the object, the BaseType property is null.
/// </remarks>
public TsType BaseType { get; internal set; }
// TODO document
public IList<TsType> Interfaces { get; internal set; }
/// <summary>
/// Gets or sets bool value indicating whether this class will be ignored by TsGenerator.
/// </summary>
public bool IsIgnored { get; set; }
/// <summary>
/// Initializes a new instance of the TsClass class with the specific CLR type.
/// </summary>
/// <param name="type">The CLR type represented by this instance of the TsClass</param>
public TsClass(Type type)
: base(type)
{
var dnxCompatible = this.Type.GetDnxCompatible();
this.Properties = dnxCompatible
.GetProperties()
.Where(pi => pi.DeclaringType == this.Type
&& pi.GetSetMethod() != null) // skip read-only
.Select(pi => new TsProperty(pi))
.ToList();
this.Fields = dnxCompatible
.GetFields()
.Where(fi => fi.DeclaringType == this.Type
&& !(fi.IsLiteral && !fi.IsInitOnly)) // skip constants
.Select(fi => new TsProperty(fi))
.ToList();
this.Constants = dnxCompatible
.GetFields()
.Where(fi => fi.DeclaringType == this.Type
&& fi.IsLiteral && !fi.IsInitOnly) // constants only
.Select(fi => new TsProperty(fi))
.ToList();
if (type.GetDnxCompatible().IsGenericType) {
this.Name = type.Name.Remove(type.Name.IndexOf('`'));
this.GenericArguments = type
.GetDnxCompatible()
.GetGenericArguments()
.Select(TsType.Create)
.ToList();
} else {
this.Name = type.Name;
this.GenericArguments = new TsType[0];
}
if (dnxCompatible.BaseType != null && dnxCompatible.BaseType != typeof(object) && dnxCompatible.BaseType != typeof(ValueType)) {
this.BaseType = new TsType(dnxCompatible.BaseType);
}
var interfaces = dnxCompatible.GetInterfaces();
this.Interfaces = interfaces
.Where(@interface => @interface.GetCustomAttribute<TsInterfaceAttribute>(false) != null)
.Except(interfaces.SelectMany(@interface => @interface.GetDnxCompatible().GetInterfaces()))
.Select(TsType.Create).ToList();
var attribute = this.Type.GetCustomAttribute<TsClassAttribute>(false);
if (attribute != null) {
if (!string.IsNullOrEmpty(attribute.Name)) {
this.Name = attribute.Name;
}
if (attribute.Module != null) {
this.Module.Name = attribute.Module;
}
}
var ignoreAttribute = this.Type.GetCustomAttribute<TsIgnoreAttribute>(false);
if (ignoreAttribute != null) {
this.IsIgnored = true;
}
}
}
}
| mit |
oakmac/autocompletejs | examples/6001.js | 409 | var onChange = function(newValue, oldValue) {
if (newValue.length < oldValue.length) {
var msg = 'Are you sure you want to remove this fruit?';
var sure = confirm(msg);
if (sure !== true) {
return oldValue;
}
}
return newValue;
};
var config = {
onChange: onChange,
lists: {
fruits: ['Apple', 'Banana', 'Orange']
}
};
var widget = new AutoComplete('search_bar', config); | mit |
mossimokim/FSND-P1-Movie-Trailer | fresh_tomatoes.py | 5783 | import webbrowser
import os
import re
# Styles and scripting for the page
pageTitle ='Youtube Viewer'
main_page_head = '''
<head>
<meta charset="utf-8">
<title>Fresh Tomatoes!</title>
<!-- Bootstrap 3 -->
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap-theme.min.css">
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.1.0/js/bootstrap.min.js"></script>
<style type="text/css" media="screen">
body {
padding-top: 80px;
background-color:#111;
opacity: 1.0;
}
h2 {
font-size: 18px;
color: #ffffff;
min-height: 60px;
}
#trailer .modal-dialog {
margin-top: 200px;
width: 540px;
height: 490px;
}
.hanging-close {
position: absolute;
top: -12px;
right: -12px;
z-index: 9001;
}
#trailer-video {
width: 100%;
height: 100%;
}
.movie-tile {
margin-bottom: 0px;
padding-top: 20px;
}
.movie-tile:hover {
background-color: #333;
cursor: pointer;
}
.scale-media {
padding-bottom: 56.25%;
position: relative;
}
.scale-media iframe {
border: none;
height: 100%;
position: absolute;
width: 100%;
left: 0;
top: 0;
background-color: white;
}
</style>
<script type="text/javascript" charset="utf-8">
// Pause the video when the modal is closed
$(document).on('click', '.hanging-close, .modal-backdrop, .modal', function (event) {
// Remove the src so the player itself gets removed, as this is the only
// reliable way to ensure the video stops playing in IE
$("#trailer-video-container").empty();
});
// Start playing the video whenever the trailer modal is opened
$(document).on('click', '.movie-tile', function (event) {
$('body').css.opacity = '0.2'
var trailerYouTubeId = $(this).attr('data-trailer-youtube-id')
var sourceUrl = 'http://www.youtube.com/embed/' + trailerYouTubeId + '?autoplay=1&html5=1';
$("#trailer-video-container").empty().append($("<iframe></iframe>", {
'id': 'trailer-video',
'type': 'text-html',
'src': sourceUrl,
'frameborder': 0
}));
});
// Animate in the movies when the page loads
$(document).ready(function () {
$('.movie-tile').hide().first().show("fast", function showNext() {
$(this).next("div").show("fast", showNext);
});
});
</script>
</head>
'''
# The main page layout and title bar
main_page_content = '''
<!DOCTYPE html>
<html lang="en">
<body>
<!-- Trailer Video Modal -->
<div class="modal" id="trailer">
<div class="modal-dialog">
<div class="modal-content">
<a href="#" class="hanging-close" data-dismiss="modal" aria-hidden="true">
<img src="https://lh5.ggpht.com/v4-628SilF0HtHuHdu5EzxD7WRqOrrTIDi_MhEG6_qkNtUK5Wg7KPkofp_VJoF7RS2LhxwEFCO1ICHZlc-o_=s0#w=24&h=24"/>
</a>
<div class="scale-media" id="trailer-video-container">
</div>
</div>
</div>
</div>
<!-- Main Page Content -->
<div class="container">
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="#">''' + pageTitle + '''</a>
</div>
</div>
</div>
</div>
<div class="container">
{movie_tiles}
</div>
</body>
</html>
'''
# A single movie entry html template
movie_tile_content = '''
<div class="col-md-6 col-lg-4 movie-tile text-center" data-trailer-youtube-id="{trailer_youtube_id}" data-toggle="modal" data-target="#trailer">
<img data-toggle="tooltip" title="{description}" src="{poster_image_url}" width="240" height="180">
<h2>{movie_title}</h2>
</div>
'''
def create_movie_tiles_content(movies):
# The HTML content for this section of the page
content = ''
for movie in movies:
# Extract the youtube ID from the url
youtube_id_match = re.search(r'(?<=v=)[^&#]+', movie.trailer_youtube_url)
youtube_id_match = youtube_id_match or re.search(r'(?<=be/)[^&#]+', movie.trailer_youtube_url)
trailer_youtube_id = youtube_id_match.group(0) if youtube_id_match else None
# Append the tile for the movie with its content filled in
content += movie_tile_content.format(
movie_title=movie.title,
poster_image_url=movie.poster_image_url,
trailer_youtube_id=trailer_youtube_id,
description = movie.storyline
)
return content
def open_movies_page(movies):
# Create or overwrite the output file
output_file = open('fresh_tomatoes.html', 'w')
# Replace the placeholder for the movie tiles with the actual dynamically generated content
rendered_content = main_page_content.format(movie_tiles=create_movie_tiles_content(movies))
# Output the file
output_file.write(main_page_head + rendered_content)
output_file.close()
# open the output file in the browser
url = os.path.abspath(output_file.name)
webbrowser.open('file://' + url, new=2) # open in a new tab, if possible | mit |
Equilibrium-Games/Flounder | Sources/Files/Json/Json.cpp | 7286 | #include "Json.hpp"
#include "Utils/Enumerate.hpp"
#include "Utils/String.hpp"
#define ATTRIBUTE_TEXT_SUPPORT 1
namespace acid {
void Json::ParseString(Node &node, std::string_view string) {
// Tokenizes the string view into small views that are used to build a Node tree.
std::vector<Node::Token> tokens;
std::size_t tokenStart = 0;
enum class QuoteState : char {
None = '\0', Single = '\'', Double = '"'
} quoteState = QuoteState::None;
// Iterates over all the characters in the string view.
for (auto &&[index, c] : Enumerate(string)) {
// If the previous character was a backslash the quote will not break the string.
if (c == '\'' && quoteState != QuoteState::Double && string[index - 1] != '\\')
quoteState = quoteState == QuoteState::None ? QuoteState::Single : QuoteState::None;
else if (c == '"' && quoteState != QuoteState::Single && string[index - 1] != '\\')
quoteState = quoteState == QuoteState::None ? QuoteState::Double : QuoteState::None;
// When not reading a string tokens can be found.
// While in a string whitespace and tokens are added to the strings view.
if (quoteState == QuoteState::None) {
if (String::IsWhitespace(c)) {
// On whitespace start save current token.
AddToken(std::string_view(string.data() + tokenStart, index - tokenStart), tokens);
tokenStart = index + 1;
} else if (c == ':' || c == '{' || c == '}' || c == ',' || c == '[' || c == ']') {
// Tokens used to read json nodes.
AddToken(std::string_view(string.data() + tokenStart, index - tokenStart), tokens);
tokens.emplace_back(Node::Type::Token, std::string_view(string.data() + index, 1));
tokenStart = index + 1;
}
}
}
// Converts the tokens into nodes.
int32_t k = 0;
Convert(node, tokens, k);
}
void Json::WriteStream(const Node &node, std::ostream &stream, Node::Format format) {
stream << (node.GetType() == Node::Type::Array ? '[' : '{') << format.newLine;
AppendData(node, stream, format, 1);
stream << (node.GetType() == Node::Type::Array ? ']' : '}');
}
void Json::AddToken(std::string_view view, std::vector<Node::Token> &tokens) {
if (view.length() != 0) {
// Finds the node value type of the string and adds it to the tokens vector.
if (view == "null") {
tokens.emplace_back(Node::Type::Null, std::string_view());
} else if (view == "true" || view == "false") {
tokens.emplace_back(Node::Type::Boolean, view);
} else if (String::IsNumber(view)) {
// This is a quick hack to get if the number is a decimal.
if (view.find('.') != std::string::npos) {
if (view.size() >= std::numeric_limits<long double>::digits)
throw std::runtime_error("Decimal number is too long");
tokens.emplace_back(Node::Type::Decimal, view);
} else {
if (view.size() >= std::numeric_limits<uint64_t>::digits)
throw std::runtime_error("Integer number is too long");
tokens.emplace_back(Node::Type::Integer, view);
}
} else { // if (view.front() == view.back() == '\"')
tokens.emplace_back(Node::Type::String, view.substr(1, view.length() - 2));
}
}
}
void Json::Convert(Node ¤t, const std::vector<Node::Token> &tokens, int32_t &k) {
if (tokens[k] == Node::Token(Node::Type::Token, "{")) {
k++;
while (tokens[k] != Node::Token(Node::Type::Token, "}")) {
auto key = tokens[k].view;
if (k + 2 >= tokens.size())
throw std::runtime_error("Missing end of {} array");
if (tokens[k + 1].view != ":")
throw std::runtime_error("Missing object colon");
k += 2;
#if ATTRIBUTE_TEXT_SUPPORT
// Write value string into current value, then continue parsing properties into current.
if (key == "#text")
Convert(current, tokens, k);
else
#endif
Convert(current.AddProperty(std::string(key)), tokens, k);
if (tokens[k].view == ",")
k++;
}
k++;
current.SetType(Node::Type::Object);
} else if (tokens[k] == Node::Token(Node::Type::Token, "[")) {
k++;
while (tokens[k] != Node::Token(Node::Type::Token, "]")) {
if (k >= tokens.size())
throw std::runtime_error("Missing end of [] object");
Convert(current.AddProperty(), tokens, k);
if (tokens[k].view == ",")
k++;
}
k++;
current.SetType(Node::Type::Array);
} else {
std::string str(tokens[k].view);
if (tokens[k].type == Node::Type::String)
str = String::UnfixEscapedChars(str);
current.SetValue(str);
current.SetType(tokens[k].type);
k++;
}
}
void Json::AppendData(const Node &node, std::ostream &stream, Node::Format format, int32_t indent) {
auto indents = format.GetIndents(indent);
// Only output the value if no properties exist.
if (node.GetProperties().empty()) {
if (node.GetType() == Node::Type::String)
stream << '\"' << String::FixEscapedChars(node.GetValue()) << '\"';
else if (node.GetType() == Node::Type::Null)
stream << "null";
else
stream << node.GetValue();
}
#if ATTRIBUTE_TEXT_SUPPORT
// If the Json Node has both properties and a value, value will be written as a "#text" property.
// XML is the only format that allows a Node to have both a value and properties.
if (!node.GetProperties().empty() && !node.GetValue().empty()) {
stream << indents;
stream << "\"#text\":" << format.space << "\"" << node.GetValue() << "\",";
// No new line if the indent level is zero (if primitive array type).
stream << (indent != 0 ? format.newLine : format.space);
}
#endif
// Output each property.
for (auto it = node.GetProperties().begin(); it < node.GetProperties().end(); ++it) {
stream << indents;
// Output name for property if it exists.
if (!it->GetName().empty()) {
stream << '\"' << it->GetName() << "\":" << format.space;
}
bool isArray = false;
if (!it->GetProperties().empty()) {
// If all properties have no names, then this must be an array.
for (const auto &property2 : it->GetProperties()) {
if (property2.GetName().empty()) {
isArray = true;
break;
}
}
stream << (isArray ? '[' : '{') << format.newLine;
} else if (it->GetType() == Node::Type::Object) {
stream << '{';
} else if (it->GetType() == Node::Type::Array) {
stream << '[';
}
// If a node type is a primitive type.
static constexpr auto IsPrimitive = [](const Node &type) {
return type.GetProperties().empty() && type.GetType() != Node::Type::Object && type.GetType() != Node::Type::Array && type.GetType() != Node::Type::Unknown;
};
// Shorten primitive array output length.
if (isArray && format.inlineArrays && !it->GetProperties().empty() && IsPrimitive(it->GetProperties()[0])) {
stream << format.GetIndents(indent + 1);
// New lines are printed a a space, no spaces are ever emitted by primitives.
AppendData(*it, stream, Node::Format(0, '\0', '\0', false), indent);
stream << '\n';
} else {
AppendData(*it, stream, format, indent + 1);
}
if (!it->GetProperties().empty()) {
stream << indents << (isArray ? ']' : '}');
} else if (it->GetType() == Node::Type::Object) {
stream << '}';
} else if (it->GetType() == Node::Type::Array) {
stream << ']';
}
// Separate properties by comma.
if (it != node.GetProperties().end() - 1)
stream << ',';
// No new line if the indent level is zero (if primitive array type).
stream << (indent != 0 ? format.newLine : format.space);
}
}
}
| mit |
reevoo/dbenvy | spec/unit/dbenvy_spec.rb | 3173 | require 'spec_helper'
require 'dbenvy'
describe DBEnvy do
describe '.to_hash' do
context 'with a DATABSE_URL in the environment' do
let(:hash) { described_class.to_hash }
before do
ENV['DATABASE_URL'] = 'mysql2://susan:sekret@127.0.0.1:3306/reevoo_live?encoding=utf8&view_options[awesome_database]=awesome_live'
end
it 'extracts the adapter' do
expect(hash['adapter']).to eq 'mysql2'
end
it 'extracts the host' do
expect(hash['host']).to eq '127.0.0.1'
end
it 'extracts the database name' do
expect(hash['database']).to eq 'reevoo_live'
end
it 'extracts the username' do
expect(hash['username']).to eq 'susan'
end
it 'extracts the password' do
expect(hash['password']).to eq 'sekret'
end
it 'extracts the port' do
expect(hash['port']).to eq 3306
end
it 'extracts some standard query params' do
expect(hash['encoding']).to eq 'utf8'
end
end
end
describe '.yaml' do
let(:yaml) { described_class.yaml }
context 'when the DATABASE_URL is not set' do
before do
ENV['RAILS_ENV'] = nil
ENV['DATABASE_URL'] = nil
end
it 'is nil' do
expect(yaml).to be_nil
end
end
context 'when RAILS_ENV is not set but Rails.env is avaliable' do
module Rails
extend self
def env
nil
end
end
context 'uses RAILS_ENV if it can' do
before do
ENV['DATABASE_URL'] = 'mysql2://reevoo:secret@db456.reevoover.com:3306/reevoo_awesome'
ENV['RAILS_ENV'] = 'ENV'
allow(Rails).to receive(:env).and_return('env')
end
specify do
expect(YAML.load(yaml)['ENV']).to_not be_nil
expect(YAML.load(yaml)['env']).to be_nil
end
end
context 'uses Rails.env if RAILS_ENV is not set' do
before do
ENV['DATABASE_URL'] = 'mysql2://reevoo:secret@db456.reevoover.com:3306/reevoo_awesome'
ENV['RAILS_ENV'] = nil
allow(Rails).to receive(:env).and_return('env')
end
specify do
expect(YAML.load(yaml)['ENV']).to be_nil
expect(YAML.load(yaml)['env']).to_not be_nil
end
end
end
context 'when RAILS_ENV is set' do
before do
ENV['RAILS_ENV'] = 'production'
ENV['DATABASE_URL'] = 'mysql2://reevoo:secret@db456.reevoover.com:3306/reevoo_awesome?encoding=utf8&view_options[awesome_database]=awesome_live&socket=%2Fvar%2Frun%2Fmysqld%2Fmysqld.sock'
end
it 'uses the current rails env and extracts the database info' do
expect(YAML.load(yaml)).to eq(
"production" => {
"adapter" => "mysql2",
"username" => "reevoo",
"port" => 3306,
"host" => "db456.reevoover.com",
"database" => "reevoo_awesome",
"password" => "secret",
"encoding" => "utf8",
"socket" => "/var/run/mysqld/mysqld.sock",
"view_options" => {"awesome_database" => "awesome_live"}})
end
end
end
end
| mit |
proxip/kantin | application/views/layouts/main.php | 13832 | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>kantin (1)</title>
<!-- Tell the browser to be responsive to screen width -->
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<!-- Bootstrap 3.3.6 -->
<link rel="stylesheet" href="<?php echo site_url('resources/css/bootstrap.min.css');?>">
<!-- Font Awesome -->
<link rel="stylesheet" href="<?php echo site_url('resources/css/font-awesome.min.css');?>">
<!-- Ionicons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css">
<!-- Datetimepicker -->
<link rel="stylesheet" href="<?php echo site_url('resources/css/bootstrap-datetimepicker.min.css');?>">
<!-- Theme style -->
<link rel="stylesheet" href="<?php echo site_url('resources/css/AdminLTE.min.css');?>">
<!-- AdminLTE Skins. Choose a skin from the css/skins
folder instead of downloading all of them to reduce the load. -->
<link rel="stylesheet" href="<?php echo site_url('resources/css/_all-skins.min.css');?>">
</head>
<body class="hold-transition skin-blue sidebar-mini">
<div class="wrapper">
<header class="main-header">
<!-- Logo -->
<a href="" class="logo">
<!-- mini logo for sidebar mini 50x50 pixels -->
<span class="logo-mini">kantin (1)</span>
<!-- logo for regular state and mobile devices -->
<span class="logo-lg">kantin (1)</span>
</a>
<!-- Header Navbar: style can be found in header.less -->
<nav class="navbar navbar-static-top">
<!-- Sidebar toggle button-->
<a href="#" class="sidebar-toggle" data-toggle="offcanvas" role="button">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<div class="navbar-custom-menu">
<ul class="nav navbar-nav">
<!-- User Account: style can be found in dropdown.less -->
<li class="dropdown user user-menu">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<img src="<?php echo site_url('resources/img/user2-160x160.jpg');?>" class="user-image" alt="User Image">
<span class="hidden-xs">Alexander Pierce</span>
</a>
<ul class="dropdown-menu">
<!-- User image -->
<li class="user-header">
<img src="<?php echo site_url('resources/img/user2-160x160.jpg');?>" class="img-circle" alt="User Image">
<p>
Alexander Pierce - Web Developer
<small>Member since Nov. 2012</small>
</p>
</li>
<!-- Menu Footer-->
<li class="user-footer">
<div class="pull-left">
<a href="#" class="btn btn-default btn-flat">Profile</a>
</div>
<div class="pull-right">
<a href="#" class="btn btn-default btn-flat">Sign out</a>
</div>
</li>
</ul>
</li>
</ul>
</div>
</nav>
</header>
<!-- Left side column. contains the logo and sidebar -->
<aside class="main-sidebar">
<!-- sidebar: style can be found in sidebar.less -->
<section class="sidebar">
<!-- Sidebar user panel -->
<div class="user-panel">
<div class="pull-left image">
<img src="<?php echo site_url('resources/img/user2-160x160.jpg');?>" class="img-circle" alt="User Image">
</div>
<div class="pull-left info">
<p>Alexander Pierce</p>
<a href="#"><i class="fa fa-circle text-success"></i> Online</a>
</div>
</div>
<!-- sidebar menu: : style can be found in sidebar.less -->
<ul class="sidebar-menu">
<li class="header">MAIN NAVIGATION</li>
<li>
<a href="<?php echo site_url();?>">
<i class="fa fa-dashboard"></i> <span>Dashboard</span>
</a>
</li>
<li>
<a href="#">
<i class="fa fa-desktop"></i> <span>Bagi Hasil</span>
</a>
<ul class="treeview-menu">
<li class="active">
<a href="<?php echo site_url('bagi_hasil/add');?>"><i class="fa fa-plus"></i> Add</a>
</li>
<li>
<a href="<?php echo site_url('bagi_hasil/index');?>"><i class="fa fa-list-ul"></i> Listing</a>
</li>
</ul>
</li>
<li>
<a href="#">
<i class="fa fa-desktop"></i> <span>Brg Masuk</span>
</a>
<ul class="treeview-menu">
<li class="active">
<a href="<?php echo site_url('brg_masuk/add');?>"><i class="fa fa-plus"></i> Add</a>
</li>
<li>
<a href="<?php echo site_url('brg_masuk/index');?>"><i class="fa fa-list-ul"></i> Listing</a>
</li>
</ul>
</li>
<li>
<a href="#">
<i class="fa fa-desktop"></i> <span>Df Penguru</span>
</a>
<ul class="treeview-menu">
<li class="active">
<a href="<?php echo site_url('df_penguru/add');?>"><i class="fa fa-plus"></i> Add</a>
</li>
<li>
<a href="<?php echo site_url('df_penguru/index');?>"><i class="fa fa-list-ul"></i> Listing</a>
</li>
</ul>
</li>
<li>
<a href="#">
<i class="fa fa-desktop"></i> <span>Lap Bulanan</span>
</a>
<ul class="treeview-menu">
<li class="active">
<a href="<?php echo site_url('lap_bulanan/add');?>"><i class="fa fa-plus"></i> Add</a>
</li>
<li>
<a href="<?php echo site_url('lap_bulanan/index');?>"><i class="fa fa-list-ul"></i> Listing</a>
</li>
</ul>
</li>
<li>
<a href="#">
<i class="fa fa-desktop"></i> <span>Lap Keuangan</span>
</a>
<ul class="treeview-menu">
<li class="active">
<a href="<?php echo site_url('lap_keuangan/add');?>"><i class="fa fa-plus"></i> Add</a>
</li>
<li>
<a href="<?php echo site_url('lap_keuangan/index');?>"><i class="fa fa-list-ul"></i> Listing</a>
</li>
</ul>
</li>
<li>
<a href="#">
<i class="fa fa-desktop"></i> <span>Pengeluaran</span>
</a>
<ul class="treeview-menu">
<li class="active">
<a href="<?php echo site_url('pengeluaran/add');?>"><i class="fa fa-plus"></i> Add</a>
</li>
<li>
<a href="<?php echo site_url('pengeluaran/index');?>"><i class="fa fa-list-ul"></i> Listing</a>
</li>
</ul>
</li>
<li>
<a href="#">
<i class="fa fa-desktop"></i> <span>Tb Barang</span>
</a>
<ul class="treeview-menu">
<li class="active">
<a href="<?php echo site_url('tb_barang/add');?>"><i class="fa fa-plus"></i> Add</a>
</li>
<li>
<a href="<?php echo site_url('tb_barang/index');?>"><i class="fa fa-list-ul"></i> Listing</a>
</li>
</ul>
</li>
<li>
<a href="#">
<i class="fa fa-desktop"></i> <span>Periode</span>
</a>
<ul class="treeview-menu">
<li class="active">
<a href="<?php echo site_url('periode/add');?>"><i class="fa fa-plus"></i> Add</a>
</li>
<li>
<a href="<?php echo site_url('periode/index');?>"><i class="fa fa-list-ul"></i> Listing</a>
</li>
</ul>
</li>
<li>
<a href="#">
<i class="fa fa-desktop"></i> <span>Nilai Bagi</span>
</a>
<ul class="treeview-menu">
<li class="active">
<a href="<?php echo site_url('nilai_bagi/add');?>"><i class="fa fa-plus"></i> Add</a>
</li>
<li>
<a href="<?php echo site_url('nilai_bagi/index');?>"><i class="fa fa-list-ul"></i> Listing</a>
</li>
</ul>
</li>
</ul>
</section>
<!-- /.sidebar -->
</aside>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Main content -->
<section class="content">
<?php
if(isset($_view) && $_view)
$this->load->view($_view);
?>
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<footer class="main-footer">
</footer>
<!-- Control Sidebar -->
<aside class="control-sidebar control-sidebar-dark">
<!-- Create the tabs -->
<ul class="nav nav-tabs nav-justified control-sidebar-tabs">
</ul>
<!-- Tab panes -->
<div class="tab-content">
<!-- Home tab content -->
<div class="tab-pane" id="control-sidebar-home-tab">
</div>
<!-- /.tab-pane -->
<!-- Stats tab content -->
<div class="tab-pane" id="control-sidebar-stats-tab">Stats Tab Content</div>
<!-- /.tab-pane -->
</div>
</aside>
<!-- /.control-sidebar -->
<!-- Add the sidebar's background. This div must be placed
immediately after the control sidebar -->
<div class="control-sidebar-bg"></div>
</div>
<!-- ./wrapper -->
<!-- jQuery 2.2.3 -->
<script src="<?php echo site_url('resources/js/jquery-2.2.3.min.js');?>"></script>
<!-- Bootstrap 3.3.6 -->
<script src="<?php echo site_url('resources/js/bootstrap.min.js');?>"></script>
<!-- FastClick -->
<script src="<?php echo site_url('resources/js/fastclick.js');?>"></script>
<!-- AdminLTE App -->
<script src="<?php echo site_url('resources/js/app.min.js');?>"></script>
<!-- AdminLTE for demo purposes -->
<script src="<?php echo site_url('resources/js/demo.js');?>"></script>
<!-- DatePicker -->
<script src="<?php echo site_url('resources/js/moment.js');?>"></script>
<script src="<?php echo site_url('resources/js/bootstrap-datetimepicker.min.js');?>"></script>
<script src="<?php echo site_url('resources/js/global.js');?>"></script>
</body>
</html>
| mit |
RicardoSaracino/sarasoft | src/AppBundle/Repository/TaxTypeRepository.php | 1147 | <?php
/**
* @author Ricardo Saracino
* @since 2/2/17
*/
namespace AppBundle\Repository;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use CommerceGuys\Tax\Repository\TaxTypeRepositoryInterface;
/**
* Class TaxRateRepository
* @package AppBundle\Repository
*/
class TaxTypeRepository extends EntityRepository implements TaxTypeRepositoryInterface
{
/**
* @param string $id
* @return \CommerceGuys\Tax\Repository\TaxTypeInterface
* @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
*/
public function get($id)
{
throw new NotFoundHttpException(sprintf('No tax type available for %s', $id));
}
/**
* @return \CommerceGuys\Tax\Repository\TaxTypeInterface[]
* @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
*/
public function getAll()
{
static $taxTypes = null;
if(!is_null($taxTypes)){
return $taxTypes;
}
$taxTypes = $this->createQueryBuilder('t')
->getQuery()
->getResult();
if (null === $taxTypes) {
throw new NotFoundHttpException('No tax types available for');
}
return $taxTypes;
}
} | mit |
JesseTG/Pants-On-Fire | config/passport.js | 14979 | const _ = require('lodash');
const passport = require('passport');
const request = require('request');
const LocalStrategy = require('passport-local').Strategy;
const FacebookStrategy = require('passport-facebook').Strategy;
const TwitterStrategy = require('passport-twitter').Strategy;
const GitHubStrategy = require('passport-github').Strategy;
const GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
const LinkedInStrategy = require('passport-linkedin-oauth2').Strategy;
const OpenIDStrategy = require('passport-openid').Strategy;
const OAuthStrategy = require('passport-oauth').OAuthStrategy;
const OAuth2Strategy = require('passport-oauth').OAuth2Strategy;
const User = require('../models/User');
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => {
done(err, user);
});
});
/**
* Sign in using Email and Password.
*/
passport.use(new LocalStrategy({ usernameField: 'email' }, (email, password, done) => {
User.findOne({ email: email.toLowerCase() }, (err, user) => {
if (err) { return done(err); }
if (!user) {
return done(null, false, { msg: `Email ${email} not found.` });
}
user.comparePassword(password, (err, isMatch) => {
if (err) { return done(err); }
if (isMatch) {
return done(null, user);
}
return done(null, false, { msg: 'Invalid email or password.' });
});
});
}));
/**
* OAuth Strategy Overview
*
* - User is already logged in.
* - Check if there is an existing account with a provider id.
* - If there is, return an error message. (Account merging not supported)
* - Else link new OAuth account with currently logged-in user.
* - User is not logged in.
* - Check if it's a returning user.
* - If returning user, sign in and we are done.
* - Else check if there is an existing account with user's email.
* - If there is, return an error message.
* - Else create a new account.
*/
/**
* Sign in with Facebook.
*/
passport.use(new FacebookStrategy({
clientID: process.env.FACEBOOK_ID,
clientSecret: process.env.FACEBOOK_SECRET,
callbackURL: '/auth/facebook/callback',
profileFields: ['name', 'email', 'link', 'locale', 'timezone'],
passReqToCallback: true
}, (req, accessToken, refreshToken, profile, done) => {
if (req.user) {
User.findOne({ facebook: profile.id }, (err, existingUser) => {
if (err) { return done(err); }
if (existingUser) {
req.flash('errors', { msg: 'There is already a Facebook account that belongs to you. Sign in with that account or delete it, then link it with your current account.' });
done(err);
} else {
User.findById(req.user.id, (err, user) => {
if (err) { return done(err); }
user.facebook = profile.id;
user.tokens.push({ kind: 'facebook', accessToken });
user.profile.name = user.profile.name || `${profile.name.givenName} ${profile.name.familyName}`;
user.profile.gender = user.profile.gender || profile._json.gender;
user.profile.picture = user.profile.picture || `https://graph.facebook.com/${profile.id}/picture?type=large`;
user.save((err) => {
req.flash('info', { msg: 'Facebook account has been linked.' });
done(err, user);
});
});
}
});
} else {
User.findOne({ facebook: profile.id }, (err, existingUser) => {
if (err) { return done(err); }
if (existingUser) {
return done(null, existingUser);
}
User.findOne({ email: profile._json.email }, (err, existingEmailUser) => {
if (err) { return done(err); }
if (existingEmailUser) {
req.flash('errors', { msg: 'There is already an account using this email address. Sign in to that account and link it with Facebook manually from Account Settings.' });
done(err);
} else {
const user = new User();
user.email = profile._json.email;
user.facebook = profile.id;
user.tokens.push({ kind: 'facebook', accessToken });
user.profile.name = `${profile.name.givenName} ${profile.name.familyName}`;
user.profile.gender = profile._json.gender;
user.profile.picture = `https://graph.facebook.com/${profile.id}/picture?type=large`;
user.profile.location = (profile._json.location) ? profile._json.location.name : '';
user.save((err) => {
done(err, user);
});
}
});
});
}
}));
/**
* Sign in with GitHub.
*/
passport.use(new GitHubStrategy({
clientID: process.env.GITHUB_ID,
clientSecret: process.env.GITHUB_SECRET,
callbackURL: '/auth/github/callback',
passReqToCallback: true
}, (req, accessToken, refreshToken, profile, done) => {
if (req.user) {
User.findOne({ github: profile.id }, (err, existingUser) => {
if (existingUser) {
req.flash('errors', { msg: 'There is already a GitHub account that belongs to you. Sign in with that account or delete it, then link it with your current account.' });
done(err);
} else {
User.findById(req.user.id, (err, user) => {
if (err) { return done(err); }
user.github = profile.id;
user.tokens.push({ kind: 'github', accessToken });
user.profile.name = user.profile.name || profile.displayName;
user.profile.picture = user.profile.picture || profile._json.avatar_url;
user.profile.location = user.profile.location || profile._json.location;
user.profile.website = user.profile.website || profile._json.blog;
user.save((err) => {
req.flash('info', { msg: 'GitHub account has been linked.' });
done(err, user);
});
});
}
});
} else {
User.findOne({ github: profile.id }, (err, existingUser) => {
if (err) { return done(err); }
if (existingUser) {
return done(null, existingUser);
}
User.findOne({ email: profile._json.email }, (err, existingEmailUser) => {
if (err) { return done(err); }
if (existingEmailUser) {
req.flash('errors', { msg: 'There is already an account using this email address. Sign in to that account and link it with GitHub manually from Account Settings.' });
done(err);
} else {
const user = new User();
user.email = profile._json.email;
user.github = profile.id;
user.tokens.push({ kind: 'github', accessToken });
user.profile.name = profile.displayName;
user.profile.picture = profile._json.avatar_url;
user.profile.location = profile._json.location;
user.profile.website = profile._json.blog;
user.save((err) => {
done(err, user);
});
}
});
});
}
}));
// Sign in with Twitter.
passport.use(new TwitterStrategy({
consumerKey: process.env.TWITTER_KEY,
consumerSecret: process.env.TWITTER_SECRET,
callbackURL: '/auth/twitter/callback',
passReqToCallback: true
}, (req, accessToken, tokenSecret, profile, done) => {
if (req.user) {
User.findOne({ twitter: profile.id }, (err, existingUser) => {
if (err) { return done(err); }
if (existingUser) {
req.flash('errors', { msg: 'There is already a Twitter account that belongs to you. Sign in with that account or delete it, then link it with your current account.' });
done(err);
} else {
User.findById(req.user.id, (err, user) => {
if (err) { return done(err); }
user.twitter = profile.id;
user.tokens.push({ kind: 'twitter', accessToken, tokenSecret });
user.profile.name = user.profile.name || profile.displayName;
user.profile.location = user.profile.location || profile._json.location;
user.profile.picture = user.profile.picture || profile._json.profile_image_url_https;
user.save((err) => {
if (err) { return done(err); }
req.flash('info', { msg: 'Twitter account has been linked.' });
done(err, user);
});
});
}
});
} else {
User.findOne({ twitter: profile.id }, (err, existingUser) => {
if (err) { return done(err); }
if (existingUser) {
return done(null, existingUser);
}
const user = new User();
// Twitter will not provide an email address. Period.
// But a person’s twitter username is guaranteed to be unique
// so we can "fake" a twitter email address as follows:
user.email = `${profile.username}@twitter.com`;
user.twitter = profile.id;
user.tokens.push({ kind: 'twitter', accessToken, tokenSecret });
user.profile.name = profile.displayName;
user.profile.location = profile._json.location;
user.profile.picture = profile._json.profile_image_url_https;
user.save((err) => {
done(err, user);
});
});
}
}));
/**
* Sign in with Google.
*/
passport.use(new GoogleStrategy({
clientID: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_SECRET,
callbackURL: '/auth/google/callback',
passReqToCallback: true
}, (req, accessToken, refreshToken, profile, done) => {
if (req.user) {
User.findOne({ google: profile.id }, (err, existingUser) => {
if (err) { return done(err); }
if (existingUser) {
req.flash('errors', { msg: 'There is already a Google account that belongs to you. Sign in with that account or delete it, then link it with your current account.' });
done(err);
} else {
User.findById(req.user.id, (err, user) => {
if (err) { return done(err); }
user.google = profile.id;
user.tokens.push({ kind: 'google', accessToken });
user.profile.name = user.profile.name || profile.displayName;
user.profile.gender = user.profile.gender || profile._json.gender;
user.profile.picture = user.profile.picture || profile._json.image.url;
user.save((err) => {
req.flash('info', { msg: 'Google account has been linked.' });
done(err, user);
});
});
}
});
} else {
User.findOne({ google: profile.id }, (err, existingUser) => {
if (err) { return done(err); }
if (existingUser) {
return done(null, existingUser);
}
User.findOne({ email: profile.emails[0].value }, (err, existingEmailUser) => {
if (err) { return done(err); }
if (existingEmailUser) {
req.flash('errors', { msg: 'There is already an account using this email address. Sign in to that account and link it with Google manually from Account Settings.' });
done(err);
} else {
const user = new User();
user.email = profile.emails[0].value;
user.google = profile.id;
user.tokens.push({ kind: 'google', accessToken });
user.profile.name = profile.displayName;
user.profile.gender = profile._json.gender;
user.profile.picture = profile._json.image.url;
user.save((err) => {
done(err, user);
});
}
});
});
}
}));
/**
* Sign in with LinkedIn.
*/
passport.use(new LinkedInStrategy({
clientID: process.env.LINKEDIN_ID,
clientSecret: process.env.LINKEDIN_SECRET,
callbackURL: process.env.LINKEDIN_CALLBACK_URL,
scope: ['r_basicprofile', 'r_emailaddress'],
passReqToCallback: true
}, (req, accessToken, refreshToken, profile, done) => {
if (req.user) {
User.findOne({ linkedin: profile.id }, (err, existingUser) => {
if (err) { return done(err); }
if (existingUser) {
req.flash('errors', { msg: 'There is already a LinkedIn account that belongs to you. Sign in with that account or delete it, then link it with your current account.' });
done(err);
} else {
User.findById(req.user.id, (err, user) => {
if (err) { return done(err); }
user.linkedin = profile.id;
user.tokens.push({ kind: 'linkedin', accessToken });
user.profile.name = user.profile.name || profile.displayName;
user.profile.location = user.profile.location || profile._json.location.name;
user.profile.picture = user.profile.picture || profile._json.pictureUrl;
user.profile.website = user.profile.website || profile._json.publicProfileUrl;
user.save((err) => {
if (err) { return done(err); }
req.flash('info', { msg: 'LinkedIn account has been linked.' });
done(err, user);
});
});
}
});
} else {
User.findOne({ linkedin: profile.id }, (err, existingUser) => {
if (err) { return done(err); }
if (existingUser) {
return done(null, existingUser);
}
User.findOne({ email: profile._json.emailAddress }, (err, existingEmailUser) => {
if (err) { return done(err); }
if (existingEmailUser) {
req.flash('errors', { msg: 'There is already an account using this email address. Sign in to that account and link it with LinkedIn manually from Account Settings.' });
done(err);
} else {
const user = new User();
user.linkedin = profile.id;
user.tokens.push({ kind: 'linkedin', accessToken });
user.email = profile._json.emailAddress;
user.profile.name = profile.displayName;
user.profile.location = profile._json.location.name;
user.profile.picture = profile._json.pictureUrl;
user.profile.website = profile._json.publicProfileUrl;
user.save((err) => {
done(err, user);
});
}
});
});
}
}));
/**
* Tumblr API OAuth.
*/
passport.use('tumblr', new OAuthStrategy({
requestTokenURL: 'http://www.tumblr.com/oauth/request_token',
accessTokenURL: 'http://www.tumblr.com/oauth/access_token',
userAuthorizationURL: 'http://www.tumblr.com/oauth/authorize',
consumerKey: process.env.TUMBLR_KEY,
consumerSecret: process.env.TUMBLR_SECRET,
callbackURL: '/auth/tumblr/callback',
passReqToCallback: true
},
(req, token, tokenSecret, profile, done) => {
User.findById(req.user._id, (err, user) => {
if (err) { return done(err); }
user.tokens.push({ kind: 'tumblr', accessToken: token, tokenSecret });
user.save((err) => {
done(err, user);
});
});
}
));
/**
* Login Required middleware.
*/
exports.isAuthenticated = (req, res, next) => {
if (req.isAuthenticated()) {
return next();
}
res.redirect('/login');
};
/**
* Authorization Required middleware.
*/
exports.isAuthorized = (req, res, next) => {
const provider = req.path.split('/').slice(-1)[0];
if (_.find(req.user.tokens, { kind: provider })) {
next();
} else {
res.redirect(`/auth/${provider}`);
}
};
| mit |
shairozan/xsnapcourier | resources/views/snapshots/create.blade.php | 360 | @extends('layouts.master')
@section('content')
<form method="post" action="/snapshots">
<input type="hidden" name="_token" value="{{csrf_token()}}" /><br />
<label>Volume Name</lable><input type="text" name="volume_name" /><br />
<label>Snapshot Name</label><input type="text" name="snapshot_name" /><br />
<input type="submit">
</form>
@stop
| mit |
ruskofulanito/CouchInn | application/views/pages/login/reset_password.php | 1485 | <?php
echo form_open();
?>
<div class="panel panel-info">
<div class="panel-heading">
<p>Restablecer contraseña</p>
</div>
<div class="panel-body">
<div class="input-group<?php if (strlen(form_error('pass')) > 0) echo ' has-error'; ?>">
<?php
echo form_label('Contraseña', 'pass', array("class" => "input-group-addon",
"id" => "label_pass"));
echo form_password('pass', '', array("id" => "password",
"aria-describedby" => "label_pass",
"placeholder" => "Contraseña",
"class" => "form-control"));
?>
</div>
<?php echo form_error('pass'); ?>
<div class="input-group<?php if (strlen(form_error('pass_conf')) > 0) echo ' has-error'; ?>">
<?php
echo form_label('Confirmar contraseña', 'pass_conf', array("class" => "input-group-addon",
"id" => "label_pass_conf"));
echo form_password('pass_conf', '', array("id" => "passwordConf",
"aria-describedby" => "label_pass_conf",
"placeholder" => "Escriba nuevamente su contraseña",
"class" => "form-control"));
?>
</div>
<?php echo form_error('pass_conf'); ?>
</div>
<div class="panel-footer">
<?php
echo form_submit('', 'Continuar', array('class' => 'btn btn-primary'));
?>
</div>
</div>
<?php
echo form_close();
| mit |
CallmeTorre/APAIEEE | src/java/users/userNotaResponseCambio.java | 491 | package users;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class userNotaResponseCambio extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
utils.coreNotas.editarDatos(request, response);
}
}
| mit |
slackapi/node-slack-sdk | packages/web-api/src/response/FilesUploadResponse.ts | 11826 | /* eslint-disable */
/////////////////////////////////////////////////////////////////////////////////////////
// //
// !!! DO NOT EDIT THIS FILE !!! //
// //
// This file is auto-generated by scripts/generate-web-api-types.sh in the repository. //
// Please refer to the script code to learn how to update the source data. //
// //
/////////////////////////////////////////////////////////////////////////////////////////
import { WebAPICallResult } from '../WebClient';
export type FilesUploadResponse = WebAPICallResult & {
ok?: boolean;
file?: File;
error?: string;
needed?: string;
provided?: string;
};
export interface File {
id?: string;
created?: number;
timestamp?: number;
name?: string;
title?: string;
subject?: string;
mimetype?: string;
filetype?: string;
pretty_type?: string;
user?: string;
mode?: string;
editable?: boolean;
non_owner_editable?: boolean;
editor?: string;
last_editor?: string;
updated?: number;
original_attachment_count?: number;
is_external?: boolean;
external_type?: string;
external_id?: string;
external_url?: string;
username?: string;
size?: number;
url_private?: string;
url_private_download?: string;
app_id?: string;
app_name?: string;
thumb_64?: string;
thumb_64_gif?: string;
thumb_64_w?: string;
thumb_64_h?: string;
thumb_80?: string;
thumb_80_gif?: string;
thumb_80_w?: string;
thumb_80_h?: string;
thumb_160?: string;
thumb_160_gif?: string;
thumb_160_w?: string;
thumb_160_h?: string;
thumb_360?: string;
thumb_360_gif?: string;
thumb_360_w?: string;
thumb_360_h?: string;
thumb_480?: string;
thumb_480_gif?: string;
thumb_480_w?: string;
thumb_480_h?: string;
thumb_720?: string;
thumb_720_gif?: string;
thumb_720_w?: string;
thumb_720_h?: string;
thumb_800?: string;
thumb_800_gif?: string;
thumb_800_w?: string;
thumb_800_h?: string;
thumb_960?: string;
thumb_960_gif?: string;
thumb_960_w?: string;
thumb_960_h?: string;
thumb_1024?: string;
thumb_1024_gif?: string;
thumb_1024_w?: string;
thumb_1024_h?: string;
thumb_video?: string;
thumb_gif?: string;
thumb_pdf?: string;
thumb_pdf_w?: string;
thumb_pdf_h?: string;
thumb_tiny?: string;
converted_pdf?: string;
image_exif_rotation?: number;
original_w?: string;
original_h?: string;
deanimate?: string;
deanimate_gif?: string;
pjpeg?: string;
permalink?: string;
permalink_public?: string;
edit_link?: string;
has_rich_preview?: boolean;
media_display_type?: string;
preview_is_truncated?: boolean;
preview?: string;
preview_highlight?: string;
plain_text?: string;
preview_plain_text?: string;
has_more?: boolean;
sent_to_self?: boolean;
lines?: number;
lines_more?: number;
is_public?: boolean;
public_url_shared?: boolean;
display_as_bot?: boolean;
channels?: string[];
groups?: string[];
ims?: string[];
shares?: Shares;
to?: Cc[];
from?: Cc[];
cc?: Cc[];
channel_actions_ts?: string;
channel_actions_count?: number;
headers?: Headers;
simplified_html?: string;
bot_id?: string;
initial_comment?: InitialComment;
num_stars?: number;
is_starred?: boolean;
pinned_to?: string[];
reactions?: Reaction[];
comments_count?: number;
attachments?: Attachment[];
blocks?: Block[];
}
export interface Attachment {
msg_subtype?: string;
fallback?: string;
callback_id?: string;
color?: string;
pretext?: string;
service_url?: string;
service_name?: string;
service_icon?: string;
author_id?: string;
author_name?: string;
author_link?: string;
author_icon?: string;
from_url?: string;
original_url?: string;
author_subname?: string;
channel_id?: string;
channel_name?: string;
id?: number;
bot_id?: string;
indent?: boolean;
is_msg_unfurl?: boolean;
is_reply_unfurl?: boolean;
is_thread_root_unfurl?: boolean;
is_app_unfurl?: boolean;
app_unfurl_url?: string;
title?: string;
title_link?: string;
text?: string;
fields?: Field[];
image_url?: string;
image_width?: number;
image_height?: number;
image_bytes?: number;
thumb_url?: string;
thumb_width?: number;
thumb_height?: number;
video_url?: string;
video_html?: string;
video_html_width?: number;
video_html_height?: number;
footer?: string;
footer_icon?: string;
ts?: string;
mrkdwn_in?: string[];
actions?: Action[];
blocks?: any[];
files?: any[];
filename?: string;
size?: number;
mimetype?: string;
url?: string;
metadata?: Metadata;
}
export interface Action {
id?: string;
name?: string;
text?: string;
style?: string;
type?: string;
value?: string;
confirm?: ActionConfirm;
options?: SelectedOptionElement[];
selected_options?: SelectedOptionElement[];
data_source?: string;
min_query_length?: number;
option_groups?: ActionOptionGroup[];
url?: string;
}
export interface ActionConfirm {
title?: string;
text?: string;
ok_text?: string;
dismiss_text?: string;
}
export interface ActionOptionGroup {
text?: string;
options?: SelectedOptionElement[];
}
export interface SelectedOptionElement {
text?: string;
value?: string;
}
export interface Field {
title?: string;
value?: string;
short?: boolean;
}
export interface Metadata {
thumb_64?: boolean;
thumb_80?: boolean;
thumb_160?: boolean;
original_w?: number;
original_h?: number;
thumb_360_w?: number;
thumb_360_h?: number;
format?: string;
extension?: string;
rotation?: number;
thumb_tiny?: string;
}
export interface Block {
type?: string;
elements?: Accessory[];
block_id?: string;
fallback?: string;
image_url?: string;
image_width?: number;
image_height?: number;
image_bytes?: number;
alt_text?: string;
title?: Text;
text?: Text;
fields?: Text[];
accessory?: Accessory;
}
export interface Accessory {
type?: string;
image_url?: string;
alt_text?: string;
fallback?: string;
image_width?: number;
image_height?: number;
image_bytes?: number;
text?: Text;
action_id?: string;
url?: string;
value?: string;
style?: string;
confirm?: AccessoryConfirm;
accessibility_label?: string;
options?: InitialOptionElement[];
initial_options?: InitialOptionElement[];
focus_on_load?: boolean;
initial_option?: InitialOptionElement;
placeholder?: Text;
initial_channel?: string;
response_url_enabled?: boolean;
initial_channels?: string[];
max_selected_items?: number;
initial_conversation?: string;
default_to_current_conversation?: boolean;
filter?: Filter;
initial_conversations?: string[];
initial_date?: string;
initial_time?: string;
min_query_length?: number;
option_groups?: AccessoryOptionGroup[];
initial_user?: string;
initial_users?: string[];
}
export interface AccessoryConfirm {
title?: Text;
text?: Text;
confirm?: Text;
deny?: Text;
style?: string;
}
export interface Text {
type?: Type;
text?: string;
emoji?: boolean;
verbatim?: boolean;
}
export enum Type {
Mrkdwn = 'mrkdwn',
PlainText = 'plain_text',
}
export interface Filter {
include?: any[];
exclude_external_shared_channels?: boolean;
exclude_bot_users?: boolean;
}
export interface InitialOptionElement {
text?: Text;
value?: string;
description?: Text;
url?: string;
}
export interface AccessoryOptionGroup {
label?: Text;
options?: InitialOptionElement[];
}
export interface Cc {
address?: string;
name?: string;
original?: string;
}
export interface Headers {
date?: string;
in_reply_to?: string;
reply_to?: string;
message_id?: string;
}
export interface InitialComment {
id?: string;
created?: number;
timestamp?: number;
user?: string;
comment?: string;
channel?: string;
is_intro?: boolean;
}
export interface Reaction {
name?: string;
count?: number;
users?: string[];
url?: string;
}
export interface Shares {
public?: { [key: string]: Private[] };
private?: { [key: string]: Private[] };
}
export interface Private {
share_user_id?: string;
reply_users?: string[];
reply_users_count?: number;
reply_count?: number;
ts?: string;
thread_ts?: string;
latest_reply?: string;
channel_name?: string;
team_id?: string;
}
| mit |
chen-android/guoliao | seal/src/main/java/com/GuoGuo/JuicyChat/server/network/download/DownLoadCallback.java | 2757 | /*
ShengDao Android Client, DownLoadCallback
Copyright (c) 2014 ShengDao Tech Company Limited
*/
package com.GuoGuo.JuicyChat.server.network.download;
import android.os.Handler;
import android.os.Message;
public class DownLoadCallback extends Handler {
protected static final int START_MESSAGE = 0;
protected static final int ADD_MESSAGE = 1;
protected static final int PROGRESS_MESSAGE = 2;
protected static final int SUCCESS_MESSAGE = 3;
protected static final int FAILURE_MESSAGE = 4;
protected static final int FINISH_MESSAGE = 5;
protected static final int STOP_MESSAGE = 6;
public void onStart() {
}
public void onAdd(String url, Boolean isInterrupt) {
}
public void onLoading(String url, int bytesWritten, int totalSize) {
}
public void onSuccess(String url, String filePath) {
}
public void onFailure(String url, String strMsg) {
}
public void onFinish(String url) {
}
public void onStop() {
}
@Override
public void handleMessage(Message msg) {
Object[] response = null;
switch (msg.what) {
case START_MESSAGE:
onStart();
break;
case ADD_MESSAGE:
response = (Object[]) msg.obj;
onAdd((String) response[0], (Boolean) response[1]);
break;
case PROGRESS_MESSAGE:
response = (Object[]) msg.obj;
onLoading((String) response[0], (Integer) response[1], (Integer) response[2]);
break;
case SUCCESS_MESSAGE:
response = (Object[]) msg.obj;
onSuccess((String) response[0], (String) response[1]);
break;
case FAILURE_MESSAGE:
response = (Object[]) msg.obj;
onFailure((String) response[0], (String) response[1]);
break;
case FINISH_MESSAGE:
response = (Object[]) msg.obj;
onFinish((String) response[0]);
break;
case STOP_MESSAGE:
onStop();
break;
}
}
protected void sendSuccessMessage(String url, String path) {
sendMessage(obtainMessage(SUCCESS_MESSAGE, new Object[]{url, path}));
}
protected void sendLoadMessage(String url, int bytesWritten, int totalSize) {
sendMessage(obtainMessage(PROGRESS_MESSAGE, new Object[]{url, bytesWritten, totalSize}));
}
protected void sendAddMessage(String url, Boolean isInterrupt) {
sendMessage(obtainMessage(ADD_MESSAGE, new Object[]{url, isInterrupt}));
}
protected void sendFailureMessage(String url, String strMsg) {
sendMessage(obtainMessage(FAILURE_MESSAGE, new Object[]{url, strMsg}));
}
protected void sendStartMessage() {
sendMessage(obtainMessage(START_MESSAGE, null));
}
protected void sendStopMessage() {
sendMessage(obtainMessage(STOP_MESSAGE, null));
}
protected void sendFinishMessage(String url) {
sendMessage(obtainMessage(FINISH_MESSAGE, new Object[]{url}));
}
}
| mit |
mlfie/mjparse | test/fixtures/orig/105mon.php | 6302 | <html lang="ja">
<head>
<meta http-equiv="content-type" content="text/html; charset=shift_jis">
<meta name="keywords" content="麻雀,役,ルール,点数,点数計算,初心者">
<meta http-equiv="Cache-Control" content="no-cache">
<link href="http://dora12.org/favicon.ico" rel="SHORTCUT ICON">
<title>役と点数当て問題【生きた麻雀講座】</title>
</head>
<body>
<div align="center">
<a href="http://smaf.jp/150964292c165736?guid=ON"><img src="http://img01.smaf.jp/b/339/12531339/m/165736.gif?m=526278" width="192" height="53" border="0"></a>
</div>
<font size="2">
<font color ="#ff9900">▼役と点数当て問題</font>
</font>
<hr color="#009900">
<p>
<a name="toi">【問題】</a><br>
</p>
<p>
<font size="2">
[東場][西家]<br>
</font>
<img src="../../image/s4.gif" border="0" alt="4索"><img src="../../image/s5.gif" border="0" alt="5索"><img src="../../image/s6.gif" border="0" alt="6索"><img src="../../image/p8.gif" border="0" alt="8筒"><img src="../../image/p9.gif" border="0" alt="9筒"><img src="../../image/p9.gif" border="0" alt="9筒"><img src="../../image/p9.gif" border="0" alt="9筒"> <img src="../../image/gpei.gif" border="0" alt="北"><img src="../../image/gpeiy.gif" border="0" alt="北"><img src="../../image/gpei.gif" border="0" alt="北"><img src="../../image/gpei.gif" border="0" alt="北"><img src="../../image/ura.gif" border="0" alt="裏"><img src="../../image/gton.gif" border="0" alt="東"><img src="../../image/gton.gif" border="0" alt="東"><img src="../../image/ura.gif" border="0" alt="裏"><br>
ツモ:<img src="../../image/p7.gif" border="0" alt="7筒"><br>
ドラ:<img src="../../image/s2.gif" border="0" alt="2索"><br>
</p>
<div align="center">
【<a href="#kotae">答え</a>】<br>
</div>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<p>
【<a name="kotae">答え</a>】
</p>
<p>
<font size="2">[役]</font><br>
<a href="../../1/yaku/fanpai.php">荘風牌</a>(場風)<br>
</p>
<p>
<font size="2">[符点・飜数]</font><br>
<font color ="#000099">80符1飜</font><br>
</p>
<p>
<font size="2">[点数]</font><br>
<font color ="#000099">700-1300(2700点)</font><br>
</p>
<p>
<font size="2">
[<a href="#toi">↑問題を見直す</a>]<br>
</font>
</p>
<p>
<font size="2">
▼出題メニュー<br>
[1]<a href="38mon.php" accesskey="1">満貫以下/40符以下/親子</a><br>
[2]<a href="20mon.php" accesskey="2">満貫以下/40符以下/子</a><br>
[3]<a href="38mon.php" accesskey="3">満貫以下/40符以下/親</a><br>
[4]<a href="98mon.php" accesskey="4">満貫以下/50符以上/親子</a><br>
[5]<a href="78mon.php" accesskey="5">満貫以下/50符以上/子</a><br>
[6]<a href="147mon.php" accesskey="6">満貫以下/50符以上/親</a><br>
[7]<a href="198mon.php" accesskey="7">跳満以上/親子</a><br>
[8]<a href="160mon.php" accesskey="8">全部ランダム</a><br>
</font>
</p>
<hr color="#009900">
<font size="2">
[0]<a href="../../" accesskey="0">生きた麻雀講座TOP</a><br>
[#]<a href="./" accesskey="#">役と点数当て問題TOP</a><br>
</font>
<hr color="#009900">
<div align="center">
<form action="http://m.mixi.jp/share.pl?guid=ON" method="POST" >
<input type="hidden" name="charset" value="shift_jis" />
<input type="hidden" name="check_key" value="8a22a9e3ecb4026cb50904eb55ffbdbfb083eabe" />
<input type="hidden" name="title" value="生きた麻雀講座" />
<input type="hidden" name="primary_url" value="http://dora12.com/2/yakuten/105mon.php" />
<input type="hidden" name="mobile_url" value="http://dora12.com/2/yakuten/105mon.php" />
<input type="hidden" name="pc_url" value="http://dora12.com/2/yakuten/105mon.php" />
<input type="submit" value="mixiチェック" />
</form>
</div>
<p>
<font size="2">
<font color="#ff0000">▼メルマガ始めました</font><br>
麻雀講座や雑学、雀荘マナーやプロ試験過去問をお送りします。<br>
<a href="mailto:autoform@dora12.info?subject=メルマガ購読&body=dora12.infoからのメールを受信できるようにしておいて下さい。追って登録用のURLを送ります。">ここにメール</a>を送るだけで購読できます。<br>
セット内容など詳しい事は<a href="http://dora12.net/modules/pico/maga/info.html">こちら</a>をご覧下さい。<br>
</font>
</p>
<p>
<font size="2">
<font color="#000099">▼お勧めサイト</font><br>
携帯で麻雀関係のサイトを利用するなら下のサイトがお勧めです。<br>
</font>
</p>
<font size="2">
●<a href="http://smaf.jp/127008461c52850?guid=ON">雀ナビ</a><br>
携帯ネット雀荘です。<br>
対人戦がしたい方はここ。<br>
麻雀仲間も作れます。<br>
<br>
●<a href="http://smaf.jp/108460984c94272?guid=ON">3D麻雀 激牌</a><br>
対人戦は怖い人や初心者向け。<br>
<br>
●<a href="http://smaf.jp/150964292c95579?guid=ON">麻雀攻略ナビ</a><br>
戦術から何切る問題、収支管理や点数計算のツールが充実してます。<br>
<br>
<a href="http://smaf.jp/127008461c52850?guid=ON">雀ナビ</a>か<a href="http://smaf.jp/108460984c94272?guid=ON">激牌</a>で実戦を積み、<a href="http://smaf.jp/150964292c95579?guid=ON">麻雀攻略ナビ</a>で勉強するのが良いと思います。<br>
</font>
<hr>
<div align="center">
(c)生きた麻雀講座
</div>
<!--ugo2-->
<div align="right">
<a href="http://ugo2.jp/m/"><img src="http://b10.ugo2.jp/?u=5039289&h=6c2f25&ut=1&guid=ON&qM=|Az|80|dora12.com|%2F2%2Fyakuten%2F105mon.php|H|&ch=UTF-8&sb=%5Bpage+title%5D" alt="携帯アクセス解析" width="72" height="16" border="0" /></a></div>
<!--ugo2-->
<!-- shinobi ct2
<div align="right">
<font size="1">
<script type="text/javascript" src="http://ct2.ohuda.com/sc/1479137"></script>
<noscript><a href="http://ct2.ohuda.com/gg/1479137" target="_blank">
<img src="http://ct2.ohuda.com/ll/1479137" border="0" alt="カウンター" /></a><br />
<span id="NINCT1SPAN1479137" style="font-size:9px">[PR] <a href="http://reflexology.rental-rental.net" target="_blank">リフレクソロジー</a></span></noscript>
</font>
</div>
-->
</body>
</html>
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.