repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
frainfreeze/studying | university/10004-Programming/labs/v5/zadatak3.cpp | 952 | #include <iostream>
#include <vector>
using namespace std;
/*
Zadatak 3. Napisite program koji od korisnika trazi da unese broj
veci od 100 (ako je broj manji od 100 ponavlja se upit).
Nakon unosa iz raspona (1 broj) upisite sve parne brojeve u polje.
Ispisite elemente polja odvojene zarezom. Nakon zadnjeg elementa stavite tocku
*/
int main() {
int broj;
vector<int> brojevi;
do {
cout << "Unesite broj veci od 100: ";
cin >> broj;
if (broj < 100) {
cout << "Broj je manji od 100!" << endl;
}
else if (broj > 100) {
//prodi kroz brojeve, nadi parne, dodaj ih u vektor
for (int i = 1; i <= broj; i++)
{
if (i % 2 == 0) {
brojevi.push_back(i);
}
}
//ispis vektora
for (int i = 0; i < size(brojevi); i++)
{
if (i == size(brojevi)-1){
cout << brojevi[i] << ".";
}
else {
cout << brojevi[i] << ", ";
}
}
break;
}
} while (true);
cout << endl;
return 0;
} | mit |
FreakingGoodSoftware/TempSensor_XamarinForms | TempSensor.Xamarin/TempSensor.Xamarin/TempSensor.Xamarin.Droid/MainActivity.cs | 765 | using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
namespace TempSensor.Xamarin.Droid
{
[Activity (Label = "TempSensor.Xamarin.Droid", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
int count = 1;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
// Get our button from the layout resource,
// and attach an event to it
Button button = FindViewById<Button> (Resource.Id.myButton);
button.Click += delegate {
button.Text = string.Format ("{0} clicks!", count++);
};
}
}
}
| mit |
raphealolams/ihub | application/third_party/Smarty/compiled/edc3b292b37dbb775e182b81e0a55f3134f229d2_0.file.header.tpl.php | 4117 | <?php /* Smarty version 3.1.27, created on 2017-02-01 14:05:27
compiled from "C:\xampp\htdocs\crystal_school_app\application\views\layouts\partials\header.tpl" */ ?>
<?php
/*%%SmartyHeaderCode:318035891dd173b67f1_98238491%%*/
if(!defined('SMARTY_DIR')) exit('no direct access allowed');
$_valid = $_smarty_tpl->decodeProperties(array (
'file_dependency' =>
array (
'edc3b292b37dbb775e182b81e0a55f3134f229d2' =>
array (
0 => 'C:\\xampp\\htdocs\\crystal_school_app\\application\\views\\layouts\\partials\\header.tpl',
1 => 1485954323,
2 => 'file',
),
),
'nocache_hash' => '318035891dd173b67f1_98238491',
'has_nocache_code' => false,
'version' => '3.1.27',
'unifunc' => 'content_5891dd17418030_90646304',
),false);
/*/%%SmartyHeaderCode%%*/
if ($_valid && !is_callable('content_5891dd17418030_90646304')) {
function content_5891dd17418030_90646304 ($_smarty_tpl) {
$_smarty_tpl->properties['nocache_hash'] = '318035891dd173b67f1_98238491';
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<!--IE Compatibility modes-->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!--Mobile first-->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Metis</title>
<meta name="description" content="Free Admin Template Based On Twitter Bootstrap 3.x">
<meta name="author" content="">
<meta name="msapplication-TileColor" content="#5bc0de" />
<meta name="msapplication-TileImage" content="<?php echo base_url("assets/dashboard/img/metis-tile.png");?>
" />
<!-- Bootstrap -->
<link rel="stylesheet" href="<?php echo base_url("assets/dashboard/lib/bootstrap/css/bootstrap.css");?>
">
<!-- Font Awesome -->
<link rel="stylesheet" href="<?php echo base_url("assets/dashboard/assets/font-awesome/css/font-awesome.css");?>
">
<!-- Metis core stylesheet -->
<link rel="stylesheet" href="<?php echo base_url("assets/dashboard/css/main.css");?>
">
<!-- metisMenu stylesheet -->
<link rel="stylesheet" href="<?php echo base_url("assets/dashboard/lib/metismenu/metisMenu.css");?>
">
<!-- animate.css")} stylesheet -->
<link rel="stylesheet" href="<?php echo base_url("assets/dashboard/lib/animate.css/animate.css");?>
">
<!-- HTML5 shim and Respond.js")} for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js")} doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<?php echo '<script'; ?>
src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"><?php echo '</script'; ?>
>
<?php echo '<script'; ?>
src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"><?php echo '</script'; ?>
>
<![endif]-->
<!--For Development Only. Not required -->
<?php echo '<script'; ?>
>
less = {
env: "development",
relativeUrls: false,
rootpath: "<?php echo base_url("assets/dashboard/");?>
"
};
<?php echo '</script'; ?>
>
<link rel="stylesheet" href="<?php echo base_url("assets/dashboard/css/style-switcher.css");?>
">
<link rel="stylesheet/less" type="text/css" href="<?php echo base_url("assets/dashboard/less/theme.less");?>
">
<link href="<?php echo base_url("assets/datatables/css/jquery.dataTables.min.css");?>
" rel="stylesheet" type="text/css"/>
<?php echo '<script'; ?>
src="https://cdnjs.cloudflare.com/ajax/libs/less.js/2.7.1/less.js"><?php echo '</script'; ?>
>
<!--jQuery -->
<?php echo '<script'; ?>
src="<?php echo base_url("assets/dashboard/lib/jquery/jquery.js");?>
"><?php echo '</script'; ?>
>
<?php echo '<script'; ?>
src="<?php echo base_url("assets/datatables/js/jquery.dataTables.min.js");?>
" type="text/javascript"><?php echo '</script'; ?>
>
<style>
.tab-content{
padding: 20px 10px;
}
#formModal .modal-body{
height: 450px;
}
</style>
<?php }
}
?> | mit |
blahami2/MI-PAA-Knapsack-evaluator | src/cz/blahami2/mipaa/knapsack/model/algorithm/DynamicPriceFPTAS.java | 4781 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package cz.blahami2.mipaa.knapsack.model.algorithm;
import java.util.Map;
import cz.blahami2.mipaa.knapsack.model.Knapsack;
import cz.blahami2.mipaa.knapsack.model.KnapsackItem;
import cz.blahami2.mipaa.knapsack.model.KnapsackConfig;
import cz.blahami2.mipaa.knapsack.utils.Formula;
/**
*
* @author MBlaha
*/
public class DynamicPriceFPTAS extends Algorithm {
private KnapsackConfig[] table;
private Knapsack knapsack;
private final double errorKoef;
// private int error; // TODO fix
private Map<Integer, Integer> errors;
public DynamicPriceFPTAS(int warmupCycles, int runCycles, double errorKoef) {
super(warmupCycles, runCycles);
this.errorKoef = errorKoef;
}
public void setErrors(Map<Integer, Integer> errors) {
this.errors = errors;
}
@Override
public KnapsackConfig solve(Knapsack knapsack, Object data) {
// System.out.println( "formula = log2 ( (" + errorKoef + " * " + knapsack.getMaxPrice() + ") / " + knapsack.getItemCount() + ")" );
int error = Formula.fptasBits(errorKoef, knapsack.getMaxPrice(), knapsack.getItemCount());
int maxPrice = knapsack.getPriceSum() >> error;
// ERROR = 0;
// ERROR = errors.get( knapsack.getId() );
// ERROR = Formula.fptasBits( errorKoef, knapsack.getMaxPrice(), knapsack.getItemCount());
// System.out.println( "ERROR = " + error );
// System.out.println( "Max price before = " + maxPrice );
// System.out.println( "Max price after = " + maxPrice );
this.table = new KnapsackConfig[maxPrice + 1];
Knapsack alteredKnapsack = new Knapsack(knapsack.getId(), knapsack.getItemCount(), knapsack.getMaxWeight());
for (int i = 0; i < knapsack.getItemCount(); i++) {
KnapsackItem item = knapsack.getItem(i);
alteredKnapsack.addItem(new KnapsackItem(item.getId(), item.getWeight(), item.getPrice() >> error));
}
KnapsackConfig cfg = new KnapsackConfig(alteredKnapsack);
cfg.setFromLongInteger(0);
table[0] = cfg;
for (int i = 0; i < alteredKnapsack.getItemCount(); i++) {
for (int j = maxPrice; j >= 0; j--) {
if (table[j] != null) {
// System.out.println( j + " != null" );
KnapsackItem item = alteredKnapsack.getItem(i);
// if(item.getPrice() == 0){
// System.out.println( "item[" + i + "] = 0" );
// }
int price = table[j].getPrice() + item.getPrice();
cfg = new KnapsackConfig(table[j]);
cfg.set(i, true);
if ((table[price] == null)
|| (table[price].getWeight() > cfg.getWeight())
|| (table[price].getWeight() == cfg.getWeight() && table[price].getSelectedItemCount() < cfg.getSelectedItemCount())
) {
table[price] = cfg;
}
}
}
}
// printTable();
for (int i = maxPrice; i >= 0; i--) {
if (table[i] != null && table[i].getWeight() <= alteredKnapsack.getMaxWeight()) {
// quickfix for zero price items, which fit weight
// System.out.println( "weight = " + table[i].getWeight() + " out of " + knapsack.getCapacity() );
for (int j = 0; j < alteredKnapsack.getItemCount(); j++) {
KnapsackItem item = alteredKnapsack.getItem(j);
// System.out.println( "item[" + j + "]: p = " + item.getPrice() + ", w = " + item.getWeight() );
if (!table[i].get(j) && table[i].getWeight() + item.getWeight() <= alteredKnapsack.getMaxWeight()) {
// System.out.println( "adding above" );
table[i].set(j, true);
}
}
return new KnapsackConfig(knapsack).setConfigFrom(table[i]);
}
}
throw new AssertionError("this should never get here");
}
private void printTable() {
int maxPrice = 0;
for (int i = 0; i < knapsack.getItemCount(); i++) {
maxPrice += knapsack.getItem(i).getPrice();
}
for (int i = 0; i <= maxPrice; i++) {
if (table[i] == null) {
System.out.println("(null)");
} else {
System.out.println("(" + table[i].getPrice() + ", " + table[i].getWeight() + ")");
}
}
}
}
| mit |
ArtOfCode-/qpixel | db/migrate/20191109211244_change_site_settings_value_type.rb | 136 | class ChangeSiteSettingsValueType < ActiveRecord::Migration[5.0]
def change
change_column :site_settings, :value, :text
end
end
| mit |
thuongho/dream-machine | app/users/users.component.js | 2026 | "use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require('@angular/core');
var http_1 = require('@angular/http');
var router_deprecated_1 = require('@angular/router-deprecated');
// import { User } from './user';
var user_service_1 = require('../services/user.service');
var UsersComponent = (function () {
function UsersComponent(_userService) {
this._userService = _userService;
}
UsersComponent.prototype.ngOnInit = function () {
var _this = this;
this._userService.getUsers()
.subscribe(function (users) {
// console.log(users);
_this.users = users;
});
// this._userService.getUsers()
// .then(users => this.users = users)
// .catch(error => this.error = error);
};
UsersComponent = __decorate([
core_1.Component({
selector: 'users',
templateUrl: '/app/users/users.component.html',
directives: [router_deprecated_1.ROUTER_DIRECTIVES],
providers: [http_1.HTTP_PROVIDERS, user_service_1.UserService]
}),
__metadata('design:paramtypes', [user_service_1.UserService])
], UsersComponent);
return UsersComponent;
}());
exports.UsersComponent = UsersComponent;
//# sourceMappingURL=users.component.js.map | mit |
lbdlbd/kof_game_server | game-server/app/domain/map/map.js | 16163 | //var buildFinder = require('pomelo-pathfinding').buildFinder;
//var geometry = require('../../util/geometry');
//var PathCache = require('../../util/pathCache');
var utils = require('../../util/utils');
var logger = require('pomelo-logger').getLogger(__filename);
var formula = require('../../consts/formula');
var fs = require('fs');
/**
* The data structure for map in the area
*/
var Map = function(opts) {
this.mapPath = process.cwd() + opts.path;
this.map = null;
this.weightMap = null;
this.name = opts.name;
this.init(opts);
};
var pro = Map.prototype;
/**
* Init game map
* @param {Object} opts
* @api private
*/
Map.prototype.init = function(opts) {
var weightMap = opts.weightMap || false;
var map = require(this.mapPath);
if(!map) {
logger.error('Load map failed! ');
} else {
this.configMap(map);
this.id = opts.id;
this.width = opts.width;
this.height = opts.height;
this.tileW = 20;
this.tileH = 20;
this.rectW = Math.ceil(this.width/this.tileW);
this.rectH = Math.ceil(this.height/this.tileH);
this.ground = this.map.ground;
/*this.pathCache = new PathCache({limit:1000});
this.pfinder = buildFinder(this);
if(weightMap) {
//Use cache map first
var path = process.cwd() + '/tmp/map.json';
var maps = fs.existsSync(path)?require(path) : {};
if(!!maps[this.id]){
this.collisions = maps[this.id].collisions;
this.weightMap = this.getWeightMap(this.collisions);
}else{
this.initWeightMap();
this.initCollisons();
maps[this.id] = {version : Date.now(), collisions : this.collisions};
fs.writeFileSync(path, JSON.stringify(maps));
}
}*/
}
};
Map.prototype.configMap = function(map){
this.map = {};
var layers = map.layers;
for(var i = 0; i < layers.length; i++){
var layer = layers[i];
if(layer.type === 'objectgroup'){
this.map[layer.name] = configObjectGroup(layer.objects);
}
}
};
function configProps(obj){
if(!!obj && !!obj.properties){
for(var key in obj.properties){
obj[key] = obj.properties[key];
}
delete obj.properties;
}
return obj;
}
function configObjectGroup(objs){
for(var i = 0; i < objs.length; i++){
objs[i] = configProps(objs[i]);
}
return objs;
}
/**
* Init weight map, which is used to record the collisions info, used for pathfinding
* @api private
*/
Map.prototype.initWeightMap = function() {
var collisions = this.getCollision();
var i, j, x, y, x1, y1, x2, y2, p, l, p1, p2, p3, p4;
this.weightMap = [];
for(i = 0; i < this.rectW; i++) {
this.weightMap[i] = [];
for(j = 0; j < this.rectH; j++) {
this.weightMap[i][j] = 1;
}
}
//Use all collsions to construct the weight map
for(i = 0; i < collisions.length; i++) {
var collision = collisions[i];
var polygon = [];
var points = collision.polygon;
if(!!points && points.length > 0) {
if(points.length < 3) {
logger.warn('The polygon data is invalid! points: %j', points);
continue;
}
//Get the rect limit for polygonal collision
var minx = Infinity, miny = Infinity, maxx = 0, maxy = 0;
for(j = 0; j < points.length; j++) {
var point = points[j];
x = Number(point.x) + Number(collision.x);
y = Number(point.y) + Number(collision.y);
minx = minx>x?x:minx;
miny = miny>y?y:miny;
maxx = maxx<x?x:maxx;
maxy = maxy<y?y:maxy;
polygon.push({x: x, y: y});
}
//A polygon need at least 3 points
if(polygon.length < 3) {
logger.error('illigle polygon: points : %j, polygon: %j', points, polygon);
continue;
}
x1 = Math.floor(minx/this.tileW);
y1 = Math.floor(miny/this.tileH);
x2 = Math.ceil(maxx/this.tileW);
y2 = Math.ceil(maxy/this.tileH);
//regular the poinit to not exceed the map
x1 = x1<0?0:x1;
y1 = y1<0?0:y1;
x2 = x2>this.rectW?this.rectW:x2;
y2 = y2>this.rectH?this.rectH:y2;
//For all the tile in the polygon's externally rect, check if the tile is in the collision
for(x = x1; x < x2; x++) {
for(y = y1; y < y2; y++) {
p = {x: x*this.tileW + this.tileW/2, y : y*this.tileH + this.tileH/2};
l = this.tileW/4;
p1 = { x: p.x - l, y: p.y - l};
p2 = { x: p.x + l, y: p.y - l};
p3 = { x: p.x - l, y: p.y + l};
p4 = { x: p.x + l, y: p.y + l};
if(geometry.isInPolygon(p1, polygon) ||
geometry.isInPolygon(p2, polygon) ||
geometry.isInPolygon(p3, polygon) ||
geometry.isInPolygon(p4, polygon)) {
this.weightMap[x][y] = Infinity;
}
}
}
} else {
x1 = Math.floor(collision.x/this.tileW);
y1 = Math.floor(collision.y/this.tileH);
x2 = Math.ceil((collision.x+collision.width)/this.tileW);
y2 = Math.ceil((collision.y+collision.height)/this.tileH);
//regular the poinit to not exceed the map
x1 = x1<0?0:x1;
y1 = y1<0?0:y1;
x2 = x2>this.rectW?this.rectW:x2;
y2 = y2>this.rectH?this.rectH:y2;
for(x = x1; x < x2; x++) {
for(y = y1; y < y2; y++) {
this.weightMap[x][y] = Infinity;
}
}
}
}
};
Map.prototype.initCollisons = function(){
var map = [];
var flag = false;
var collision;
for(var x = 0; x < this.weightMap.length; x++){
var array = this.weightMap[x];
var length = array.length;
var collisions = [];
for(var y = 0; y < length; y++){
//conllisions start
if(!flag && (array[y] === Infinity)){
collision = {};
collision.start = y;
flag = true;
}
if(flag && array[y] === 1){
flag = false;
collision.length = y - collision.start;
collisions.push(collision);
}else if(flag && (y === length - 1)){
flag = false;
collision.length = y - collision.start + 1;
collisions.push(collision);
}
}
map[x] = {collisions: collisions};
}
this.collisions = map;
};
Map.prototype.getWeightMap = function(collisions){
var map = [];
var x, y;
for(x = 0; x < this.rectW; x++) {
var row = [];
for(y = 0; y < this.rectH; y++) {
row.push(1);
}
map.push(row);
}
for(x = 0; x < collisions.length; x++){
var array = collisions[x].collisions;
if(!array){
continue;
}
for(var j = 0; j < array.length; j++){
var c = array[j];
for(var k = 0; k < c.length; k++){
map[x][c.start+k] = Infinity;
}
}
}
return map;
};
/**
* Get all mob zones in the map
* @return {Array} All mobzones in the map
* @api public
*/
Map.prototype.getMobZones = function() {
if(!this.map) {
logger.error('map not load');
return null;
}
return this.map.mob;
};
/**
* Get all npcs from map
* @return {Array} All npcs in the map
* @api public
*/
Map.prototype.getNPCs = function() {
return this.map.npc;
};
/**
* Get all collisions form the map
* @return {Array} All collisions
* @api public
*/
Map.prototype.getCollision = function() {
return this.map.collision;
};
/**
* Get born place for this map
* @return {Object} Born place for this map
* @api public
*/
// temporary code
Map.prototype.getBornPlace = function() {
var bornPlace = this.map.birth[0];
if(!bornPlace) {
bornPlace = this.map.transPoint;
}
if(!bornPlace) {
return null;
}
return bornPlace;
};
/*
Map.prototype.getBornPlace = function() {
var bornPlaces = this.getMobZones();
var randomV = Math.floor(Math.random() * bornPlaces.length);
var bornPlace = bornPlaces[randomV];
if(!bornPlace) {
return null;
}
return bornPlace;
};
*/
// temporary code
/**
* Get born point for this map, the point is random generate in born place
* @return {Object} A random generated born point for this map.
* @api public
*/
Map.prototype.getBornPoint = function() {
var bornPlace = this.getBornPlace();
var pos = {
x : bornPlace.x + Math.floor(Math.random()*bornPlace.width),
y : bornPlace.y + Math.floor(Math.random()*bornPlace.height)
};
return pos;
};
/**
* Random generate a position for give pos and range
* @param pos {Object} The center position
* @param range {Number} The max distance form the pos
* @return {Object} A random generate postion in the range of given pos
* @api public
*/
Map.prototype.genPos = function(pos, range) {
var result = {};
var limit = 10;
for(var i = 0; i < limit; i++) {
var x = pos.x + Math.random()*range - range/2;
var y = pos.y + Math.random()*range - range/2;
if(this.isReachable(x, y)) {
result.x = x;
result.y = y;
return result;
}
}
return null;
};
/**
* Get all reachable pos for given x and y
* This interface is used for pathfinding
* @param x {Number} x position.
* @param y {Number} y position.
* @param processReachable {function} Call back function, for all reachable x and y, the function will bu called and use the position as param
* @api public
*/
Map.prototype.forAllReachable = function(x, y, processReachable) {
var x1 = x - 1, x2 = x + 1;
var y1 = y - 1, y2 = y + 1;
x1 = x1<0?0:x1;
y1 = y1<0?0:y1;
x2 = x2>=this.rectW?(this.rectW-1):x2;
y2 = y2>=this.rectH?(this.rectH-1):y2;
if(y > 0) {
processReachable(x, y - 1, this.weightMap[x][y - 1]);
}
if((y + 1) < this.rectH) {
processReachable(x, y + 1, this.weightMap[x][y + 1]);
}
if(x > 0) {
processReachable(x - 1, y, this.weightMap[x - 1][y]);
}
if((x + 1) < this.rectW) {
processReachable(x + 1, y, this.weightMap[x + 1][y]);
}
};
/**
* Get weicht for given pos
*/
Map.prototype.getWeight = function(x, y) {
return this.weightMap[x][y];
};
/**
* Return is reachable for given pos
*/
Map.prototype.isReachable = function(x, y) {
return true;
if(x < 0 || y < 0 || x >= this.width || y >= this.height) {
return false;
}
try{
var x1 = Math.floor(x/this.tileW);
var y1 = Math.floor(y/this.tileH);
if(!this.weightMap[x1] || !this.weightMap[x1][y1]) {
return false;
}
}catch(e){
console.error('reachable error : %j', e);
}
return this.weightMap[x1][y1] === 1;
};
/**
* Find path for given pos
* @param x, y {Number} Start point
* @param x1, y1 {Number} End point
* @param useCache {Boolean} If pathfinding cache is used
* @api public
*/
Map.prototype.findPath = function(x, y, x1, y1, useCache) {
useCache = useCache || false;
if( x < 0 || x > this.width || y < 0 || y > this.height || x1 < 0 || x1 > this.width || y1 < 0 || y1 > this.height) {
logger.warn('The point exceed the map range!');
return null;
}
if(!this.isReachable(x, y)) {
logger.warn('The start point is not reachable! start :(%j, %j)', x, y);
return null;
}
if(!this.isReachable(x1, y1)) {
logger.warn('The end point is not reachable! end : (%j, %j)', x1, y1);
return null;
}
if(this._checkLinePath(x, y, x1, y1)) {
return {path: [{x: x, y: y}, {x: x1, y: y1}], cost: formula.distance(x, y, x1, y1)};
}
var tx1 = Math.floor(x/this.tileW);
var ty1 = Math.floor(y/this.tileH);
var tx2 = Math.floor(x1/this.tileW);
var ty2 = Math.floor(y1/this.tileH);
//Use cache to get path
var path = this.pathCache.getPath(tx1, ty1, tx2, ty2);
if(!path || !path.paths) {
path = this.pfinder(tx1, ty1, tx2, ty2);
if(!path || !path.paths) {
logger.warn('can not find the path, path: %j', path);
return null;
}
if(useCache) {
this.pathCache.addPath(tx1, ty1, tx2, ty2, path);
}
}
var result = {};
var paths = [];
for(var i = 0; i < path.paths.length; i++) {
paths.push(transPos(path.paths[i], this.tileW, this.tileH));
}
paths = this.compressPath2(paths);
if(paths.length > 2) {
paths = this.compressPath1(paths, 3);
paths = this.compressPath2(paths);
}
result.path = paths;
result.cost = computeCost(paths);
return result;
};
/**
* Compute cost for given path
* @api public
*/
function computeCost(path) {
var cost = 0;
for(var i = 1; i < path.length; i++) {
var start = path[i-1];
var end = path[i];
cost += formula.distance(start.x, start.y, end.x, end.y);
}
return cost;
}
/**
* compress path by gradient
* @param tilePath {Array} Old path, construct by points
* @param x {Number} start x
* @param y {Number} start y
* @param x1 {Number} end x
* @param y1 {Number} end y
* @api private
*/
Map.prototype.compressPath2= function(tilePath) {
var oldPos = tilePath[0];
var path = [oldPos];
for(var i = 1; i < (tilePath.length - 1); i++) {
var pos = tilePath[i];
var nextPos = tilePath[i + 1];
if(!isLine(oldPos, pos, nextPos)) {
path.push(pos);
}
oldPos = pos;
pos = nextPos;
}
path.push(tilePath[tilePath.length - 1]);
return path;
};
/**
* Compress path to remove unneeded point
* @param path [Ayyay] The origin path
* @param loopTime [Number] The times to remove point, the bigger the number, the better the result, it should not exceed log(2, path.length)
* @return The compressed path
* @api private
*/
Map.prototype.compressPath1 = function(path, loopTime) {
var newPath;
for(var k = 0; k < loopTime; k++) {
var start;
var end;
newPath = [path[0]];
for(var i = 0, j = 2; j < path.length;) {
start = path[i];
end = path[j];
if(this._checkLinePath(start.x, start.y, end.x, end.y)) {
newPath.push(end);
i = j;
j += 2;
} else {
newPath.push(path[i+1]);
i++;
j++;
}
if(j >= path.length) {
if((i + 2) === path.length) {
newPath.push(path[i+1]);
}
}
}
path = newPath;
}
return newPath;
};
/**
* Veriry if the given path is valid
* @param path {Array} The given path
* @return {Boolean} verify result
* @api public
*/
Map.prototype.verifyPath = function(path) {
if(path.length < 2) {
return false;
}
var i;
for(i = 0; i < path.length; i++) {
if(!this.isReachable(path[i].x, path[i].y)) {
return false;
}
}
for(i = 1; i < path.length; i++) {
if(!this._checkLinePath(path[i-1].x, path[i-1].y, path[i].x, path[i].y)) {
logger.error('illigle path ! i : %j, path[i] : %j, path[i+1] : %j', i, path[i], path[i+1]);
return false;
}
}
return true;
};
/**
* Check if the line is valid
* @param x1 {Number} start x
* @param y1 {Number} start y
* @param x2 {Number} end x
* @param y2 {Number} end y
*/
Map.prototype._checkLinePath = function(x1, y1, x2, y2) {
var px = x2 - x1;
var py = y2 - y1;
var tile = this.tileW/2;
if(px === 0) {
while(x1 < x2) {
x1 += tile;
if(!this.isReachable(x1, y1)) {
return false;
}
}
return true;
}
if(py === 0) {
while(y1 < y2) {
y1 += tile;
if(!this.isReachable(x1, y1)) {
return false;
}
}
return true;
}
var dis = formula.distance(x1, y1, x2, y2);
var rx = (x2 - x1) / dis;
var ry = (y2 - y1) / dis;
var dx = tile * rx;
var dy = tile * ry;
var x0 = x1;
var y0 = y1;
x1 += dx;
y1 += dy;
while((dx > 0 && x1 < x2) || (dx < 0 && x1 > x2)) {
if(!this._testLine(x0, y0, x1, y1)) {
return false;
}
x0 = x1;
y0 = y1;
x1 += dx;
y1 += dy;
}
return true;
};
Map.prototype._testLine = function(x, y, x1, y1) {
if(!this.isReachable(x, y) || !this.isReachable(x1, y1)) {
return false;
}
var dx = x1 - x;
var dy = y1 - y;
var tileX = Math.floor(x/this.tileW);
var tileY = Math.floor(y/this.tileW);
var tileX1 = Math.floor(x1/this.tileW);
var tileY1 = Math.floor(y1/this.tileW);
if(tileX === tileX1 || tileY === tileY1) {
return true;
}
var minY = y < y1 ? y : y1;
var maxTileY = (tileY > tileY1 ? tileY : tileY1) * this.tileW;
if((maxTileY-minY) === 0) {
return true;
}
var y0 = maxTileY;
var x0 = x + dx / dy * (y0 - y);
var maxTileX = (tileX > tileX1 ? tileX : tileX1) * this.tileW;
var x3 = (x0 + maxTileX) / 2;
var y3 = y + dy / dx * (x3 - x);
if(this.isReachable(x3, y3)) {
return true;
}
return false;
};
/**
* Change pos from tile pos to real position(The center of tile)
* @param pos {Object} Tile position
* @param tileW {Number} Tile width
* @param tileH {Number} Tile height
* @return {Object} The real position
* @api public
*/
function transPos(pos, tileW, tileH) {
var newPos = {};
newPos.x = pos.x*tileW + tileW/2;
newPos.y = pos.y*tileH + tileH/2;
return newPos;
}
/**
* Test if the given three point is on the same line
* @param p0 {Object}
* @param p1 {Object}
* @param p2 {Object}
* @return {Boolean}
* @api public
*/
function isLine(p0, p1, p2) {
return ((p1.x-p0.x)===(p2.x-p1.x)) && ((p1.y-p0.y) === (p2.y-p1.y));
}
module.exports = Map;
| mit |
sayarco/sayardocs | src/app/shared/components/compare.component.ts | 7540 | import { Component, Input, Output, EventEmitter, ViewChild } from '@angular/core';
import { Scroll } from 'ionic-angular';
import { Observable } from 'rxjs/Observable';
import { Store } from '@ngrx/store';
import { AppState } from '../../store/root.reducer';
import * as Impetus from 'impetus/dist/impetus';
@Component({
selector:'sd-compare',
styles:[],
template: `
<header-tabs><ng-content></ng-content></header-tabs>
<header-tabs-scroll [tabDisplaySizeRate]="tabDisplaySizeRate" [tabDisplayLeft]="tabDisplayLeft" [transitionEnabled]="false"></header-tabs-scroll>
<ion-content padding class="headerTabsTopMargin noPaddingTop">
<ion-list ion-grid>
<ion-row>
<ion-col [attr.col-4]="viewportSmall" [attr.col-2]="viewportLarge">
<record-detail *ngIf="records[0]" [inputKey]="records[0]" [fieldOnly]="true"></record-detail>
</ion-col>
<ion-col [attr.col-8]="viewportSmall" [attr.col-10]="viewportLarge" #tableContainer>
<div class="is-blankBackground is-fullHeight" #topContainer>
<div class="is-overFlowHidden is-fullHeight" [style.width.px]="mainContainerWidth">
<ng-container *ngIf="platform.isBrowser">
<div class="is-relative is-fullHeight"
[style.transform]="'translateX(' + innerContainerLeft + 'px)'"
[style.width.px]="innerContainerWidth"
[ngClass]="{'transition': false}"
>
<ng-container *ngTemplateOutlet="compare"></ng-container>
</div>
</ng-container>
<ng-container *ngIf="!platform.isBrowser">
<ion-scroll class="is-fullHeight is-fullHeightScroll noPaddingLeft noPaddingTop" scrollX="true" scrollY="false" #innerContainerScroll>
<div class="is-relative is-fullHeight" [style.width.px]="innerContainerWidth" [style.left.px]="innerContainerLeft">
<ng-container *ngTemplateOutlet="compare"></ng-container>
</div>
</ion-scroll>
</ng-container>
</div>
</div>
</ion-col>
</ion-row>
</ion-list>
</ion-content>
<ng-template #compare>
<ng-container *ngFor="let record of records; let i=index; let f=first">
<div class="is-floatLeft is-borderRight" [style.width.px]="computedPanelWidth">
<record-detail [inputKey]="record" [dataOnly]="true"></record-detail>
<ion-item no-lines (click)="revert.emit(record)" *ngIf="isButtonsEnabled && !record.isDeleted">
<button small ion-button color="primary" class="mL8i">Revert to Version {{record['_v']}}</button>
</ion-item>
<ion-item no-lines *ngIf="isButtonsEnabled && record.isDeleted">
<button small ion-button color="primary" class="mL8i" disabled>Can't revert to deleted Version {{record['_v']}}</button>
</ion-item>
</div>
</ng-container>
</ng-template>
`
})
export class CompareComponent {
@ViewChild('tableContainer') tableContainer: any;
@ViewChild('topContainer') topContainer: any;
@ViewChild('innerContainerScroll') innerContainerScroll: any;
fullContainerWidth: number;
mainContainerWidth: number;
innerContainerLeft$; innerContainerLeft: number = 0; innerContainerWidth: number = 0;
columnSizeUnit: number = 100;
impetusBounceWidth: number; panelImpetus;
tabDisplaySizeRate: number;
tabDisplayLeft: number = 0;
@Input() records = [];
@Input() idealPanelWidth;
@Input() isButtonsEnabled = false;
@Output() revert: EventEmitter<any> = new EventEmitter<any>();
computedPanelWidth: number;
viewportSize$; viewportSmall; viewportLarge;
dimensionSubs; dimensions$ = this.store.select(store => store.layout.dimensions);
platform; platform$ = this.store.select(store => store.system.platform);
constructor(
private store: Store<AppState>
) {
// Responsive layout for the template. Can have maximum 5 columns in the largest screens
this.viewportSize$ = this.store.select(store => store.layout.viewport)
.select(viewport=>viewport.size).subscribe(x=> {
if(x === 'lg' || x === 'xl') {
this.viewportSmall = null; this.viewportLarge = true;
} else {
this.viewportSmall = true; this.viewportLarge = null;
}
});
this.platform$.subscribe(platform=> {
this.platform = platform;
//this.platform = {isBrowser:false}; // Useful for testing non-browser (native)in development
});
}
ngOnChanges(changes) {
// Wait for data to arrive. There are too many inputs. Make sure all the initial data comes and the block
// below gets executed once in the initialization. Debounce dimensions to make it execute after viewport.
if(this.dimensionSubs) { this.dimensionSubs.unsubscribe(); }
if(this.records) {
this.dimensionSubs = this.dimensions$.debounceTime(10).subscribe(dimensions => {
this.mainContainerWidth = this.tableContainer.nativeElement.clientWidth;
this.fullContainerWidth = dimensions.mainContainerWidth;
this.organizeColumns();
});
}
}
organizeColumns() {
let initialTableSize = this.records.length * this.idealPanelWidth;
// Computed table size is smaller than viewport. Strech it
// console.log(`${initialTableSize} / ${this.mainContainerWidth}`);
if(initialTableSize < this.mainContainerWidth ) {
this.computedPanelWidth = (this.mainContainerWidth / this.records.length);
this.innerContainerWidth = this.computedPanelWidth * this.records.length;
this.tabDisplaySizeRate = 100;
} else {
if (this.mainContainerWidth < this.idealPanelWidth) {
this.computedPanelWidth = this.mainContainerWidth;
} else {
this.computedPanelWidth = this.idealPanelWidth;
}
this.innerContainerWidth = this.computedPanelWidth * this.records.length;
this.tabDisplaySizeRate = this.mainContainerWidth / this.innerContainerWidth * 100;
}
this.innerContainerLeft = 0;
if(this.platform.isBrowser) {
this.createImpetus(this.innerContainerLeft);
} else {
if(this.innerContainerScroll) {
Observable.fromEvent(this.innerContainerScroll._scrollContent.nativeElement, 'scroll').subscribe(x=> {
let scrollLeft = this.innerContainerScroll._scrollContent.nativeElement.scrollLeft;
this.tabDisplayLeft = scrollLeft * ( this.mainContainerWidth / this.innerContainerWidth) * (this.fullContainerWidth / this.mainContainerWidth);
});
}
}
function getSum(total, num) {
return parseInt(total) + parseInt(num);
}
}
createImpetus(initialX) {
if(this.platform.isBrowser) {
if(this.panelImpetus) {
this.panelImpetus = this.panelImpetus.destroy();
}
this.panelImpetus = new Impetus({
source: this.topContainer.nativeElement,
bounce: false, // Bounce is flickering between 1 and -1 so its toggled off
boundX: [-(this.innerContainerWidth - this.mainContainerWidth) ,0], // Not used now
initialValues: [initialX, 0],
friction: 0.92,
update: (x, y) => {
this.innerContainerLeft = x;
this.tabDisplayLeft = (-1) * x * (this.mainContainerWidth / this.innerContainerWidth) * (this.fullContainerWidth / this.mainContainerWidth);
}
});
}
}
}
| mit |
raczeja/Test.Automation | Objectivity.Test.Automation.Common/Types/Kendo/KendoComboBox.cs | 1916 | /*
The MIT License (MIT)
Copyright (c) 2015 Objectivity Bespoke Software Specialists
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.
*/
namespace Objectivity.Test.Automation.Common.Types.Kendo
{
using OpenQA.Selenium;
/// <summary>
/// Kendo Combo Box element
/// </summary>
public class KendoComboBox : KendoSelect
{
/// <summary>
/// Initializes a new instance of the <see cref="KendoComboBox"/> class.
/// </summary>
/// <param name="webElement">The webElement</param>
public KendoComboBox(IWebElement webElement)
: base(webElement)
{
}
/// <summary>Gets the selector.</summary>
/// <value>The selector.</value>
protected override string SelectType
{
get
{
return "kendoComboBox";
}
}
}
}
| mit |
lexek/chat | src/main/java/lexek/wschat/chat/msg/EmoticonProvider.java | 235 | package lexek.wschat.chat.msg;
import lexek.wschat.db.model.Emoticon;
import org.jvnet.hk2.annotations.Contract;
import java.util.List;
@Contract
public interface EmoticonProvider<T extends Emoticon> {
List<T> getEmoticons();
}
| mit |
craigbridges/Nettle | src/Nettle.Tests/NettleTests.cs | 600 | using Shouldly;
using System;
using Xunit;
namespace Nettle.Tests
{
public class NettleTests
{
[Fact]
public void CanTemplateString()
{
var source = @"Welcome {{Name}}";
var model = new
{
Name = "John Smith"
};
var compiler = NettleEngine.GetCompiler();
var template = compiler.Compile(source);
var output = template(model);
output.ShouldBe("Welcome John Smith");
/* Result:
Welcome John Smith
*/
}
}
}
| mit |
aarongough/triangular | lib/triangular/facet.rb | 1765 | # frozen_string_literal: true
module Triangular
class Facet
attr_accessor :normal, :vertices
def initialize(normal = nil, *args)
@normal = normal
@vertices = args
end
def to_s
output = "facet normal #{@normal}\n"
output += "outer loop\n"
@vertices.each do |vertex|
output += "#{vertex}\n"
end
output += "endloop\n"
output += "endfacet\n"
output
end
def lines
[
Line.new(@vertices[0], @vertices[1]),
Line.new(@vertices[1], @vertices[2]),
Line.new(@vertices[2], @vertices[0])
]
end
def intersection_at_z(z_plane)
return nil if @vertices.count { |vertex| vertex.z == z_plane } > 2
intersection_points = lines.map do |line|
line.intersection_at_z(z_plane)
end.compact
return Line.new(intersection_points[0], intersection_points[1]) if intersection_points.count == 2
nil
end
def translate!(x, y, z)
@vertices.each do |vertex|
vertex.translate!(x, y, z)
end
end
def self.parse(string)
facets = []
string.scan(pattern) do |match_data|
facets << Facet.new(
Vector.parse(match_data[0]), # Normal
Vertex.parse(match_data[4]), # Vertex 1
Vertex.parse(match_data[9]), # Vertex 2
Vertex.parse(match_data[14]) # Vertex 3
)
end
facets.length == 1 ? facets.first : facets
end
def self.pattern
/
\s* facet\snormal\s (?<normal> #{Point.pattern})\s
\s* outer\sloop\s
\s* (?<vertex1> #{Vertex.pattern})
\s* (?<vertex2> #{Vertex.pattern})
\s* (?<vertex3> #{Vertex.pattern})
\s* endloop\s
\s* endfacet\s
/x
end
end
end
| mit |
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_06_01/aio/operations/_vpn_sites_configuration_operations.py | 8363 | # coding=utf-8
# --------------------------------------------------------------------------
# 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.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class VpnSitesConfigurationOperations:
"""VpnSitesConfigurationOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.network.v2019_06_01.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
async def _download_initial(
self,
resource_group_name: str,
virtual_wan_name: str,
request: "_models.GetVpnSitesConfigurationRequest",
**kwargs: Any
) -> None:
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2019-06-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self._download_initial.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'virtualWANName': self._serialize.url("virtual_wan_name", virtual_wan_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(request, 'GetVpnSitesConfigurationRequest')
body_content_kwargs['content'] = body_content
request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.Error, response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_download_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualWans/{virtualWANName}/vpnConfiguration'} # type: ignore
async def begin_download(
self,
resource_group_name: str,
virtual_wan_name: str,
request: "_models.GetVpnSitesConfigurationRequest",
**kwargs: Any
) -> AsyncLROPoller[None]:
"""Gives the sas-url to download the configurations for vpn-sites in a resource group.
:param resource_group_name: The resource group name.
:type resource_group_name: str
:param virtual_wan_name: The name of the VirtualWAN for which configuration of all vpn-sites is
needed.
:type virtual_wan_name: str
:param request: Parameters supplied to download vpn-sites configuration.
:type request: ~azure.mgmt.network.v2019_06_01.models.GetVpnSitesConfigurationRequest
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling.
Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType[None]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = await self._download_initial(
resource_group_name=resource_group_name,
virtual_wan_name=virtual_wan_name,
request=request,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
if cls:
return cls(pipeline_response, None, {})
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'virtualWANName': self._serialize.url("virtual_wan_name", virtual_wan_name, 'str'),
}
if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = AsyncNoPolling()
else: polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_download.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualWans/{virtualWANName}/vpnConfiguration'} # type: ignore
| mit |
aq1018/pdfkit | js/path.js | 9425 | (function() {
var SVGPath;
SVGPath = (function() {
var apply, arcToSegments, cx, cy, parameters, parse, px, py, runners, segmentToBezier, solveArc, sx, sy;
function SVGPath() {}
SVGPath.apply = function(doc, path) {
var commands;
commands = parse(path);
return apply(commands, doc);
};
parameters = {
A: 7,
a: 7,
C: 6,
c: 6,
H: 1,
h: 1,
L: 2,
l: 2,
M: 2,
m: 2,
Q: 4,
q: 4,
S: 4,
s: 4,
T: 2,
t: 2,
V: 1,
v: 1,
Z: 0,
z: 0
};
parse = function(path) {
var args, c, cmd, curArg, foundDecimal, params, ret, _i, _len;
ret = [];
args = [];
curArg = "";
foundDecimal = false;
params = 0;
for (_i = 0, _len = path.length; _i < _len; _i++) {
c = path[_i];
if (parameters[c] != null) {
params = parameters[c];
if (cmd) {
if (curArg.length > 0) {
args[args.length] = +curArg;
}
ret[ret.length] = {
cmd: cmd,
args: args
};
args = [];
curArg = "";
foundDecimal = false;
}
cmd = c;
} else if ((c === " " || c === ",") || (c === "-" && curArg.length > 0) || (c === "." && foundDecimal)) {
if (curArg.length === 0) {
continue;
}
if (args.length === params) {
ret[ret.length] = {
cmd: cmd,
args: args
};
args = [+curArg];
if (cmd === "M") {
cmd = "L";
}
if (cmd === "m") {
cmd = "l";
}
} else {
args[args.length] = +curArg;
}
foundDecimal = c === ".";
curArg = c === '-' || c === '.' ? c : '';
} else {
curArg += c;
if (c === '.') {
foundDecimal = true;
}
}
}
if (curArg.length > 0) {
args[args.length] = +curArg;
}
ret[ret.length] = {
cmd: cmd,
args: args
};
return ret;
};
cx = cy = px = py = sx = sy = 0;
apply = function(commands, doc) {
var c, i, _i, _len, _name;
cx = cy = px = py = sx = sy = 0;
for (i = _i = 0, _len = commands.length; _i < _len; i = ++_i) {
c = commands[i];
if (typeof runners[_name = c.cmd] === "function") {
runners[_name](doc, c.args);
}
}
return cx = cy = px = py = 0;
};
runners = {
M: function(doc, a) {
cx = a[0];
cy = a[1];
px = py = null;
sx = cx;
sy = cy;
return doc.moveTo(cx, cy);
},
m: function(doc, a) {
cx += a[0];
cy += a[1];
px = py = null;
sx = cx;
sy = cy;
return doc.moveTo(cx, cy);
},
C: function(doc, a) {
cx = a[4];
cy = a[5];
px = a[2];
py = a[3];
return doc.bezierCurveTo.apply(doc, a);
},
c: function(doc, a) {
doc.bezierCurveTo(a[0] + cx, a[1] + cy, a[2] + cx, a[3] + cy, a[4] + cx, a[5] + cy);
px = cx + a[2];
py = cy + a[3];
cx += a[4];
return cy += a[5];
},
S: function(doc, a) {
if (px === null) {
px = cx;
py = cy;
}
doc.bezierCurveTo(cx - (px - cx), cy - (py - cy), a[0], a[1], a[2], a[3]);
px = a[0];
py = a[1];
cx = a[2];
return cy = a[3];
},
s: function(doc, a) {
doc.bezierCurveTo(cx - (px - cx), cy - (py - cy), cx + a[0], cy + a[1], cx + a[2], cy + a[3]);
px = cx + a[0];
py = cy + a[1];
cx += a[2];
return cy += a[3];
},
Q: function(doc, a) {
px = a[0];
py = a[1];
cx = a[2];
cy = a[3];
return doc.quadraticCurveTo(a[0], a[1], cx, cy);
},
q: function(doc, a) {
doc.quadraticCurveTo(a[0] + cx, a[1] + cy, a[2] + cx, a[3] + cy);
px = cx + a[0];
py = cy + a[1];
cx += a[2];
return cy += a[3];
},
T: function(doc, a) {
if (px === null) {
px = cx;
py = cy;
} else {
px = cx - (px - cx);
py = cy - (py - cy);
}
doc.quadraticCurveTo(px, py, a[0], a[1]);
px = cx - (px - cx);
py = cy - (py - cy);
cx = a[0];
return cy = a[1];
},
t: function(doc, a) {
if (px === null) {
px = cx;
py = cy;
} else {
px = cx - (px - cx);
py = cy - (py - cy);
}
doc.quadraticCurveTo(px, py, cx + a[0], cy + a[1]);
cx += a[0];
return cy += a[1];
},
A: function(doc, a) {
solveArc(doc, cx, cy, a);
cx = a[5];
return cy = a[6];
},
a: function(doc, a) {
a[5] += cx;
a[6] += cy;
solveArc(doc, cx, cy, a);
cx = a[5];
return cy = a[6];
},
L: function(doc, a) {
cx = a[0];
cy = a[1];
px = py = null;
return doc.lineTo(cx, cy);
},
l: function(doc, a) {
cx += a[0];
cy += a[1];
px = py = null;
return doc.lineTo(cx, cy);
},
H: function(doc, a) {
cx = a[0];
px = py = null;
return doc.lineTo(cx, cy);
},
h: function(doc, a) {
cx += a[0];
px = py = null;
return doc.lineTo(cx, cy);
},
V: function(doc, a) {
cy = a[0];
px = py = null;
return doc.lineTo(cx, cy);
},
v: function(doc, a) {
cy += a[0];
px = py = null;
return doc.lineTo(cx, cy);
},
Z: function(doc) {
doc.closePath();
cx = sx;
return cy = sy;
},
z: function(doc) {
doc.closePath();
cx = sx;
return cy = sy;
}
};
solveArc = function(doc, x, y, coords) {
var bez, ex, ey, large, rot, rx, ry, seg, segs, sweep, _i, _len, _results;
rx = coords[0], ry = coords[1], rot = coords[2], large = coords[3], sweep = coords[4], ex = coords[5], ey = coords[6];
segs = arcToSegments(ex, ey, rx, ry, large, sweep, rot, x, y);
_results = [];
for (_i = 0, _len = segs.length; _i < _len; _i++) {
seg = segs[_i];
bez = segmentToBezier.apply(null, seg);
_results.push(doc.bezierCurveTo.apply(doc, bez));
}
return _results;
};
arcToSegments = function(x, y, rx, ry, large, sweep, rotateX, ox, oy) {
var a00, a01, a10, a11, cos_th, d, i, pl, result, segments, sfactor, sfactor_sq, sin_th, th, th0, th1, th2, th3, th_arc, x0, x1, xc, y0, y1, yc, _i;
th = rotateX * (Math.PI / 180);
sin_th = Math.sin(th);
cos_th = Math.cos(th);
rx = Math.abs(rx);
ry = Math.abs(ry);
px = cos_th * (ox - x) * 0.5 + sin_th * (oy - y) * 0.5;
py = cos_th * (oy - y) * 0.5 - sin_th * (ox - x) * 0.5;
pl = (px * px) / (rx * rx) + (py * py) / (ry * ry);
if (pl > 1) {
pl = Math.sqrt(pl);
rx *= pl;
ry *= pl;
}
a00 = cos_th / rx;
a01 = sin_th / rx;
a10 = (-sin_th) / ry;
a11 = cos_th / ry;
x0 = a00 * ox + a01 * oy;
y0 = a10 * ox + a11 * oy;
x1 = a00 * x + a01 * y;
y1 = a10 * x + a11 * y;
d = (x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0);
sfactor_sq = 1 / d - 0.25;
if (sfactor_sq < 0) {
sfactor_sq = 0;
}
sfactor = Math.sqrt(sfactor_sq);
if (sweep === large) {
sfactor = -sfactor;
}
xc = 0.5 * (x0 + x1) - sfactor * (y1 - y0);
yc = 0.5 * (y0 + y1) + sfactor * (x1 - x0);
th0 = Math.atan2(y0 - yc, x0 - xc);
th1 = Math.atan2(y1 - yc, x1 - xc);
th_arc = th1 - th0;
if (th_arc < 0 && sweep === 1) {
th_arc += 2 * Math.PI;
} else if (th_arc > 0 && sweep === 0) {
th_arc -= 2 * Math.PI;
}
segments = Math.ceil(Math.abs(th_arc / (Math.PI * 0.5 + 0.001)));
result = [];
for (i = _i = 0; 0 <= segments ? _i < segments : _i > segments; i = 0 <= segments ? ++_i : --_i) {
th2 = th0 + i * th_arc / segments;
th3 = th0 + (i + 1) * th_arc / segments;
result[i] = [xc, yc, th2, th3, rx, ry, sin_th, cos_th];
}
return result;
};
segmentToBezier = function(cx, cy, th0, th1, rx, ry, sin_th, cos_th) {
var a00, a01, a10, a11, t, th_half, x1, x2, x3, y1, y2, y3;
a00 = cos_th * rx;
a01 = -sin_th * ry;
a10 = sin_th * rx;
a11 = cos_th * ry;
th_half = 0.5 * (th1 - th0);
t = (8 / 3) * Math.sin(th_half * 0.5) * Math.sin(th_half * 0.5) / Math.sin(th_half);
x1 = cx + Math.cos(th0) - t * Math.sin(th0);
y1 = cy + Math.sin(th0) + t * Math.cos(th0);
x3 = cx + Math.cos(th1);
y3 = cy + Math.sin(th1);
x2 = x3 + t * Math.sin(th1);
y2 = y3 - t * Math.cos(th1);
return [a00 * x1 + a01 * y1, a10 * x1 + a11 * y1, a00 * x2 + a01 * y2, a10 * x2 + a11 * y2, a00 * x3 + a01 * y3, a10 * x3 + a11 * y3];
};
return SVGPath;
})();
module.exports = SVGPath;
}).call(this);
// Generated by CoffeeScript 1.5.0-pre
| mit |
PLOS/rich_citations_api | db/migrate/20140913031005_add_ref_id_to_citation.rb | 306 | class AddRefIdToCitation < ActiveRecord::Migration
def up
# Do this in two steps because SQLLite is a pain
add_column :citations, :ref, :string, limit: 255
change_column :citations, :ref, :string, limit: 255, :null => false
end
def down
remove_column :citations, :ref
end
end
| mit |
Zenohm/mafiademonstration | src/mafiademonstration.py | 2859 | # -*- coding: utf-8 -*-
import kivy
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, NoTransition
from os.path import join, dirname
kivy.require('1.9.1')
try:
import stages
except ModuleNotFoundError:
from . import stages
class MafiaDemonstrationApp(App):
"""Simple Slideshow App with a user defined title.
Attributes:
title (str): Window title of the application
"""
title = 'Mafia Demonstration'
def build(self) -> ScreenManager:
"""Initialize the GUI based on the kv file and set up events.
:rtype: ScreenManager
:return: Root widget specified in the kv file of the app
"""
sm = ScreenManager(transition=NoTransition())
sm.add_widget(stages.MainMenu(name='mainmenu'))
sm.add_widget(stages.Discussion(name='discussion'))
sm.add_widget(stages.Tutorial(name='tutorial'))
sm.add_widget(stages.PlayerStatus(name='playerstatus'))
sm.add_widget(stages.StagesTutorial(name='stagestutorial'))
sm.add_widget(stages.Credits(name='credits'))
sm.add_widget(stages.LoadingDT(name='loadingDT'))
sm.add_widget(stages.Trial(name='trial'))
sm.add_widget(stages.LoadingTN(name='loadingTN'))
sm.add_widget(stages.Night(name='night'))
sm.add_widget(stages.LoadingND(name='loadingND'))
sm.add_widget(stages.GameOverMenu(name='gameovermenu'))
return sm
def build_config(self, config) -> None:
"""Create a config file on disk and assign the ConfigParser object to
`self.config`.
"""
config.setdefaults(
'user_settings', {
'timer_interval': '1/60 sec',
'language': 'en',
'player_count': 6,
'agent_number': 1,
}
)
config.setdefaults(
'debug', {
'stage_jump': 'discussion',
}
)
def build_settings(self, settings) -> None:
filename = join(dirname(__file__), 'user_settings.json')
settings.add_json_panel(self.title, self.config, filename)
def on_config_change(self, config, section, key, value) -> None:
if config is self.config:
token = (section, key)
if token == ('user_settings', 'timer_interval'):
pass
# self.timer_interval = TIMER_OPTIONS[value]
elif token == ('user_settings', 'language'):
self.language = value
elif token == ('user_settings', 'player_count'):
self.config.write
self.player_count = value
elif token == ('user_settings', 'agent_number'):
self.agent_number = value
def on_pause(self) -> bool:
return True
def on_resume(self) -> None:
pass
| mit |
samrodriguez/sf_siresca | app/cache/dev/assetic/config/5/561b4f4900da52220373c7fdf79420a4.php | 69 | <?php
// UDSsirescaBundle:Direccion:new.html.twig
return array (
);
| mit |
drborges/pyprofiler | tests/decorators_profile_checkpoint_test.py | 700 | from sure import expect
from mock import Mock, call
from decorators import profile_checkpoint
def test_profile_checkpoint_decorator():
profiler = Mock()
profiler.start = Mock()
profiler.intermediate = Mock()
@profile_checkpoint(profiler, profile_id='id')
def fn():
profiler.intermediate()
fn()
expect(profiler.mock_calls[0]).to.equal(call.checkpoint('id'))
expect(profiler.mock_calls[1]).to.equal(call.intermediate())
expect(profiler.mock_calls).to.have.length_of(2)
def test_profiled_function_returns_expected_value():
@profile_checkpoint(profiler = Mock(), profile_id='id')
def sum(a, b):
return a + b
sum_result = sum(3, 2)
expect(sum_result).to.equal(5)
| mit |
Universal-Model-Converter/UMC3.0a | data/Python/x86/Lib/site-packages/OpenGL/raw/GL/ARB/shader_stencil_export.py | 484 | '''OpenGL extension ARB.shader_stencil_export
Automatically generated by the get_gl_extensions script, do not edit!
'''
from OpenGL import platform, constants, constant, arrays
from OpenGL import extensions
from OpenGL.GL import glget
import ctypes
EXTENSION_NAME = 'GL_ARB_shader_stencil_export'
_DEPRECATED = False
def glInitShaderStencilExportARB():
'''Return boolean indicating whether this extension is available'''
return extensions.hasGLExtension( EXTENSION_NAME )
| mit |
thlorenz/bconfig | examples/separate-paths.js | 242 | 'use strict';
var bconfig = require('..');
var util = require('util');
var separatePathsAndShim = true;
var config = bconfig(require.resolve('./fixtures/requirejs-config'), separatePathsAndShim);
console.log(util.inspect(config, null, 5));
| mit |
helix-toolkit/icon-generator | IconGenerator/TrefoilKnotVisual3D.cs | 3879 | namespace IconGenerator
{
using System;
using System.Windows;
using System.Windows.Media.Media3D;
using HelixToolkit.Wpf;
/// <summary>
/// Represents a 3D visual showing a trefoil knot.
/// </summary>
/// <remarks>See <a href="https://en.wikipedia.org/wiki/Trefoil_knot">Wikipedia</a>.</remarks>
public class TrefoilKnotVisual3D : ParametricSurface3D
{
/// <summary>
/// Identifies the <see cref="B"/> dependency property.
/// </summary>
public static readonly DependencyProperty BProperty =
DependencyProperty.Register("B", typeof(double), typeof(TrefoilKnotVisual3D), new PropertyMetadata(3d, GeometryChanged));
/// <summary>
/// Identifies the <see cref="C1"/> dependency property.
/// </summary>
public static readonly DependencyProperty C1Property =
DependencyProperty.Register("C1", typeof(double), typeof(TrefoilKnotVisual3D), new PropertyMetadata(10d, GeometryChanged));
/// <summary>
/// Identifies the <see cref="C2"/> dependency property.
/// </summary>
public static readonly DependencyProperty C2Property =
DependencyProperty.Register("C2", typeof(double), typeof(TrefoilKnotVisual3D), new PropertyMetadata(2d, GeometryChanged));
/// <summary>
/// Gets or sets the b parameter. The default is 3.
/// </summary>
/// <value>The b value.</value>
public double B
{
get { return (double)this.GetValue(BProperty); }
set { this.SetValue(BProperty, value); }
}
/// <summary>
/// Gets or sets the c1 parameter. The default is 10.
/// </summary>
/// <value>The c1 value.</value>
public double C1
{
get { return (double)this.GetValue(C1Property); }
set { this.SetValue(C1Property, value); }
}
/// <summary>
/// Gets or sets the c2 parameter. The default is 2.
/// </summary>
/// <value>The c2 value.</value>
public double C2
{
get { return (double)this.GetValue(C2Property); }
set { this.SetValue(C2Property, value); }
}
/// <summary>
/// Evaluates the surface at the specified u,v parameters.
/// </summary>
/// <param name="u">The u parameter.</param>
/// <param name="v">The v parameter.</param>
/// <param name="uv">The texture coordinates.</param>
/// <returns>The evaluated <see cref="T:System.Windows.Media.Media3D.Point3D" />.</returns>
protected override Point3D Evaluate(double u, double v, out Point uv)
{
u *= 4 * Math.PI;
v = (v - 0.5) * 2 * Math.PI;
double b = this.B;
double cosu = Math.Cos(u);
double sinu = Math.Sin(u);
double cosv = Math.Cos(v);
double sinv = Math.Sin(v);
double c1 = this.C1;
double c2 = this.C2;
double c3 = c1 * (Math.Cos(b * u / 2) + b) / 4;
double c4 = -c3 * sinu - b * c1 * Math.Sin(b * u / 2) * cosu / 8;
double c5 = c3 * cosu - b * c1 * Math.Sin(b * u / 2) * sinu / 8;
double c6 = (b * c3 * Math.Cos(Math.Sin(b * u / 2)) * Math.Cos(b * u / 2)) / 2 - (b * c1 * Math.Sin(Math.Sin(b * u / 2)) * Math.Sin(b * u / 2)) / 8;
double c7 = Math.Sqrt(c4 * c4 + c5 * c5);
double c8 = Math.Sqrt(c4 * c4 + c5 * c5 + c6 * c6);
var x = c3 * cosu + (c2 * (c8 * cosv * c5 - sinv * c4 * c6) / (c7 * c8));
var y = c3 * sinu - (c2 * (c8 * cosv * c4 + sinv * c5 * c6) / (c7 * c8));
var z = c3 * Math.Sin(Math.Sin(b * u / 2)) + (c2 * sinv * c7 / c8);
uv = new Point(u, v);
return new Point3D(x, y, z);
}
}
} | mit |
rails/conductor | app/controllers/conductor/app_controllers_controller.rb | 594 | require 'rails/generators'
module Conductor
class AppControllersController < ApplicationController
include Tubesock::Hijack
require 'pty'
def new
@page_title = 'Controllers'
end
def create
@form = ControllerGeneratorForm.new(params[:app_controller])
if @form.valid?
Rails.logger.info @form.command_line
@form.run
flash[:success] = "The controller was created!"
else
flash[:error] = "Cannot create the controller! Please verify the information"
end
redirect_to(new_app_controller_url)
end
end
end
| mit |
gems-uff/trackbus | www/js/utils/directives/focus-element.directives.js | 685 | (function() {
'use strict';
angular
.module('utils')
.directive('focusElement', focusElement);
focusElement.$inject = ['$window', '$timeout'];
function focusElement($window, $timeout) {
return function(scope, elem, attr) {
elem.on('click', function() {
$timeout(function() {
$window.document.getElementById(attr.focusElement).focus();
})
});
// Removes bound events in the element itself
// when the scope is destroyed
scope.$on('$destroy', function() {
elem.off('click');
});
};
};
})(); | mit |
selvasingh/azure-sdk-for-java | sdk/network/mgmt-v2020_04_01/src/main/java/com/microsoft/azure/management/network/v2020_04_01/ApplicationGatewaySslProtocol.java | 1647 | /**
* 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.
*/
package com.microsoft.azure.management.network.v2020_04_01;
import java.util.Collection;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.microsoft.rest.ExpandableStringEnum;
/**
* Defines values for ApplicationGatewaySslProtocol.
*/
public final class ApplicationGatewaySslProtocol extends ExpandableStringEnum<ApplicationGatewaySslProtocol> {
/** Static value TLSv1_0 for ApplicationGatewaySslProtocol. */
public static final ApplicationGatewaySslProtocol TLSV1_0 = fromString("TLSv1_0");
/** Static value TLSv1_1 for ApplicationGatewaySslProtocol. */
public static final ApplicationGatewaySslProtocol TLSV1_1 = fromString("TLSv1_1");
/** Static value TLSv1_2 for ApplicationGatewaySslProtocol. */
public static final ApplicationGatewaySslProtocol TLSV1_2 = fromString("TLSv1_2");
/**
* Creates or finds a ApplicationGatewaySslProtocol from its string representation.
* @param name a name to look for
* @return the corresponding ApplicationGatewaySslProtocol
*/
@JsonCreator
public static ApplicationGatewaySslProtocol fromString(String name) {
return fromString(name, ApplicationGatewaySslProtocol.class);
}
/**
* @return known ApplicationGatewaySslProtocol values
*/
public static Collection<ApplicationGatewaySslProtocol> values() {
return values(ApplicationGatewaySslProtocol.class);
}
}
| mit |
icarus-consulting/Yaapii.Atoms | tests/Yaapii.Atoms.Tests/Number/LiveNumberTests.cs | 4032 | // MIT License
//
// Copyright(c) 2022 ICARUS Consulting GmbH
//
// 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.
using System;
using System.Collections.Generic;
using Xunit;
namespace Yaapii.Atoms.Number.Tests
{
public sealed class LiveNumberTests
{
[Fact]
public void ConversionIsLive()
{
var text = "gkb";
var number = new LiveNumber(() => text);
text = "42";
Assert.Equal(42, number.AsInt());
}
[Fact]
public void ParsesFloat()
{
Assert.True(
new LiveNumber(() => 4673.453F).AsFloat() == 4673.453F
);
}
[Fact]
public void RejectsNoFloatText()
{
Assert.Throws<ArgumentException>(() =>
new LiveNumber(() => "ghki").AsFloat()
);
}
[Fact]
public void ParsesInt()
{
Assert.True(
new LiveNumber(() => 1337).AsInt() == 1337
);
}
[Fact]
public void RejectsNoIntText()
{
Assert.Throws<ArgumentException>(() =>
new LiveNumber(() => "ghki").AsInt()
);
}
[Fact]
public void ParsesDouble()
{
Assert.True(
new LiveNumber(() => 843.23969274001D).AsDouble() == 843.23969274001D
);
}
[Fact]
public void RejectsNoDoubleText()
{
Assert.Throws<ArgumentException>(() =>
new LiveNumber(() => "ghki").AsDouble()
);
}
[Fact]
public void ParsesLong()
{
Assert.True(
new LiveNumber(() => 139807814253711).AsLong() == 139807814253711L
);
}
[Fact]
public void RejectsNoLongText()
{
Assert.Throws<ArgumentException>(() =>
new LiveNumber(() => "ghki").AsLong()
);
}
[Fact]
public void IntToDouble()
{
Assert.True(
new LiveNumber(
() => 5
).AsDouble() == 5d
);
}
[Fact]
public void DoubleToFloat()
{
Assert.True(
new LiveNumber(
() => (551515155.451d)
).AsFloat() == 551515155.451f
);
}
[Fact]
public void FloatAsDouble()
{
Assert.True(
new LiveNumber(
() => (5.243)
).AsDouble() == 5.243d
);
}
[Fact]
public void AveragesLiveNumbers()
{
var list = new List<int>() { 1, 2, 3 };
var liveAverage = new LiveNumber(() => new AvgOf(list));
var first = liveAverage.AsDouble();
list.Add(4);
Assert.NotEqual(first, liveAverage.AsDouble());
}
}
}
| mit |
mind0n/hive | Cache/Libs/net46/ndp/fx/src/DataWeb/Design/System/Data/EntityModel/Emitters/PropertyEmitterBase.cs | 4022 | //---------------------------------------------------------------------
// <copyright file="PropertyEmitterBase.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System.CodeDom;
using System.Data.Metadata.Edm;
using System.Data.Services.Design;
using System.Diagnostics;
namespace System.Data.EntityModel.Emitters
{
internal abstract class PropertyEmitterBase : MetadataItemEmitter
{
private bool _declaringTypeUsesStandardBaseType;
protected PropertyEmitterBase(ClientApiGenerator generator, MetadataItem item, bool declaringTypeUsesStandardBaseType)
: base(generator, item)
{
Debug.Assert(item != null, "item is null");
_declaringTypeUsesStandardBaseType = declaringTypeUsesStandardBaseType;
}
/// <summary>
/// This is where the derived classes supply their emit logic.
/// </summary>
/// <param name="typeDecl">The CodeDom representation of the type that the property is being added to.</param>
protected abstract void EmitProperty(CodeTypeDeclaration typeDecl);
/// <summary>
/// Validation logic specific to property emitters
/// </summary>
protected override void Validate()
{
VerifyGetterAndSetterAccessibilityCompatability();
Generator.VerifyLanguageCaseSensitiveCompatibilityForProperty(Item as EdmMember);
}
/// <summary>
/// The compiler ensures accessibility on a Setter/Getter is more restrictive than on the Property.
/// However accessibility modifiers are not well ordered. Internal and Protected don't go well together
/// because neither is more restrictive than others.
/// </summary>
private void VerifyGetterAndSetterAccessibilityCompatability()
{
if (PropertyEmitter.GetGetterAccessibility(Item) == MemberAttributes.Assembly
&& PropertyEmitter.GetSetterAccessibility(Item) == MemberAttributes.Family)
{
Generator.AddError(Strings.GeneratedPropertyAccessibilityConflict(Item.Name, "Internal", "Protected"),
ModelBuilderErrorCode.GeneratedPropertyAccessibilityConflict,
EdmSchemaErrorSeverity.Error);
}
else if (PropertyEmitter.GetGetterAccessibility(Item) == MemberAttributes.Family
&& PropertyEmitter.GetSetterAccessibility(Item) == MemberAttributes.Assembly)
{
Generator.AddError(Strings.GeneratedPropertyAccessibilityConflict(Item.Name, "Protected", "Internal"),
ModelBuilderErrorCode.GeneratedPropertyAccessibilityConflict,
EdmSchemaErrorSeverity.Error);
}
}
/// <summary>
/// Main method for Emitting property code.
/// </summary>
/// <param name="typeDecl">The CodeDom representation of the type that the property is being added to.</param>
public void Emit(CodeTypeDeclaration typeDecl)
{
Validate();
EmitProperty(typeDecl);
}
protected bool AncestorClassDefinesName(string name)
{
if (_declaringTypeUsesStandardBaseType && Utils.DoesTypeReserveMemberName(Item.DeclaringType, name, Generator.LanguageAppropriateStringComparer))
{
return true;
}
StructuralType baseType = Item.DeclaringType.BaseType as StructuralType;
if (baseType != null && baseType.Members.Contains(name))
{
return true;
}
return false;
}
public new EdmMember Item
{
get
{
return base.Item as EdmMember;
}
}
}
}
| mit |
apo-j/Projects_Working | S/SOURCE/SOURCE.Common/SOURCE.Domaine/Results/SelectionResult.cs | 1175 | using System;
using System.Runtime.Serialization;
namespace SOURCE.Domaine.Results
{
public partial class SelectionResult
{
public long SelectionID { get; set; }
public long? RechercheID { get; set; }
public string SelectionLibelle { get; set;}
public long SelectionElementID { get; set; }
public long IntervenantID { get; set; }
public string Commentaire { get; set; }
public string IntervenantNom { get; set; }
public string IntervenantRoles { get; set; }
public string IntervenantEmail { get; set; }
public decimal? TarifForceeAuditeur { get; set; }
public decimal? TarifForceeRA { get; set; }
public long? DeviseID { get; set; }
public bool ASuperviser { get; set; }
public bool ReaForce { get; set; }
public string EtatPreservation { get; set; }
public string ToolTip { get; set; }
public bool Remplacant { get; set; }
public bool NonRetenu { get; set; }
public DateTime? DateEnvoiPreReservation { get; set; }
public string CommentairePreReservation { get; set; }
}
}
| mit |
lewischeng-ms/WebApi | OData/test/E2ETest/WebStack.QA.Test.OData/Common/LinkRoutingConvention2.cs | 3802 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Linq;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.OData.Routing;
using System.Web.OData.Routing.Conventions;
using Microsoft.OData.Edm;
using Microsoft.OData.UriParser;
using ODataPath = System.Web.OData.Routing.ODataPath;
namespace WebStack.QA.Test.OData.Common
{
public class LinkRoutingConvention2 : EntitySetRoutingConvention
{
public override string SelectAction(ODataPath odataPath, HttpControllerContext controllerContext, ILookup<string, HttpActionDescriptor> actionMap)
{
if (odataPath == null)
{
throw new ArgumentNullException("odataPath");
}
if (controllerContext == null)
{
throw new ArgumentNullException("controllerContext");
}
if (actionMap == null)
{
throw new ArgumentNullException("actionMap");
}
HttpMethod requestMethod = controllerContext.Request.Method;
if (odataPath.PathTemplate == "~/entityset/key/navigation/$ref"
|| odataPath.PathTemplate == "~/entityset/key/cast/navigation/$ref"
|| odataPath.PathTemplate == "~/entityset/key/navigation/key/$ref"
|| odataPath.PathTemplate == "~/entityset/key/cast/navigation/key/$ref")
{
var actionName = string.Empty;
if ((requestMethod == HttpMethod.Post) || (requestMethod == HttpMethod.Put))
{
actionName += "CreateRefTo";
}
else if (requestMethod == HttpMethod.Delete)
{
actionName += "DeleteRefTo";
}
else
{
return null;
}
var navigationSegment = odataPath.Segments.OfType<NavigationPropertyLinkSegment>().Last();
actionName += navigationSegment.NavigationProperty.Name;
var castSegment = odataPath.Segments[2] as TypeSegment;
if (castSegment != null)
{
IEdmType elementType = castSegment.EdmType;
if (castSegment.EdmType.TypeKind == EdmTypeKind.Collection)
{
elementType = ((IEdmCollectionType)castSegment.EdmType).ElementType.Definition;
}
var actionCastName = string.Format("{0}On{1}", actionName, ((IEdmEntityType)elementType).Name);
if (actionMap.Contains(actionCastName))
{
AddLinkInfoToRouteData(controllerContext, odataPath);
return actionCastName;
}
}
if (actionMap.Contains(actionName))
{
AddLinkInfoToRouteData(controllerContext, odataPath);
return actionName;
}
}
return null;
}
private static void AddLinkInfoToRouteData(HttpControllerContext controllerContext, ODataPath odataPath)
{
KeySegment keyValueSegment = odataPath.Segments.OfType<KeySegment>().First();
controllerContext.AddKeyValueToRouteData(keyValueSegment);
KeySegment relatedKeySegment = odataPath.Segments.Last() as KeySegment;
if (relatedKeySegment != null)
{
controllerContext.AddKeyValueToRouteData(relatedKeySegment, ODataRouteConstants.RelatedKey);
}
}
}
}
| mit |
geocre/geocre | controllers/page.php | 56779 | <?php
if(!defined('IN_INDEX')) exit;
define('DEFAULT_PAGE_SUBTEMPLATE', 'default.inc.tpl');
$settings['project_thumbnail_width'] = 170;
$settings['project_thumbnail_height'] = 170;
$settings['project_thumbnail_quality'] = 80;
$settings['page_image_width'] = 380;
$settings['page_image_height'] = 285;
$settings['page_image_quality'] = 85;
$settings['project_photo_width'] = 900;
$settings['project_photo_height'] = 800;
$settings['project_photo_quality'] = 85;
//$settings['page_teaser_auto_truncate'] = 385;
function get_uploaded_image($upload, $directory, $height, $width, $mode='inset', $quality=85)
{
if(isset($_FILES[$upload]) && is_uploaded_file($_FILES[$upload]['tmp_name']))
{
if($_FILES[$upload]['error']) $errors[] = 'error_photo_upload';
if(empty($errors))
{
$upload_info = getimagesize($_FILES[$upload]['tmp_name']);
if($upload_info[2]!=IMAGETYPE_JPEG && $upload_info[2]!=IMAGETYPE_JPEG2000 && $upload_info[2]!=IMAGETYPE_PNG && $upload_info[2]!=IMAGETYPE_GIF) $errors[] = 'error_photo_invalid_file_type';
}
if(empty($errors))
{
$filename = gmdate("YmdHis").uniqid();
if($upload_info[2]==IMAGETYPE_PNG) $extension = 'png';
elseif($upload_info[2]==IMAGETYPE_GIF) $extension = 'gif';
else $extension = 'jpg';
$image_info['file'] = $filename . '.' . $extension;
$imagine = new Imagine\Gd\Imagine();
$image = $imagine->open($_FILES[$upload]['tmp_name']);
$image_options = array('quality' => $quality);
$image_size = new Imagine\Image\Box($width, $height);
if($mode=='inset') $image_mode = Imagine\Image\ImageInterface::THUMBNAIL_INSET;
else $image_mode = Imagine\Image\ImageInterface::THUMBNAIL_OUTBOUND;
$image->thumbnail($image_size, $image_mode)->save($directory.$image_info['file'], $image_options);
$saved_image_info = getimagesize($directory.$image_info['file']);
$image_info['width'] = $saved_image_info[0];
$image_info['height'] = $saved_image_info[1];
return $image_info;
}
}
return false;
}
if(isset($_GET['page'])) $action = 'page';
// get available templates:
if($action == 'add' || $action == 'edit' || $action == 'edit_submit')
{
$handle=opendir(BASE_PATH.'templates/subtemplates/pages');
while($file = readdir($handle))
{
if(preg_match('/\.inc\.tpl$/i', $file))
{
$template_file_array[] = $file;
}
}
closedir($handle);
natcasesort($template_file_array);
$i=0;
foreach($template_file_array as $file)
{
$template_files[$i] = $file;
#$template_files[$i]['name'] = htmlspecialchars($file);
$i++;
}
if(isset($template_files))
{
$template->assign('available_subtemplates',$template_files);
}
}
switch($action)
{
case 'page':
if($permission->granted(Permission::PAGE_MANAGEMENT)) $min_status = 0;
elseif($permission->granted(Permission::USER)) $min_status = 1;
else $min_status = 2;
$dbr = Database::$connection->prepare("SELECT a.id,
a.identifier,
a.title,
a.title_as_headline,
a.content,
a.location,
a.custom_date,
a.contact_name,
a.contact_email,
a.page_image,
a.page_image_width,
a.page_image_height,
a.page_image_caption,
a.status,
a.sidebar_title,
a.sidebar_text,
a.sidebar_link,
a.sidebar_linktext,
a.page_info_title,
a.subtemplate,
a.menu,
a.tv,
b.identifier AS parent_identifier,
b.title AS parent_title
FROM ".Database::$db_settings['pages_table']." AS a
LEFT JOIN ".Database::$db_settings['pages_table']." AS b ON a.parent=b.id
WHERE lower(a.identifier)=lower(:identifier) AND a.status>=:min_status
LIMIT 1");
$dbr->bindParam(':identifier', $_GET['page'], PDO::PARAM_STR);
$dbr->bindParam(':min_status', $min_status, PDO::PARAM_INT);
$dbr->execute();
$row = $dbr->fetch();
if(isset($row['id']))
{
$page['id'] = intval($row['id']);
$page['title'] = htmlspecialchars($row['title']);
$page['title_as_headline'] = $row['title_as_headline'];
$page['custom_date'] = htmlspecialchars($row['custom_date']);
$page['location'] = htmlspecialchars($row['location']);
$page['contact_name'] = htmlspecialchars($row['contact_name']);
$page['contact_email'] = htmlspecialchars($row['contact_email']);
$page['content'] = $row['content'];
$page['status'] = $row['status'];
$page['sidebar_title'] = htmlspecialchars($row['sidebar_title']);
$page['sidebar_text'] = $row['sidebar_text'];
$page['sidebar_link'] = htmlspecialchars($row['sidebar_link']);
$page['sidebar_linktext'] = htmlspecialchars($row['sidebar_linktext']);
$page['page_info_title'] = htmlspecialchars($row['page_info_title']);
$page['subtemplate'] = $row['subtemplate'];
$page['menu'] = htmlspecialchars($row['menu']);
if($tv = extract_tvs($row['tv'])) $template->assign('tv', $tv);
$page['parent_identifier'] = htmlspecialchars($row['parent_identifier']);
$page['parent_title'] = htmlspecialchars($row['parent_title']);
if($row['page_image'])
{
$page['page_image']['file'] = htmlspecialchars($row['page_image']);
$page['page_image']['width'] = intval($row['page_image_width']);
$page['page_image']['height'] = intval($row['page_image_height']);
$page['page_image']['caption'] = htmlspecialchars($row['page_image_caption']);
}
$template->assign('page', $page);
$template->assign('current_page', $row['identifier']);
$template->assign('subtitle', htmlspecialchars($row['title']));
if($permission->granted(Permission::PAGE_MANAGEMENT) || $page['sidebar_title'] || $page['page_info_title']) $template->assign('sidebar', true);
else $template->assign('sidebar', false);
// get sub pages:
if($permission->granted(Permission::USER)) $min_status = 1;
else $min_status = 2;
$dbr = Database::$connection->prepare("SELECT id,
identifier,
title
FROM ".Database::$db_settings['pages_table']."
WHERE status>=:min_status AND parent=:id
ORDER BY sequence ASC");
$dbr->bindParam(':id', $page['id'], PDO::PARAM_INT);
$dbr->bindParam(':min_status', $min_status, PDO::PARAM_INT);
$dbr->execute();
$i=0;
while($row = $dbr->fetch())
{
$sub_pages[$i]['id'] = $row['id'];
$sub_pages[$i]['identifier'] = htmlspecialchars($row['identifier']);
$sub_pages[$i]['title'] = htmlspecialchars($row['title']);
++$i;
}
if(isset($sub_pages)) $template->assign('sub_pages', $sub_pages);
// get project data:
if($permission->granted(Permission::DATA_MANAGEMENT))
{
$data_query = 'SELECT id, table_name, title, type, status
FROM '.Database::$db_settings['data_models_table'].'
WHERE status>0 AND parent_table=0 AND project=:project
ORDER BY sequence ASC';
}
else
{
if($items = $permission->get_list(Permission::DATA_ACCESS))
{
$items_list = implode(', ', $items);
$data_query = 'SELECT id, table_name, title, type, status
FROM '.Database::$db_settings['data_models_table'].'
WHERE status>0 AND parent_table=0 AND project=:project AND id IN ('.$items_list.')
ORDER BY sequence ASC';
}
}
if(isset($data_query))
{
$dbr = Database::$connection->prepare($data_query);
$dbr->bindParam(':project', $page['id'], PDO::PARAM_INT);
$dbr->execute();
$i=0;
while($row = $dbr->fetch())
{
$data[$i]['id'] = $row['id'];
$data[$i]['title'] = htmlspecialchars($row['title']);
$data[$i]['type'] = intval($row['type']);
$data[$i]['status'] = intval($row['status']);
++$i;
}
if(isset($data)) $template->assign('data', $data);
}
// get photos:
$dbr = Database::$connection->prepare("SELECT id, filename, thumbnail_width, thumbnail_height, title, description, author FROM ".$db_settings['page_photos_table']." WHERE page=:page ORDER by sequence ASC");
$dbr->bindParam(':page', $page['id'], PDO::PARAM_INT);
$dbr->execute();
$i=0;
while($row = $dbr->fetch())
{
$photos[$i]['id'] = $row['id'];
$photos[$i]['filename'] = htmlspecialchars($row['filename']);
$photos[$i]['thumbnail_width'] = intval($row['thumbnail_width']);
$photos[$i]['thumbnail_height'] = intval($row['thumbnail_height']);
$photos[$i]['title'] = htmlspecialchars($row['title']);
$photos[$i]['description'] = htmlspecialchars($row['description']);
if($row['author']) $photos[$i]['author'] = str_replace('[author]', htmlspecialchars($row['author']), $lang['page_photo_author_declaration']);
else $photos[$i]['author'] = '';
++$i;
}
$template->assign('number_of_photos', $i);
if(isset($photos))
{
$template->assign('photos', $photos);
#$javascripts[] = HAMMER;
$javascripts[] = LIGHTBOX;
}
if($permission->granted(Permission::PAGE_MANAGEMENT))
{
$javascripts[] = JQUERY_UI;
$javascripts[] = JQUERY_UI_HANDLER;
$stylesheets[] = JQUERY_UI_CSS;
}
$granted_permissions['page_management'] = $permission->granted(Permission::PAGE_MANAGEMENT) ? true : false;
$template->assign('permission', $granted_permissions);
if($page['subtemplate']) $template->assign('subtemplate', 'pages/'.$page['subtemplate']);
else $template->assign('subtemplate', 'subtemplates/'.DEFAULT_PAGE_SUBTEMPLATE);
}
else $http_status=404;
break;
case 'add':
// parent pages:
$dbr = Database::$connection->prepare("SELECT id, title FROM ".$db_settings['pages_table']." ORDER BY sequence ASC");
$dbr->execute();
if($dbr->rowCount()>1)
{
$i=0;
while($row = $dbr->fetch())
{
$parent_pages[$i]['id'] = intval($row['id']);
$parent_pages[$i]['title'] = htmlspecialchars($row['title']);
++$i;
}
if(isset($parent_pages)) $template->assign('parent_pages', $parent_pages);
}
$page['title_as_headline'] = true;
$page['subtemplate'] = DEFAULT_PAGE_SUBTEMPLATE;
$page['status'] = 0;
$template->assign('page', $page);
$template->assign('subtitle', $lang['page_add_subtitle']);
$template->assign('subtemplate', 'page.edit.inc.tpl');
$javascripts[] = JQUERY_UI;
$javascripts[] = JQUERY_UI_HANDLER;
if(empty($_REQUEST['disable_wysiwyg']))
{
$template->assign('wysiwyg', true);
$javascripts[] = WYSIWYG_EDITOR;
$javascripts[] = STATIC_URL.'js/edit_page_wysiwyg_init.js';
}
else
{
$template->assign('wysiwyg', false);
}
break;
case 'edit':
if(isset($_GET['id']) && $permission->granted(Permission::PAGE_MANAGEMENT))
{
$dbr = Database::$connection->prepare("SELECT id, title, title_as_headline, identifier, teaser_supertitle, teaser_title, teaser_text, teaser_linktext, content, location, custom_date, contact_name, contact_email, teaser_image, teaser_image_width, teaser_image_height, page_image, page_image_width, page_image_height, page_image_caption, status, index, news, project, sidebar_title, sidebar_text, sidebar_link, sidebar_linktext, page_info_title, parent, subtemplate, menu, tv FROM ".$db_settings['pages_table']." WHERE id=:id LIMIT 1");
$dbr->bindParam(':id', $_GET['id'], PDO::PARAM_INT);
$dbr->execute();
$row = $dbr->fetch();
if(isset($row['id']))
{
$action = 'edit';
$page['id'] = $row['id'];
$page['title'] = htmlspecialchars($row['title']);
$page['title_as_headline'] = $row['title_as_headline'];
$page['identifier'] = htmlspecialchars($row['identifier']);
$page['teaser_supertitle'] = htmlspecialchars($row['teaser_supertitle']);
$page['teaser_title'] = htmlspecialchars($row['teaser_title']);
$page['teaser_text'] = htmlspecialchars($row['teaser_text']);
$page['teaser_linktext'] = htmlspecialchars($row['teaser_linktext']);
$page['content'] = htmlspecialchars($row['content']);
$page['location'] = htmlspecialchars($row['location']);
$page['custom_date'] = htmlspecialchars($row['custom_date']);
$page['contact_name'] = htmlspecialchars($row['contact_name']);
$page['contact_email'] = htmlspecialchars($row['contact_email']);
$page['teaser_image'] = $row['teaser_image'];
$page['teaser_image_width'] = $row['teaser_image_width'];
$page['teaser_image_height'] = $row['teaser_image_height'];
$page['page_image'] = $row['page_image'];
$page['page_image_width'] = $row['page_image_width'];
$page['page_image_height'] = $row['page_image_height'];
$page['page_image_caption'] = htmlspecialchars($row['page_image_caption']);
$page['status'] = intval($row['status']);
$page['index'] = $row['index'];
$page['news'] = $row['news'];
$page['project'] = $row['project'];
$page['sidebar_title'] = htmlspecialchars($row['sidebar_title']);
$page['sidebar_text'] = htmlspecialchars($row['sidebar_text']);
$page['sidebar_link'] = htmlspecialchars($row['sidebar_link']);
$page['sidebar_linktext'] = htmlspecialchars($row['sidebar_linktext']);
$page['page_info_title'] = htmlspecialchars($row['page_info_title']);
$page['parent'] = $row['parent'];
$page['subtemplate'] = htmlspecialchars($row['subtemplate']);
$page['menu'] = htmlspecialchars($row['menu']);
$page['tv'] = str_replace(',',', ',htmlspecialchars($row['tv']));
$template->assign('page', $page);
$template->assign('subtitle', $lang['page_edit_subtitle']);
$template->assign('subtemplate', 'page.edit.inc.tpl');
//$javascripts[] = JQUERY_UI;
//$javascripts[] = JQUERY_UI_HANDLER;
if(empty($_REQUEST['disable_wysiwyg']))
{
$template->assign('wysiwyg', true);
$javascripts[] = WYSIWYG_EDITOR;
$javascripts[] = STATIC_URL.'js/edit_page_wysiwyg_init.js';
}
else
{
$template->assign('wysiwyg', false);
}
// parent pages:
$dbr = Database::$connection->prepare("SELECT id, title FROM ".$db_settings['pages_table']." WHERE id!=:id ORDER BY sequence ASC");
$dbr->bindParam(':id', $row['id'], PDO::PARAM_INT);
$dbr->execute();
if($dbr->rowCount()>1)
{
$i=0;
while($row = $dbr->fetch())
{
$parent_pages[$i]['id'] = intval($row['id']);
$parent_pages[$i]['title'] = htmlspecialchars($row['title']);
++$i;
}
if(isset($parent_pages)) $template->assign('parent_pages', $parent_pages);
}
}
}
break;
case 'edit_submit':
if($permission->granted(Permission::PAGE_MANAGEMENT))
{
// get posted data:
$title = isset($_POST['title']) ? trim($_POST['title']) : '';
$title_as_headline = isset($_POST['title_as_headline']) ? true : false;
$identifier = isset($_POST['identifier']) ? trim($_POST['identifier']) : '';
$content = isset($_POST['content']) ? trim($_POST['content']) : '';
$custom_date = isset($_POST['custom_date']) ? trim($_POST['custom_date']) : '';
$location = isset($_POST['location']) ? trim($_POST['location']) : '';
$contact_name = isset($_POST['contact_name']) ? trim($_POST['contact_name']) : '';
$contact_email = isset($_POST['contact_email']) ? trim($_POST['contact_email']) : '';
$status = isset($_POST['status']) ? intval($_POST['status']) : 0;
$index = isset($_POST['index']) ? true : false;
$news = isset($_POST['news']) ? true : false;
$project = isset($_POST['project']) ? true : false;
$teaser_supertitle = isset($_POST['teaser_supertitle']) ? trim($_POST['teaser_supertitle']) : '';
$teaser_title = isset($_POST['teaser_title']) ? trim($_POST['teaser_title']) : '';
$teaser_text = isset($_POST['teaser_text']) ? trim($_POST['teaser_text']) : '';
$teaser_linktext = isset($_POST['teaser_linktext']) ? trim($_POST['teaser_linktext']) : '';
$delete_teaser_image = isset($_POST['delete_teaser_image']) && $_POST['delete_teaser_image'] ? true : false;
$page_image_caption = isset($_POST['page_image_caption']) ? trim($_POST['page_image_caption']) : '';
$delete_page_image = isset($_POST['delete_page_image']) && $_POST['delete_page_image'] ? true : false;
$sidebar_title = isset($_POST['sidebar_title']) ? trim($_POST['sidebar_title']) : '';
$sidebar_text = isset($_POST['sidebar_text']) ? trim($_POST['sidebar_text']) : '';
$sidebar_link = isset($_POST['sidebar_link']) ? trim($_POST['sidebar_link']) : '';
$sidebar_linktext = isset($_POST['sidebar_linktext']) ? trim($_POST['sidebar_linktext']) : '';
$page_info_title = isset($_POST['page_info_title']) ? trim($_POST['page_info_title']) : '';
$parent = isset($_POST['parent']) ? intval($_POST['parent']) : 0;
$subtemplate = isset($_POST['subtemplate']) ? trim($_POST['subtemplate']) : '';
$menu = isset($_POST['menu']) && $_POST['menu'] ? trim($_POST['menu']) : NULL;
if(isset($_POST['tv']) && trim($_POST['tv']))
{
$tv_array = explode(',', $_POST['tv']);
foreach($tv_array as $item)
{
if(trim($item)!='')
{
$cleared_tv_array[] = trim($item);
}
}
if(isset($cleared_tv_array)) $tv = implode(',', $cleared_tv_array);
else $tv = NULL;
}
else $tv = NULL;
// chacke data:
if(empty($title)) $errors[] = 'error_no_title';
if(empty($identifier)) $errors[] = 'error_no_identifier';
elseif(!preg_match(VALID_URL_CHARACTERS, $identifier)) $errors[] = 'error_page_identifier_invalid';
else
{
// check if identifier already exists:
if(isset($_POST['id'])) $id_exclusion_query = ' AND id != '.intval($_POST['id']);
else $id_exclusion_query = '';;
$dbr = Database::$connection->prepare("SELECT COUNT(*)
FROM ".Database::$db_settings['pages_table']."
WHERE LOWER(identifier)=LOWER(:identifier)".$id_exclusion_query);
$dbr->bindParam(':identifier', $_POST['identifier'], PDO::PARAM_STR);
$dbr->execute();
list($count) = $dbr->fetch();
if($count>0) $errors[] = 'error_page_identifier_exists';
}
if(empty($errors))
{
spl_autoload_register('imagineLoader');
$teaser_image = get_uploaded_image('teaser_image', PAGE_TEASER_IMAGES_PATH, $settings['project_thumbnail_height'], $settings['project_thumbnail_width'], 'outbound', $settings['project_thumbnail_quality']);
$page_image = get_uploaded_image('page_image', PAGE_IMAGES_PATH, $settings['page_image_height'], $settings['page_image_width'], 'inset', $settings['page_image_quality']);
if(isset($_POST['id'])) // edit;
{
// get current teaser image:
$del_dbr = Database::$connection->prepare("SELECT teaser_image, page_image FROM ".$db_settings['pages_table']." WHERE id=:id LIMIT 1");
$del_dbr->bindParam(':id', $_POST['id'], PDO::PARAM_INT);
$del_dbr->execute();
$row = $del_dbr->fetch();
if($row['teaser_image']) $old_teaser_image = $row['teaser_image'];
if($row['page_image']) $old_page_image = $row['page_image'];
// update record:
$dbr = Database::$connection->prepare("UPDATE ".$db_settings['pages_table']." SET last_editor=:last_editor, last_edited=NOW(), title=:title, title_as_headline=:title_as_headline, identifier=:identifier, teaser_supertitle=:teaser_supertitle, teaser_title=:teaser_title, teaser_text=:teaser_text, teaser_linktext=:teaser_linktext, content=:content, location=:location, custom_date=:custom_date, contact_name=:contact_name, contact_email=:contact_email, page_image_caption=:page_image_caption, status=:status, index=:index, news=:news, project=:project, sidebar_title=:sidebar_title, sidebar_text=:sidebar_text, sidebar_link=:sidebar_link, sidebar_linktext=:sidebar_linktext, page_info_title=:page_info_title, parent=:parent, subtemplate=:subtemplate, menu=:menu, tv=:tv WHERE id=:id");
$dbr->bindParam(':id', $_POST['id'], PDO::PARAM_INT);
$dbr->bindParam(':last_editor', $_SESSION[$settings['session_prefix'].'auth']['id'], PDO::PARAM_INT);
$dbr->bindParam(':title', $title, PDO::PARAM_STR);
$dbr->bindParam(':title_as_headline', $title_as_headline, PDO::PARAM_BOOL);
$dbr->bindParam(':identifier', $identifier, PDO::PARAM_STR);
$dbr->bindParam(':location', $location, PDO::PARAM_STR);
$dbr->bindParam(':custom_date', $custom_date, PDO::PARAM_STR);
$dbr->bindParam(':contact_name', $contact_name, PDO::PARAM_STR);
$dbr->bindParam(':contact_email', $contact_email, PDO::PARAM_STR);
$dbr->bindParam(':teaser_supertitle', $teaser_supertitle, PDO::PARAM_STR);
$dbr->bindParam(':teaser_title', $teaser_title, PDO::PARAM_STR);
$dbr->bindParam(':teaser_text', $teaser_text, PDO::PARAM_STR);
$dbr->bindParam(':teaser_linktext', $teaser_linktext, PDO::PARAM_STR);
$dbr->bindParam(':content', $content, PDO::PARAM_STR);
$dbr->bindParam(':status', $status, PDO::PARAM_STR);
$dbr->bindParam(':index', $index, PDO::PARAM_BOOL);
$dbr->bindParam(':news', $news, PDO::PARAM_BOOL);
$dbr->bindParam(':project', $project, PDO::PARAM_BOOL);
$dbr->bindParam(':page_image_caption', $page_image_caption, PDO::PARAM_STR);
$dbr->bindParam(':sidebar_title', $sidebar_title, PDO::PARAM_STR);
$dbr->bindParam(':sidebar_text', $sidebar_text, PDO::PARAM_STR);
$dbr->bindParam(':sidebar_link', $sidebar_link, PDO::PARAM_STR);
$dbr->bindParam(':sidebar_linktext', $sidebar_linktext, PDO::PARAM_STR);
$dbr->bindParam(':page_info_title', $page_info_title, PDO::PARAM_STR);
$dbr->bindParam(':parent', $parent, PDO::PARAM_INT);
$dbr->bindParam(':subtemplate', $subtemplate, PDO::PARAM_STR);
if($menu) $dbr->bindParam(':menu', $menu, PDO::PARAM_STR);
else $dbr->bindValue(':menu', NULL, PDO::PARAM_NULL);
if($tv) $dbr->bindParam(':tv', $tv, PDO::PARAM_STR);
else $dbr->bindValue(':tv', NULL, PDO::PARAM_NULL);
$dbr->execute();
$id = intval($_POST['id']);
/*if(isset($_POST['project_order']))
{
$project_order_array = explode(',', $_POST['project_order']);
foreach($project_order_array as $project_order_item)
{
$cleared_project_order_item = intval(str_replace('item_', '', $project_order_item));
if($cleared_project_order_item>0) $validated_project_order_array[] = $cleared_project_order_item;
}
if(isset($validated_project_order_array))
{
$dbr = Database::$connection->prepare("UPDATE ".$db_settings['pages_table']." SET sequence=:sequence WHERE id=:id");
$dbr->bindParam(':sequence', $sequence, PDO::PARAM_INT);
$dbr->bindParam(':id', $pid, PDO::PARAM_INT);
Database::$connection->beginTransaction();
$sequence = 1;
foreach($validated_project_order_array as $pid)
{
$dbr->execute();
++$sequence;
}
Database::$connection->commit();
}
}*/
}
else // add
{
// determine sequence:
#$dbr = Database::$connection->prepare("SELECT sequence FROM ".$db_settings['pages_table']." ORDER BY sequence DESC LIMIT 1");
#$dbr->execute();
#$row = $dbr->fetch();
#if(isset($row['sequence'])) $new_sequence = $row['sequence'] + 1;
#else $new_sequence = 1;
// save record:
$dbr = Database::$connection->prepare("INSERT INTO ".Database::$db_settings['pages_table']." (creator, created, sequence, title, title_as_headline, identifier, teaser_supertitle, teaser_title, teaser_text, teaser_linktext, content, location, custom_date, contact_name, contact_email, page_image_caption, status, index, news, project, sidebar_title, sidebar_text, sidebar_link, sidebar_linktext, page_info_title, parent, subtemplate, menu, tv) VALUES (:creator, NOW(), :sequence, :title, :title_as_headline, :identifier, :teaser_supertitle, :teaser_title, :teaser_text, :teaser_linktext, :content, :location, :custom_date, :contact_name, :contact_email, :page_image_caption, :status, :index, :news, :project, :sidebar_title, :sidebar_text, :sidebar_link, :sidebar_linktext, :page_info_title, :parent, :subtemplate, :menu, :tv)");
#$dbr->bindParam(':sequence', $new_sequence, PDO::PARAM_INT);
$dbr->bindParam(':creator', $_SESSION[$settings['session_prefix'].'auth']['id'], PDO::PARAM_INT);
$dbr->bindValue(':sequence', 1, PDO::PARAM_INT);
$dbr->bindParam(':title', $title, PDO::PARAM_STR);
$dbr->bindParam(':title_as_headline', $title_as_headline, PDO::PARAM_BOOL);
$dbr->bindParam(':identifier', $identifier, PDO::PARAM_STR);
$dbr->bindParam(':location', $location, PDO::PARAM_STR);
$dbr->bindParam(':custom_date', $custom_date, PDO::PARAM_STR);
$dbr->bindParam(':contact_name', $contact_name, PDO::PARAM_STR);
$dbr->bindParam(':contact_email', $contact_email, PDO::PARAM_STR);
$dbr->bindParam(':teaser_supertitle', $teaser_supertitle, PDO::PARAM_STR);
$dbr->bindParam(':teaser_title', $teaser_title, PDO::PARAM_STR);
$dbr->bindParam(':teaser_text', $teaser_text, PDO::PARAM_STR);
$dbr->bindParam(':teaser_linktext', $teaser_linktext, PDO::PARAM_STR);
$dbr->bindParam(':content', $content, PDO::PARAM_STR);
$dbr->bindParam(':status', $status, PDO::PARAM_STR);
$dbr->bindParam(':index', $index, PDO::PARAM_BOOL);
$dbr->bindParam(':news', $news, PDO::PARAM_BOOL);
$dbr->bindParam(':project', $project, PDO::PARAM_BOOL);
$dbr->bindParam(':page_image_caption', $page_image_caption, PDO::PARAM_STR);
$dbr->bindParam(':sidebar_title', $sidebar_title, PDO::PARAM_STR);
$dbr->bindParam(':sidebar_text', $sidebar_text, PDO::PARAM_STR);
$dbr->bindParam(':sidebar_link', $sidebar_link, PDO::PARAM_STR);
$dbr->bindParam(':sidebar_linktext', $sidebar_linktext, PDO::PARAM_STR);
$dbr->bindParam(':page_info_title', $page_info_title, PDO::PARAM_STR);
$dbr->bindParam(':parent', $parent, PDO::PARAM_INT);
$dbr->bindParam(':subtemplate', $subtemplate, PDO::PARAM_STR);
if($menu) $dbr->bindParam(':menu', $menu, PDO::PARAM_STR);
else $dbr->bindValue(':menu', NULL, PDO::PARAM_NULL);
if($tv) $dbr->bindParam(':tv', $tv, PDO::PARAM_STR);
else $dbr->bindValue(':tv', NULL, PDO::PARAM_NULL);
$dbr->execute();
$dbr = Database::$connection->query(LAST_INSERT_ID_QUERY);
list($id) = $dbr->fetch();
// reorder...
$dbr = Database::$connection->prepare("SELECT id FROM ".Database::$db_settings['pages_table']." WHERE id!=:id ORDER BY sequence ASC");
$dbr->bindParam(':id', $id, PDO::PARAM_INT);
$dbr->execute();
$i=2;
while($row2 = $dbr->fetch())
{
$dbr2 = Database::$connection->prepare("UPDATE ".Database::$db_settings['pages_table']." SET sequence=:sequence WHERE id=:id");
$dbr2->bindValue(':sequence', $i, PDO::PARAM_INT);
$dbr2->bindValue(':id', $row2['id'], PDO::PARAM_INT);
$dbr2->execute();
++$i;
}
}
// update teaser image:
if($teaser_image || $delete_teaser_image)
{
$dbr = Database::$connection->prepare("UPDATE ".$db_settings['pages_table']." SET teaser_image=:teaser_image, teaser_image_width=:teaser_image_width, teaser_image_height=:teaser_image_height WHERE id=:id");
$dbr->bindParam(':id', $id, PDO::PARAM_INT);
if($teaser_image)
{
$dbr->bindParam(':teaser_image', $teaser_image['file'], PDO::PARAM_STR);
$dbr->bindParam(':teaser_image_width', $teaser_image['width'], PDO::PARAM_INT);
$dbr->bindParam(':teaser_image_height', $teaser_image['height'], PDO::PARAM_INT);
}
else
{
$dbr->bindValue(':teaser_image', NULL, PDO::PARAM_NULL);
$dbr->bindValue(':teaser_image_width', NULL, PDO::PARAM_NULL);
$dbr->bindValue(':teaser_image_height', NULL, PDO::PARAM_NULL);
}
$dbr->execute();
// delete old teaser image:
if($old_teaser_image) @unlink(PAGE_TEASER_IMAGES_PATH.$old_teaser_image);
}
// update project image:
if($page_image || $delete_page_image)
{
$dbr = Database::$connection->prepare("UPDATE ".$db_settings['pages_table']." SET page_image=:page_image, page_image_width=:page_image_width, page_image_height=:page_image_height WHERE id=:id");
$dbr->bindParam(':id', $id, PDO::PARAM_INT);
if($page_image)
{
$dbr->bindParam(':page_image', $page_image['file'], PDO::PARAM_STR);
$dbr->bindParam(':page_image_width', $page_image['width'], PDO::PARAM_INT);
$dbr->bindParam(':page_image_height', $page_image['height'], PDO::PARAM_INT);
}
else
{
$dbr->bindValue(':page_image', NULL, PDO::PARAM_NULL);
$dbr->bindValue(':page_image_width', NULL, PDO::PARAM_NULL);
$dbr->bindValue(':page_image_height', NULL, PDO::PARAM_NULL);
}
$dbr->execute();
// delete old teaser image:
if($old_page_image) @unlink(PAGE_IMAGES_PATH.$old_page_image);
}
header('Location: '.BASE_URL.$identifier);
exit;
} // if(empty($errors))
else
{
foreach($_POST as $key=>$val)
{
$page[$key] = htmlspecialchars($val);
}
$template->assign('page', $page);
$template->assign('project', $project);
$template->assign('errors', $errors);
$template->assign('subtitle', $lang['page_edit_subtitle']);
$template->assign('subtemplate', 'page.edit.inc.tpl');
$javascripts[] = JQUERY_UI;
$javascripts[] = JQUERY_UI_HANDLER;
if(empty($_REQUEST['disable_wysiwyg']))
{
$template->assign('wysiwyg', true);
$javascripts[] = WYSIWYG_EDITOR;
$javascripts[] = STATIC_URL.'js/edit_page_wysiwyg_init.js';
}
else
{
$template->assign('wysiwyg', false);
}
}
}
break;
case 'delete':
if(isset($_GET['id']) && $permission->granted(Permission::PAGE_MANAGEMENT))
{
$dbr = Database::$connection->prepare("SELECT id, title, identifier FROM ".$db_settings['pages_table']." WHERE id=:id LIMIT 1");
$dbr->bindParam(':id', $_GET['id'], PDO::PARAM_INT);
$dbr->execute();
$row = $dbr->fetch();
if(isset($row['id']))
{
$page['id'] = $row['id'];
$page['identifier'] = htmlspecialchars($row['identifier']);
$page['title'] = htmlspecialchars($row['title']);
$template->assign('page', $page);
$template->assign('subtitle', $lang['page_delete_subtitle']);
if(isset($_GET['failure'])) $template->assign('failure', htmlspecialchars($_GET['failure']));
$template->assign('subtemplate', 'page.delete.inc.tpl');
}
}
break;
case 'delete_submit':
if(isset($_POST['pw']) && isset($_REQUEST['id']) && $permission->granted(Permission::PAGE_MANAGEMENT))
{
// check password:
$dbr = Database::$connection->prepare("SELECT pw FROM ".Database::$db_settings['userdata_table']." WHERE id=:id LIMIT 1");
$dbr->bindParam(':id', $_SESSION[$settings['session_prefix'].'auth']['id']);
$dbr->execute();
list($pw) = $dbr->fetch();
if(check_pw($_POST['pw'], $pw))
{
$dbr = Database::$connection->prepare("SELECT id, teaser_image, page_image FROM ".$db_settings['pages_table']." WHERE id=:id LIMIT 1");
$dbr->bindParam(':id', $_REQUEST['id'], PDO::PARAM_INT);
$dbr->execute();
$row = $dbr->fetch();
if(isset($row['id']))
{
// delete page:
$dbr = Database::$connection->prepare("DELETE FROM ".$db_settings['pages_table']." WHERE id = :id");
$dbr->bindValue(':id', $_REQUEST['id'], PDO::PARAM_INT);
$dbr->execute();
// reorder...
$dbr = Database::$connection->prepare("SELECT id FROM ".$db_settings['pages_table']." ORDER BY sequence ASC");
$dbr->execute();
$i=1;
while($reorder_row = $dbr->fetch())
{
$dbr2 = Database::$connection->prepare("UPDATE ".$db_settings['pages_table']." SET sequence=:sequence WHERE id=:id");
$dbr2->bindValue(':sequence', $i, PDO::PARAM_INT);
$dbr2->bindValue(':id', $reorder_row['id'], PDO::PARAM_INT);
$dbr2->execute();
++$i;
}
// delete page photos:
@unlink(PAGE_TEASER_IMAGES_PATH.$row['teaser_image']);
@unlink(PAGE_IMAGES_PATH.$row['page_image']);
// delete page photos:
$dbr = Database::$connection->prepare("SELECT filename FROM ".$db_settings['page_photos_table']." WHERE page=:page");
$dbr->bindParam(':page', $_REQUEST['id'], PDO::PARAM_INT);
$dbr->execute();
$i=0;
while($row = $dbr->fetch())
{
@unlink(PAGE_PHOTOS_PATH.$row['filename']);
@unlink(PAGE_THUMBNAILS_PATH.$row['filename']);
}
$dbr = Database::$connection->prepare("DELETE FROM ".$db_settings['page_photos_table']." WHERE page=:page");
$dbr->bindValue(':page', $_REQUEST['id'], PDO::PARAM_INT);
$dbr->execute();
}
header('Location: '.BASE_URL.'?r=page.overview');
exit;
}
else
{
header('Location: '.BASE_URL.'?r=page.delete&id='.intval($_REQUEST['id']).'&failure=password_wrong');
exit;
}
}
break;
case 'reorder_pages':
if(isset($_REQUEST['item']) && is_array($_REQUEST['item']) && $permission->granted(Permission::PAGE_MANAGEMENT))
{
$dbr = Database::$connection->prepare("UPDATE ".Database::$db_settings['pages_table']." SET sequence=:sequence WHERE id=:id");
$dbr->bindParam(':sequence', $sequence, PDO::PARAM_INT);
$dbr->bindParam(':id', $id, PDO::PARAM_INT);
Database::$connection->beginTransaction();
$sequence = 1;
foreach($_REQUEST['item'] as $id)
{
$dbr->execute();
++$sequence;
}
Database::$connection->commit();
exit;
}
break;
case 'add_photo':
if(isset($_GET['page_id']) && $permission->granted(Permission::PAGE_MANAGEMENT))
{
$dbr = Database::$connection->prepare("SELECT id, identifier, title FROM ".Database::$db_settings['pages_table']." WHERE id=:id LIMIT 1");
$dbr->bindParam(':id', $_GET['page_id'], PDO::PARAM_INT);
$dbr->execute();
$row = $dbr->fetch();
if(isset($row['id']))
{
$page['id'] = $row['id'];
$page['identifier'] = htmlspecialchars($row['identifier']);
$page['title'] = htmlspecialchars($row['title']);
$template->assign('page', $page);
$template->assign('subtitle', $lang['page_add_photo_subtitle']);
$template->assign('subtemplate', 'page.edit_photo.inc.tpl');
}
}
break;
case 'add_photo_submit':
if(isset($_FILES['photo']) && is_uploaded_file($_FILES['photo']['tmp_name']) && isset($_POST['page_id']) && $permission->granted(Permission::PAGE_MANAGEMENT))
{
// check if project exists:
$dbr = Database::$connection->prepare("SELECT id, identifier FROM ".Database::$db_settings['pages_table']." WHERE id=:id LIMIT 1");
$dbr->bindParam(':id', $_POST['page_id'], PDO::PARAM_INT);
$dbr->execute();
$row = $dbr->fetch();
if(isset($row['id']))
{
$page_id = $row['id'];
$page_identifier = $row['identifier'];
$title = isset($_POST['title']) ? trim($_POST['title']) : '';
$description = isset($_POST['description']) ? trim($_POST['description']) : '';
$author = isset($_POST['author']) ? trim($_POST['author']) : '';
if($_FILES['photo']['error']) $errors[] = 'error_photo_upload';
if(empty($errors))
{
$upload_info = getimagesize($_FILES['photo']['tmp_name']);
if($upload_info[2]!=IMAGETYPE_JPEG && $upload_info[2]!=IMAGETYPE_JPEG2000 && $upload_info[2]!=IMAGETYPE_PNG && $upload_info[2]!=IMAGETYPE_GIF) $errors[] = 'error_photo_invalid_file_type';
}
if(empty($errors))
{
spl_autoload_register('imagineLoader');
$filename = gmdate("YmdHis").uniqid();
if($upload_info[2]==IMAGETYPE_PNG) $extension = 'png';
elseif($upload_info[2]==IMAGETYPE_GIF) $extension = 'gif';
else $extension = 'jpg';
$photo_info['filename'] = $filename . '.' . $extension;
$imagine = new Imagine\Gd\Imagine();
$photo = $imagine->open($_FILES['photo']['tmp_name']);
// create photo:
$photo_options = array('quality' => $settings['project_photo_quality']);
$photo_size = new Imagine\Image\Box($settings['project_photo_width'], $settings['project_photo_height']);
$photo_mode = Imagine\Image\ImageInterface::THUMBNAIL_INSET;
$photo->thumbnail($photo_size, $photo_mode)->save(PAGE_PHOTOS_PATH.$photo_info['filename'], $photo_options);
//$photo->resize(new Imagine\Image\Box($settings['project_photo_width'], $settings['project_photo_height']))->save(BASE_PATH.PAGE_PHOTOS_DIR.$photo_info['filename'], $photo_options);
// create thumbnail:
$thumbnail_options = array('quality' => $settings['project_thumbnail_quality']);
$thumbnail_size = new Imagine\Image\Box($settings['project_thumbnail_width'], $settings['project_thumbnail_height']);
$thumbnail_mode = Imagine\Image\ImageInterface::THUMBNAIL_INSET;
$photo->thumbnail($thumbnail_size, $thumbnail_mode)->save(PAGE_THUMBNAILS_PATH.$photo_info['filename'], $thumbnail_options);
$saved_photo_info = getimagesize(PAGE_PHOTOS_PATH.$photo_info['filename']);
$saved_thumbnail_info = getimagesize(PAGE_THUMBNAILS_PATH.$photo_info['filename']);
$photo_info['photo_width'] = $saved_photo_info[0];
$photo_info['photo_height'] = $saved_photo_info[1];
$photo_info['thumbnail_width'] = $saved_thumbnail_info[0];
$photo_info['thumbnail_height'] = $saved_thumbnail_info[1];
// determine sequence:
$dbr = Database::$connection->prepare("SELECT sequence FROM ".$db_settings['page_photos_table']." WHERE page=:page ORDER BY sequence DESC LIMIT 1");
$dbr->bindParam(':page', $page_id, PDO::PARAM_INT);
$dbr->execute();
$row = $dbr->fetch();
if(isset($row['sequence'])) $new_sequence = $row['sequence'] + 1;
else $new_sequence = 1;
// save record:
$dbr = Database::$connection->prepare("INSERT INTO ".$db_settings['page_photos_table']." (creator, created, page, sequence, filename, thumbnail_width, thumbnail_height, photo_width, photo_height, title, description, author) VALUES (:creator, NOW(), :page,:sequence,:filename,:thumbnail_width,:thumbnail_height,:photo_width,:photo_height,:title,:description,:author)");
$dbr->bindParam(':creator', $_SESSION[$settings['session_prefix'].'auth']['id'], PDO::PARAM_INT);
$dbr->bindParam(':page', $page_id, PDO::PARAM_INT);
$dbr->bindParam(':sequence', $new_sequence, PDO::PARAM_INT);
$dbr->bindParam(':filename', $photo_info['filename'], PDO::PARAM_STR);
$dbr->bindParam(':thumbnail_width', $photo_info['thumbnail_width'], PDO::PARAM_INT);
$dbr->bindParam(':thumbnail_height', $photo_info['thumbnail_height'], PDO::PARAM_INT);
$dbr->bindParam(':photo_width', $photo_info['photo_width'], PDO::PARAM_INT);
$dbr->bindParam(':photo_height', $photo_info['photo_height'], PDO::PARAM_INT);
$dbr->bindParam(':title', $title, PDO::PARAM_STR);
$dbr->bindParam(':description', $description, PDO::PARAM_STR);
$dbr->bindParam(':author', $author, PDO::PARAM_STR);
$dbr->execute();
header('Location: '.BASE_URL.$page_identifier.'#photos');
exit;
}
}
}
break;
case 'edit_photo':
if(isset($_GET['id']) && $permission->granted(Permission::PAGE_MANAGEMENT))
{
$dbr = Database::$connection->prepare("SELECT photo.id,
photo.page AS page_id,
photo.title,
photo.description,
photo.author,
photo.filename,
page.identifier AS page_identifier,
page.title AS page_title
FROM ".Database::$db_settings['page_photos_table']." AS photo
LEFT JOIN ".Database::$db_settings['pages_table']." AS page ON photo.page=page.id
WHERE photo.id=:id LIMIT 1");
$dbr->bindParam(':id', $_GET['id'], PDO::PARAM_INT);
$dbr->execute();
$row = $dbr->fetch();
if(isset($row['id']))
{
$page['id'] = intval($row['page_id']);
$page['identifier'] = htmlspecialchars($row['page_identifier']);
$page['title'] = htmlspecialchars($row['page_title']);
$photo['id'] = intval($row['id']);
$photo['title'] = htmlspecialchars($row['title']);
$photo['description'] = htmlspecialchars($row['description']);
$photo['author'] = htmlspecialchars($row['author']);
$photo['filename'] = htmlspecialchars($row['filename']);
$template->assign('page', $page);
$template->assign('photo', $photo);
$template->assign('subtitle', $lang['page_edit_photo_subtitle']);
$template->assign('subtemplate', 'page.edit_photo.inc.tpl');
}
}
break;
case 'edit_photo_submit':
if(isset($_POST['id']) && $permission->granted(Permission::PAGE_MANAGEMENT))
{
// get project id:
$dbr = Database::$connection->prepare("SELECT photo.id,
page.identifier
FROM ".Database::$db_settings['page_photos_table']." AS photo
LEFT JOIN ".Database::$db_settings['pages_table']." AS page ON photo.page=page.id
WHERE photo.id=:id LIMIT 1");
$dbr->bindParam(':id', $_POST['id'], PDO::PARAM_INT);
$dbr->execute();
$row = $dbr->fetch();
if(isset($row['id']))
{
$title = isset($_POST['title']) ? trim($_POST['title']) : '';
$description = isset($_POST['description']) ? trim($_POST['description']) : '';
$author = isset($_POST['author']) ? trim($_POST['author']) : '';
// update record:
$dbr = Database::$connection->prepare("UPDATE ".Database::$db_settings['page_photos_table']." SET title=:title, description=:description, author=:author, last_editor=:last_editor, last_edited=NOW() WHERE id=:id");
$dbr->bindParam(':id', $_POST['id'], PDO::PARAM_INT);
$dbr->bindParam(':last_editor', $_SESSION[$settings['session_prefix'].'auth']['id'], PDO::PARAM_INT);
$dbr->bindParam(':title', $title, PDO::PARAM_STR);
$dbr->bindParam(':description', $description, PDO::PARAM_STR);
$dbr->bindParam(':author', $author, PDO::PARAM_STR);
$dbr->execute();
header('Location: '.BASE_URL.$row['identifier'].'#photos');
exit;
}
}
break;
case 'reorder_photos':
if(isset($_REQUEST['item']) && is_array($_REQUEST['item']) && $permission->granted(Permission::PAGE_MANAGEMENT))
{
$dbr = Database::$connection->prepare("UPDATE ".$db_settings['page_photos_table']." SET sequence=:sequence WHERE id=:id");
$dbr->bindParam(':sequence', $sequence, PDO::PARAM_INT);
$dbr->bindParam(':id', $id, PDO::PARAM_INT);
Database::$connection->beginTransaction();
$sequence = 1;
foreach($_REQUEST['item'] as $id)
{
$dbr->execute();
++$sequence;
}
Database::$connection->commit();
exit;
}
break;
case 'delete_photo':
if(isset($_REQUEST['id']) && $permission->granted(Permission::PAGE_MANAGEMENT))
{
// check if project exists:
$dbr = Database::$connection->prepare("SELECT photo.id,
photo.filename,
photo.page,
page.identifier
FROM ".Database::$db_settings['page_photos_table']." AS photo
LEFT JOIN ".Database::$db_settings['pages_table']." AS page ON photo.page=page.id
WHERE photo.id=:id LIMIT 1");
$dbr->bindParam(':id', $_REQUEST['id'], PDO::PARAM_INT);
$dbr->execute();
$row = $dbr->fetch();
if(isset($row['id']))
{
$dbr = Database::$connection->prepare("DELETE FROM ".Database::$db_settings['page_photos_table']." WHERE id = :id");
$dbr->bindParam(':id', $_REQUEST['id'], PDO::PARAM_INT);
$dbr->execute();
@unlink(PAGE_PHOTOS_PATH.$row['filename']);
@unlink(PAGE_THUMBNAILS_PATH.$row['filename']);
// reorder...
$dbr = Database::$connection->prepare("SELECT id FROM ".Database::$db_settings['page_photos_table']." WHERE page=:page ORDER BY sequence ASC");
$dbr->bindParam(':page', $row['page'], PDO::PARAM_INT);
$dbr->execute();
$i=1;
while($row2 = $dbr->fetch())
{
$dbr2 = Database::$connection->prepare("UPDATE ".Database::$db_settings['page_photos_table']." SET sequence=:sequence WHERE id=:id");
$dbr2->bindValue(':sequence', $i, PDO::PARAM_INT);
$dbr2->bindValue(':id', $row2['id'], PDO::PARAM_INT);
$dbr2->execute();
++$i;
}
header('Location: '.BASE_URL.$row['identifier'].'#photos');
exit;
}
}
break;
case 'overview':
if($permission->granted(Permission::PAGE_MANAGEMENT))
{
$dbr = Database::$connection->prepare("SELECT a.id,
a.identifier,
a.title,
a.status,
a.index,
a.news,
a.project,
b.title as parent_title
FROM ".Database::$db_settings['pages_table']." AS a
LEFT JOIN ".Database::$db_settings['pages_table']." AS b ON a.parent=b.id
ORDER BY a.sequence ASC");
$dbr->execute();
$i=0;
while($row = $dbr->fetch())
{
$pages[$i]['id'] = intval($row['id']);
$pages[$i]['identifier'] = htmlspecialchars($row['identifier']);
$pages[$i]['title'] = htmlspecialchars($row['title']);
$pages[$i]['status'] = intval($row['status']);
$pages[$i]['index'] = $row['index'];
$pages[$i]['news'] = $row['news'];
$pages[$i]['project'] = $row['project'];
$pages[$i]['parent_title'] = htmlspecialchars($row['parent_title']);
#$pages[$i]['active'] = $row['active'];
++$i;
}
if(isset($pages)) $template->assign('pages', $pages);
$javascripts[] = JQUERY_UI;
$javascripts[] = JQUERY_UI_HANDLER;
#$stylesheets[] = JQUERY_UI_CSS;
$template->assign('subtitle', $lang['page_overview_subtitle']);
$template->assign('subtemplate', 'page.overview.inc.tpl');
}
break;
default:
#$dbr = Database::$connection->prepare("SELECT id, title, teaser, teaser_image, teaser_image_width, teaser_image_height FROM ".$db_settings['pages_table']." WHERE status>0 ORDER BY sequence ASC");
if($permission->granted(Permission::PAGE_MANAGEMENT)) $status_query = '';
elseif($permission->granted(Permission::USER)) $status_query = ' AND status > 0';
else $status_query = ' AND status = 2';
$dbr = Database::$connection->prepare("SELECT id, identifier, extract(epoch FROM created) as created_timestamp, custom_date, title, content, teaser_supertitle, teaser_title, teaser_text, teaser_linktext, teaser_image, teaser_image_width, teaser_image_height, tv FROM ".Database::$db_settings['pages_table']." WHERE index IS true".$status_query." ORDER BY sequence ASC");
$dbr->execute();
$i=0;
while($row = $dbr->fetch())
{
if($tv = extract_tvs($row['tv'])) $projects[$i]['tv'] = $tv;
$projects[$i]['id'] = intval($row['id']);
$projects[$i]['identifier'] = htmlspecialchars($row['identifier']);
$projects[$i]['created'] = htmlspecialchars(strftime($lang['time_format'], $row['created_timestamp']));
if($row['teaser_supertitle']) $projects[$i]['teaser_supertitle'] = htmlspecialchars($row['teaser_supertitle']);
//else $projects[$i]['teaser_supertitle'] = strftime($lang['time_format'], $row['created_timestamp']);
if($row['teaser_title']) $projects[$i]['teaser_title'] = htmlspecialchars($row['teaser_title']);
else $projects[$i]['teaser_title'] = htmlspecialchars($row['title']);
if($row['teaser_text']) $projects[$i]['teaser_text'] = $row['teaser_text'];
//else $projects[$i]['teaser_text'] = truncate($row['content'], $settings['page_teaser_auto_truncate']);
else $projects[$i]['teaser_text'] = $row['content'];
if($row['teaser_linktext']) $projects[$i]['teaser_linktext'] = $row['teaser_linktext'];
//else $projects[$i]['teaser_linktext'] = $lang['page_default_teaser_linktext'];
if($row['teaser_image'])
{
$projects[$i]['teaser_image']['file'] = $row['teaser_image'];
$projects[$i]['teaser_image']['width'] = $row['teaser_image_width'];
$projects[$i]['teaser_image']['height'] = $row['teaser_image_height'];
}
++$i;
}
if(isset($projects))
{
$template->assign('projects', $projects);
$template->assign('project_count', $i);
}
$template->assign('active', 'home');
$template->assign('page_title', $settings['index_page_title']);
#$template->assign('subtitle', $lang['projects_subtitle']);
$template->assign('subtemplate', 'index.inc.tpl');
}
?>
| mit |
danjac/podbaby | Godeps/_workspace/src/gopkg.in/redis.v3/ring_test.go | 4416 | package redis_test
import (
"crypto/rand"
"fmt"
"time"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/danjac/podbaby/Godeps/_workspace/src/gopkg.in/redis.v3"
)
var _ = Describe("Redis ring", func() {
var ring *redis.Ring
setRingKeys := func() {
for i := 0; i < 100; i++ {
err := ring.Set(fmt.Sprintf("key%d", i), "value", 0).Err()
Expect(err).NotTo(HaveOccurred())
}
}
BeforeEach(func() {
ring = redis.NewRing(&redis.RingOptions{
Addrs: map[string]string{
"ringShardOne": ":" + ringShard1Port,
"ringShardTwo": ":" + ringShard2Port,
},
})
// Shards should not have any keys.
Expect(ringShard1.FlushDb().Err()).NotTo(HaveOccurred())
Expect(ringShard1.Info().Val()).NotTo(ContainSubstring("keys="))
Expect(ringShard2.FlushDb().Err()).NotTo(HaveOccurred())
Expect(ringShard2.Info().Val()).NotTo(ContainSubstring("keys="))
})
AfterEach(func() {
Expect(ring.Close()).NotTo(HaveOccurred())
})
It("uses both shards", func() {
setRingKeys()
// Both shards should have some keys now.
Expect(ringShard1.Info().Val()).To(ContainSubstring("keys=57"))
Expect(ringShard2.Info().Val()).To(ContainSubstring("keys=43"))
})
It("uses one shard when other shard is down", func() {
// Stop ringShard2.
Expect(ringShard2.Close()).NotTo(HaveOccurred())
// Ring needs 5 * heartbeat time to detect that node is down.
// Give it more to be sure.
heartbeat := 100 * time.Millisecond
time.Sleep(5*heartbeat + heartbeat)
setRingKeys()
// RingShard1 should have all keys.
Expect(ringShard1.Info().Val()).To(ContainSubstring("keys=100"))
// Start ringShard2.
var err error
ringShard2, err = startRedis(ringShard2Port)
Expect(err).NotTo(HaveOccurred())
// Wait for ringShard2 to come up.
Eventually(func() error {
return ringShard2.Ping().Err()
}, "1s").ShouldNot(HaveOccurred())
// Ring needs heartbeat time to detect that node is up.
// Give it more to be sure.
time.Sleep(heartbeat + heartbeat)
setRingKeys()
// RingShard2 should have its keys.
Expect(ringShard2.Info().Val()).To(ContainSubstring("keys=43"))
})
It("supports hash tags", func() {
for i := 0; i < 100; i++ {
err := ring.Set(fmt.Sprintf("key%d{tag}", i), "value", 0).Err()
Expect(err).NotTo(HaveOccurred())
}
Expect(ringShard1.Info().Val()).ToNot(ContainSubstring("keys="))
Expect(ringShard2.Info().Val()).To(ContainSubstring("keys=100"))
})
Describe("pipelining", func() {
It("returns an error when all shards are down", func() {
ring := redis.NewRing(&redis.RingOptions{})
_, err := ring.Pipelined(func(pipe *redis.RingPipeline) error {
pipe.Ping()
return nil
})
Expect(err).To(MatchError("redis: all ring shards are down"))
})
It("uses both shards", func() {
pipe := ring.Pipeline()
for i := 0; i < 100; i++ {
err := pipe.Set(fmt.Sprintf("key%d", i), "value", 0).Err()
Expect(err).NotTo(HaveOccurred())
}
cmds, err := pipe.Exec()
Expect(err).NotTo(HaveOccurred())
Expect(cmds).To(HaveLen(100))
Expect(pipe.Close()).NotTo(HaveOccurred())
for _, cmd := range cmds {
Expect(cmd.Err()).NotTo(HaveOccurred())
Expect(cmd.(*redis.StatusCmd).Val()).To(Equal("OK"))
}
// Both shards should have some keys now.
Expect(ringShard1.Info().Val()).To(ContainSubstring("keys=57"))
Expect(ringShard2.Info().Val()).To(ContainSubstring("keys=43"))
})
It("is consistent with ring", func() {
var keys []string
for i := 0; i < 100; i++ {
key := make([]byte, 64)
_, err := rand.Read(key)
Expect(err).NotTo(HaveOccurred())
keys = append(keys, string(key))
}
_, err := ring.Pipelined(func(pipe *redis.RingPipeline) error {
for _, key := range keys {
pipe.Set(key, "value", 0).Err()
}
return nil
})
Expect(err).NotTo(HaveOccurred())
for _, key := range keys {
val, err := ring.Get(key).Result()
Expect(err).NotTo(HaveOccurred())
Expect(val).To(Equal("value"))
}
})
It("supports hash tags", func() {
_, err := ring.Pipelined(func(pipe *redis.RingPipeline) error {
for i := 0; i < 100; i++ {
pipe.Set(fmt.Sprintf("key%d{tag}", i), "value", 0).Err()
}
return nil
})
Expect(err).NotTo(HaveOccurred())
Expect(ringShard1.Info().Val()).ToNot(ContainSubstring("keys="))
Expect(ringShard2.Info().Val()).To(ContainSubstring("keys=100"))
})
})
})
| mit |
LauenerEngineering/Lauener.Core | Lauener.Core/Serializer/JsonSerialization.cs | 983 | namespace Lauener.Core.Serializer
{
using System.IO;
using System.Runtime.Serialization.Json;
using Newtonsoft.Json;
public class JsonSerialization : ISerializer
{
public T DeserializeStream<T>(Stream stream)
{
stream.ThrowIfNull(nameof(stream));
var s = new DataContractJsonSerializer(typeof(T));
return (T)s.ReadObject(stream);
}
public T DeserializeString<T>(string data)
{
return JsonConvert.DeserializeObject<T>(data.ThrowIfNull(nameof(data)));
}
public T DeserializeByte<T>(byte[] data)
{
data.ThrowIfNull(nameof(data));
using (var s = new MemoryStream(data))
{
return this.DeserializeStream<T>(s);
}
}
public string Serialize<T>(T obj)
{
return JsonConvert.SerializeObject(obj.ThrowIfNull(nameof(obj)));
}
}
} | mit |
hisekaldma/Polyhymnia | src/polyhymnia.js | 2472 | var Polyhymnia = Polyhymnia || {};
Polyhymnia.getAudioContext = function() {
'use strict';
if (!Polyhymnia.audioContext) {
window.AudioContext = window.AudioContext || window.webkitAudioContext;
Polyhymnia.audioContext = new AudioContext();
}
return Polyhymnia.audioContext;
};
Polyhymnia.isSupported = function() {
'use strict';
window.AudioContext = window.AudioContext || window.webkitAudioContext;
if (window.AudioContext) {
return true;
} else {
return false;
}
};
Polyhymnia.Context = function(options) {
'use strict';
if (!Polyhymnia.isSupported()) {
return {
play: function() { },
stop: function() { },
setParam: function() { },
setRules: function() { },
setTempo: function() { },
setAnimCallback: function() { }
};
}
// Generator
var generator = new Polyhymnia.Generator();
generator.setParam('x', 0);
generator.instruments = {};
// Sequencer
var sequencer = new Polyhymnia.Sequencer();
sequencer.generator = generator;
// Metronome
var metronome = new Polyhymnia.Metronome();
metronome.sequencer = sequencer;
if (options && options.tempo) {
metronome.tempo = options.tempo;
}
// Instruments
if (options && options.instruments) {
options.instruments.forEach(function(instrument) {
sequencer.instruments[instrument.name] = new Polyhymnia.Sampler(instrument);
});
}
function parse(code) {
var tokens = Polyhymnia.tokenize(code);
var result = Polyhymnia.parse(tokens);
result = Polyhymnia.validate(result, sequencer.instruments);
generator.setRules(result.rules);
return result;
}
function play() {
metronome.play();
}
function stop() {
metronome.stop();
sequencer.stop();
generator.reset();
}
function setTempo(tempo) {
metronome.tempo = tempo;
}
function setTimeSignature(numerator, denominator) {
sequencer.timeSignature.num = numerator;
sequencer.timeSignature.den = denominator;
}
function setTonic(tonic) {
generator.tonic = tonic;
}
function setScale(scale) {
generator.scale = scale;
}
function setAnimCallback(callback) {
sequencer.animCallback = callback;
}
return {
parse: parse,
play: play,
stop: stop,
setParam: generator.setParam,
setTempo: setTempo,
setTonic: setTonic,
setScale: setScale,
setTimeSignature: setTimeSignature,
setAnimCallback: setAnimCallback
};
}; | mit |
yangra/SoftUni | Java-DB-Fundamentals/DatabasesFrameworks-Hibernate&SpringData/EXAMS/weddings_planner_exam/src/main/java/softuni/services/impl/VenueServiceImpl.java | 1713 | package softuni.services.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import softuni.dto.Export.VenueExportXmlDto;
import softuni.dto.Export.VenuesExportXmlDto;
import softuni.dto.Import.VenueImportXmlDto;
import softuni.entities.Venue;
import softuni.repositories.VenueRepository;
import softuni.services.api.VenueService;
import softuni.utils.ModelParser;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
@Service
@Transactional
public class VenueServiceImpl implements VenueService {
private final VenueRepository venueRepository;
@Autowired
public VenueServiceImpl(VenueRepository venueRepository) {
this.venueRepository = venueRepository;
}
@Override
public void saveDto(VenueImportXmlDto venueImportDto) {
Venue venue = ModelParser.getInstance().map(venueImportDto, Venue.class);
this.venueRepository.saveAndFlush(venue);
}
@Override
public List<Venue> getAll() {
return this.venueRepository.findAll();
}
@Override
public VenuesExportXmlDto getVenuesIn(String town, Integer count) {
List<Venue> venues = this.venueRepository.findByTown(town, count);
VenuesExportXmlDto venuesExportDto = new VenuesExportXmlDto();
List<VenueExportXmlDto> venueExportDtos = new ArrayList<>();
for (Venue venue : venues) {
VenueExportXmlDto venueExportDto = ModelParser.getInstance().map(venue,VenueExportXmlDto.class);
venueExportDtos.add(venueExportDto);
}
venuesExportDto.setVenueExportXmlDtos(venueExportDtos);
return venuesExportDto;
}
}
| mit |
quantiguous/api_banking | lib/api_banking/soap/instantMoneyTransferService.rb | 9181 | module ApiBanking
class InstantMoneyTransferService < Soap12Client
SERVICE_NAMESPACE = 'http://www.quantiguous.com/services'
SERVICE_VERSION = 1
attr_accessor :request, :result
module AddBeneficiary
Request = Struct.new(:uniqueRequestNo, :appID, :customerID, :beneficiaryMobileNo, :beneficiaryName, :beneficiaryAddress)
Address = Struct.new(:addressLine, :cityName, :postalCode)
Result = Struct.new(:uniqueResponseNo)
end
module CancelTransfer
Request = Struct.new(:uniqueRequestNo, :appID, :customerID, :initiateTransferRequestNo, :reasonToCancel)
Result = Struct.new(:uniqueResponseNo, :cancelResult)
CancelResult = Struct.new(:imtReferenceNo, :bankReferenceNo)
end
module DeleteBeneficiary
Request = Struct.new(:uniqueRequestNo, :appID, :customerID, :beneficiaryMobileNo)
Result = Struct.new(:uniqueResponseNo)
end
module GetBeneficiaries
Request = Struct.new(:uniqueRequestNo, :appID, :customerID, :dateRange, :numBeneficiaries)
DateRange = Struct.new(:fromDate, :toDate)
Beneficiary = Struct.new(:beneficiaryName, :beneficiaryMobileNo, :registrationDate, :addressLine, :postalCode)
BeneficiariesArray = Struct.new(:beneficiary)
Result = Struct.new(:numBeneficiaries, :beneficiariesArray)
end
#transfer
module InitiateTransfer
Request = Struct.new(:uniqueRequestNo, :appID, :customerID, :beneficiaryMobileNo, :transferAmount, :passCode, :remitterToBeneficiaryInfo)
Result = Struct.new(:uniqueResponseNo, :initiateTransferResult)
TransferResult = Struct.new(:bankReferenceNo, :imtReferenceNo)
end
class << self
attr_accessor :configuration
end
def self.configure
self.configuration ||= Configuration.new
yield(configuration)
end
class Configuration
attr_accessor :environment, :proxy, :timeout
end
def self.transfer(env, request, callbacks = nil)
reply = do_remote_call(env, callbacks) do |xml|
xml.initiateTransfer("xmlns:ns" => SERVICE_NAMESPACE ) do
xml.parent.namespace = xml.parent.namespace_definitions.first
xml['ns'].version SERVICE_VERSION
xml['ns'].uniqueRequestNo request.uniqueRequestNo
xml['ns'].appID request.appID
xml['ns'].customerID request.customerID
xml['ns'].beneficiaryMobileNo request.beneficiaryMobileNo
xml['ns'].transferAmount request.transferAmount
xml['ns'].passCode request.passCode
xml['ns'].remitterToBeneficiaryInfo request.remitterToBeneficiaryInfo
end
end
parse_reply(:initiateTransfer, reply)
end
def self.add_beneficiary(env, request, callbacks = nil)
reply = do_remote_call(env, callbacks) do |xml|
xml.addBeneficiary("xmlns:ns" => SERVICE_NAMESPACE ) do
xml.parent.namespace = xml.parent.namespace_definitions.first
xml['ns'].version SERVICE_VERSION
xml['ns'].uniqueRequestNo request.uniqueRequestNo
xml['ns'].appID request.appID
xml['ns'].customerID request.customerID
xml['ns'].beneficiaryMobileNo request.beneficiaryMobileNo
xml['ns'].beneficiaryName request.beneficiaryName
xml['ns'].beneficiaryAddress do |xml|
if request.beneficiaryAddress.kind_of? AddBeneficiary::Address
xml.addressLine request.beneficiaryAddress.addressLine
xml.cityName request.beneficiaryAddress.cityName unless request.beneficiaryAddress.cityName.nil?
xml.postalCode request.beneficiaryAddress.postalCode unless request.beneficiaryAddress.postalCode.nil?
else
xml.addressLine request.beneficiaryAddress
end
end
end
end
parse_reply(:addBeneficiary, reply)
end
def self.delete_beneficiary(env, request, callbacks = nil)
reply = do_remote_call(env, callbacks) do |xml|
xml.deleteBeneficiary("xmlns:ns" => SERVICE_NAMESPACE ) do
xml.parent.namespace = xml.parent.namespace_definitions.first
xml['ns'].version SERVICE_VERSION
xml['ns'].uniqueRequestNo request.uniqueRequestNo
xml['ns'].appID request.appID
xml['ns'].customerID request.customerID
xml['ns'].beneficiaryMobileNo request.beneficiaryMobileNo
end
end
parse_reply(:deleteBeneficiary, reply)
end
def self.get_beneficiaries(env, request, callbacks = nil)
reply = do_remote_call(env, callbacks) do |xml|
xml.getBeneficiaries("xmlns:ns" => SERVICE_NAMESPACE ) do
xml.parent.namespace = xml.parent.namespace_definitions.first
xml['ns'].version SERVICE_VERSION
xml['ns'].appID request.appID
xml['ns'].customerID request.customerID
xml.dateRange do |xml|
xml.fromDate request.dateRange.fromDate unless request.dateRange.fromDate.nil?
xml.toDate request.dateRange.toDate unless request.dateRange.toDate.nil?
end
xml['ns'].numBeneficiaries request.numBeneficiaries
end
end
parse_reply(:getBeneficiaries, reply)
end
def self.cancel_transfer(env, request, callbacks = nil)
reply = do_remote_call(env, callbacks) do |xml|
xml.cancelTransfer("xmlns:ns" => SERVICE_NAMESPACE ) do
xml.parent.namespace = xml.parent.namespace_definitions.first
xml['ns'].version SERVICE_VERSION
xml['ns'].uniqueRequestNo request.uniqueRequestNo
xml['ns'].appID request.appID
xml['ns'].customerID request.customerID
xml['ns'].initiateTransferRequestNo request.initiateTransferRequestNo
xml['ns'].reasonToCancel request.reasonToCancel
end
end
parse_reply(:cancelTransfer, reply)
end
private
def self.parse_reply(operationName, reply)
if reply.kind_of?Fault
return reply
else
case operationName
when :initiateTransfer
transferResult = InitiateTransfer::TransferResult.new(
content_at(reply.at_xpath('//ns:initiateTransferResponse/ns:initiateTransferResult/ns:bankReferenceNo', 'ns' => SERVICE_NAMESPACE)),
content_at(reply.at_xpath('//ns:initiateTransferResponse/ns:initiateTransferResult/ns:imtReferenceNo', 'ns' => SERVICE_NAMESPACE))
)
return InitiateTransfer::Result.new(
content_at(reply.at_xpath('//ns:initiateTransferResponse/ns:uniqueResponseNo', 'ns' => SERVICE_NAMESPACE)),
transferResult
)
when :addBeneficiary
return AddBeneficiary::Result.new(
content_at(reply.at_xpath('//ns:addBeneficiaryResponse/ns:uniqueResponseNo', 'ns' => SERVICE_NAMESPACE)),
)
when :deleteBeneficiary
return DeleteBeneficiary::Result.new(
content_at(reply.at_xpath('//ns:deleteBeneficiaryResponse/ns:uniqueResponseNo', 'ns' => SERVICE_NAMESPACE)),
)
when :getBeneficiaries
beneficiariesArray = Array.new
i = 1
numBeneficiaries = content_at(reply.at_xpath('//ns:getBeneficiariesResponse/ns:numBeneficiaries', 'ns' => SERVICE_NAMESPACE)).to_i
until i > numBeneficiaries
beneficiariesArray << GetBeneficiaries::Beneficiary.new(
content_at(reply.at_xpath("//ns:getBeneficiariesResponse/ns:beneficiariesArray/ns:beneficiary[#{i}]/ns:beneficiaryName", 'ns' => SERVICE_NAMESPACE)),
content_at(reply.at_xpath("//ns:getBeneficiariesResponse/ns:beneficiariesArray/ns:beneficiary[#{i}]/ns:beneficiaryMobileNo", 'ns' => SERVICE_NAMESPACE)),
content_at(reply.at_xpath("//ns:getBeneficiariesResponse/ns:beneficiariesArray/ns:beneficiary[#{i}]/ns:registrationDate", 'ns' => SERVICE_NAMESPACE)),
content_at(reply.at_xpath("//ns:getBeneficiariesResponse/ns:beneficiariesArray/ns:beneficiary[#{i}]/ns:addressLine", 'ns' => SERVICE_NAMESPACE)),
content_at(reply.at_xpath("//ns:getBeneficiariesResponse/ns:beneficiariesArray/ns:beneficiary[#{i}]/ns:postalCode", 'ns' => SERVICE_NAMESPACE))
)
i = i + 1;
end;
beneArray = GetBeneficiaries::BeneficiariesArray.new(beneficiariesArray)
return GetBeneficiaries::Result.new(
content_at(reply.at_xpath('//ns:getBeneficiariesResponse/ns:numBeneficiaries', 'ns' => SERVICE_NAMESPACE)),
beneArray
)
when :cancelTransfer
cancelResult = CancelTransfer::CancelResult.new(
content_at(reply.at_xpath('//ns:cancelTransferResponse/ns:cancelResult/ns:imtReferenceNo', 'ns' => SERVICE_NAMESPACE)),
content_at(reply.at_xpath('//ns:cancelTransferResponse/ns:cancelResult/ns:bankReferenceNo', 'ns' => SERVICE_NAMESPACE))
)
return CancelTransfer::Result.new(
content_at(reply.at_xpath('//ns:cancelTransferResponse/ns:uniqueResponseNo', 'ns' => SERVICE_NAMESPACE)),
cancelResult
)
end
end
end
end
end
| mit |
cmavromoustakos/i18n | test/translation_helper_test.rb | 370 | require 'test_helper'
require 'i18n/action_view/helpers/translation_helper'
class TranslationHelperTest < Test::Unit::TestCase
include ActionView::Helpers::TranslationHelper
def test_run_substitutions
result = run_substitutions "this is text with a :special field", :special => "FNORD"
assert_equal "this is text with a FNORD field", result
end
end
| mit |
Scardiecat/svermaker | semver/projectversionservice_test.go | 13711 | package semver_test
import (
"github.com/Scardiecat/svermaker"
mock "github.com/Scardiecat/svermaker/mock"
"github.com/Scardiecat/svermaker/semver"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("Projectversionservice", func() {
var serializer = mock.Serializer{}
var pvs = semver.ProjectVersionService{Serializer: &serializer}
BeforeEach(func() {
serializer = mock.Serializer{}
pvs = semver.ProjectVersionService{Serializer: &serializer}
})
Describe("Init()", func() {
Context("If a ProjectVersion does not exist", func() {
It("should create a new saved version", func() {
serializer.ExistsFn = func() bool {
return false
}
serializer.SerializerFn = func(p svermaker.ProjectVersion) error {
return nil
}
p, err := pvs.Init()
Expect(err).To(BeNil())
Expect(serializer.ExistsInvoked).To(BeTrue())
Expect(serializer.SerializerInvoked).To(BeTrue())
Expect(serializer.DeserializerInvoked).To(BeFalse())
Expect(p).To(Equal(&svermaker.DefaultProjectVersion))
})
It("should return the default version", func() {
serializer.ExistsFn = func() bool {
return false
}
serializer.SerializerFn = func(p svermaker.ProjectVersion) error {
return nil
}
p, err := pvs.Init()
Expect(err).To(BeNil())
Expect(p).To(Equal(&svermaker.DefaultProjectVersion))
})
})
Context("If a ProjectVersion does exist", func() {
It("should use the existing version and return it", func() {
saved := &svermaker.ProjectVersion{Current: svermaker.Version{1, 1, 1, nil, nil}, Next: svermaker.Version{1, 1, 1, nil, nil}}
serializer.ExistsFn = func() bool {
return true
}
serializer.DeserializeFn = func() (*svermaker.ProjectVersion, error) {
return saved, nil
}
p, err := pvs.Init()
Expect(err).To(BeNil())
Expect(serializer.ExistsInvoked).To(BeTrue())
Expect(serializer.SerializerInvoked).To(BeFalse())
Expect(serializer.DeserializerInvoked).To(BeTrue())
Expect(p).To(Equal(saved))
})
})
})
Describe("Get()", func() {
Context("If a ProjectVersion does not exist", func() {
It("it should raise an error", func() {
serializer.ExistsFn = func() bool {
return false
}
_, err := pvs.Get()
Expect(err).To(MatchError("version not found"))
})
})
Context("If a ProjectVersion does exist", func() {
It("it should return it", func() {
current := svermaker.Version{1, 1, 1, nil, nil}
saved := &svermaker.ProjectVersion{Current: current, Next: current}
serializer.ExistsFn = func() bool {
return true
}
serializer.DeserializeFn = func() (*svermaker.ProjectVersion, error) {
return saved, nil
}
c, err := pvs.Get()
Expect(err).To(BeNil())
Expect(c).To(Equal(saved))
})
})
})
Describe("GetCurrent()", func() {
Context("If a ProjectVersion does not exist", func() {
It("it should raise an error", func() {
serializer.ExistsFn = func() bool {
return false
}
_, err := pvs.GetCurrent()
Expect(err).To(MatchError("version not found"))
})
})
Context("If a ProjectVersion does exist", func() {
It("it should return the current version", func() {
current := svermaker.Version{1, 1, 1, nil, nil}
saved := &svermaker.ProjectVersion{Current: current, Next: svermaker.Version{1, 1, 2, nil, nil}}
serializer.ExistsFn = func() bool {
return true
}
serializer.DeserializeFn = func() (*svermaker.ProjectVersion, error) {
return saved, nil
}
c, err := pvs.GetCurrent()
Expect(err).To(BeNil())
Expect(c).To(Equal(¤t))
})
})
})
Describe("Bump()", func() {
It("should fail if the repo is not initialized", func() {
serializer.ExistsFn = func() bool {
return false
}
_, err := pvs.Bump(svermaker.PATCH, nil)
Expect(err).To(MatchError("version not found"))
})
Context("When bumping for a patch ", func() {
It("should increase the patch version on the next version", func() {
current := svermaker.Version{1, 1, 1, nil, nil}
next := svermaker.Version{1, 1, 2, nil, nil}
saved := &svermaker.ProjectVersion{Current: current, Next: current}
serializer.ExistsFn = func() bool {
return true
}
serializer.DeserializeFn = func() (*svermaker.ProjectVersion, error) {
return saved, nil
}
serializer.SerializerFn = func(p svermaker.ProjectVersion) error {
return nil
}
p, err := pvs.Bump(svermaker.PATCH, nil)
Expect(err).To(BeNil())
Expect(serializer.ExistsInvoked).To(BeTrue())
Expect(serializer.SerializerInvoked).To(BeTrue())
Expect(serializer.DeserializerInvoked).To(BeTrue())
Expect(p.Next).To(Equal(next))
})
Context("When a prerelease version is set", func() {
It("should use the supplied prerelease version for current version", func() {
current := svermaker.Version{1, 1, 1, nil, nil}
next := svermaker.Version{1, 1, 2, nil, nil}
expected := &svermaker.ProjectVersion{Current: current, Next: next}
saved := &svermaker.ProjectVersion{Current: current, Next: current}
serializer.ExistsFn = func() bool {
return true
}
serializer.DeserializeFn = func() (*svermaker.ProjectVersion, error) {
return saved, nil
}
serializer.SerializerFn = func(p svermaker.ProjectVersion) error {
return nil
}
m := semver.Manipulator{}
pre, _ := m.MakePrerelease("testpre")
p, err := pvs.Bump(svermaker.PATCH, pre)
Expect(err).To(BeNil())
Expect(serializer.ExistsInvoked).To(BeTrue())
Expect(serializer.SerializerInvoked).To(BeTrue())
Expect(serializer.DeserializerInvoked).To(BeTrue())
expected.Current, _ = m.SetPrerelease(expected.Next, pre)
Expect(p).To(Equal(expected))
})
})
Context("When a prerelease version is not set", func() {
It("should set the prerelease to rc for current version", func() {
current := svermaker.Version{1, 1, 1, nil, nil}
next := svermaker.Version{1, 1, 2, nil, nil}
expected := &svermaker.ProjectVersion{Current: current, Next: next}
saved := &svermaker.ProjectVersion{Current: current, Next: current}
serializer.ExistsFn = func() bool {
return true
}
serializer.DeserializeFn = func() (*svermaker.ProjectVersion, error) {
return saved, nil
}
serializer.SerializerFn = func(p svermaker.ProjectVersion) error {
return nil
}
p, err := pvs.Bump(svermaker.PATCH, nil)
m := semver.Manipulator{}
pre, _ := m.MakePrerelease("rc")
Expect(err).To(BeNil())
Expect(serializer.ExistsInvoked).To(BeTrue())
Expect(serializer.SerializerInvoked).To(BeTrue())
Expect(serializer.DeserializerInvoked).To(BeTrue())
expected.Current, _ = m.SetPrerelease(expected.Next, pre)
Expect(p).To(Equal(expected))
})
})
})
Context("When bumping for a minor", func() {
It("should increase the minor version on the next version", func() {
current := svermaker.Version{1, 1, 1, nil, nil}
next := svermaker.Version{1, 2, 0, nil, nil}
saved := &svermaker.ProjectVersion{Current: current, Next: current}
serializer.ExistsFn = func() bool {
return true
}
serializer.DeserializeFn = func() (*svermaker.ProjectVersion, error) {
return saved, nil
}
serializer.SerializerFn = func(p svermaker.ProjectVersion) error {
return nil
}
p, err := pvs.Bump(svermaker.MINOR, nil)
Expect(err).To(BeNil())
Expect(serializer.ExistsInvoked).To(BeTrue())
Expect(serializer.SerializerInvoked).To(BeTrue())
Expect(serializer.DeserializerInvoked).To(BeTrue())
Expect(p.Next).To(Equal(next))
})
Context("When a prerelease version is set", func() {
It("should use the supplied prerelease version for current version", func() {
current := svermaker.Version{1, 1, 1, nil, nil}
next := svermaker.Version{1, 2, 0, nil, nil}
expected := &svermaker.ProjectVersion{Current: current, Next: next}
saved := &svermaker.ProjectVersion{Current: current, Next: current}
serializer.ExistsFn = func() bool {
return true
}
serializer.DeserializeFn = func() (*svermaker.ProjectVersion, error) {
return saved, nil
}
serializer.SerializerFn = func(p svermaker.ProjectVersion) error {
return nil
}
m := semver.Manipulator{}
pre, _ := m.MakePrerelease("testpre")
p, err := pvs.Bump(svermaker.MINOR, pre)
Expect(err).To(BeNil())
Expect(serializer.ExistsInvoked).To(BeTrue())
Expect(serializer.SerializerInvoked).To(BeTrue())
Expect(serializer.DeserializerInvoked).To(BeTrue())
expected.Current, _ = m.SetPrerelease(expected.Next, pre)
Expect(p).To(Equal(expected))
})
})
Context("When a prerelease version is not set", func() {
It("should set the prerelease to rc for current version", func() {
current := svermaker.Version{1, 1, 1, nil, nil}
next := svermaker.Version{1, 2, 0, nil, nil}
expected := &svermaker.ProjectVersion{Current: current, Next: next}
saved := &svermaker.ProjectVersion{Current: current, Next: current}
serializer.ExistsFn = func() bool {
return true
}
serializer.DeserializeFn = func() (*svermaker.ProjectVersion, error) {
return saved, nil
}
serializer.SerializerFn = func(p svermaker.ProjectVersion) error {
return nil
}
p, err := pvs.Bump(svermaker.MINOR, nil)
m := semver.Manipulator{}
pre, _ := m.MakePrerelease("rc")
Expect(err).To(BeNil())
Expect(serializer.ExistsInvoked).To(BeTrue())
Expect(serializer.SerializerInvoked).To(BeTrue())
Expect(serializer.DeserializerInvoked).To(BeTrue())
expected.Current, _ = m.SetPrerelease(expected.Next, pre)
Expect(p).To(Equal(expected))
})
})
})
Context("When bumping for a major", func() {
It("should increase the major version on the next version", func() {
current := svermaker.Version{1, 1, 1, nil, nil}
next := svermaker.Version{2, 0, 0, nil, nil}
saved := &svermaker.ProjectVersion{Current: current, Next: current}
serializer.ExistsFn = func() bool {
return true
}
serializer.DeserializeFn = func() (*svermaker.ProjectVersion, error) {
return saved, nil
}
serializer.SerializerFn = func(p svermaker.ProjectVersion) error {
return nil
}
p, err := pvs.Bump(svermaker.MAJOR, nil)
Expect(err).To(BeNil())
Expect(serializer.ExistsInvoked).To(BeTrue())
Expect(serializer.SerializerInvoked).To(BeTrue())
Expect(serializer.DeserializerInvoked).To(BeTrue())
Expect(p.Next).To(Equal(next))
})
Context("When a prerelease version is set", func() {
It("should use the supplied prerelease version for current version", func() {
current := svermaker.Version{1, 1, 1, nil, nil}
next := svermaker.Version{2, 0, 0, nil, nil}
expected := &svermaker.ProjectVersion{Current: current, Next: next}
saved := &svermaker.ProjectVersion{Current: current, Next: current}
serializer.ExistsFn = func() bool {
return true
}
serializer.DeserializeFn = func() (*svermaker.ProjectVersion, error) {
return saved, nil
}
serializer.SerializerFn = func(p svermaker.ProjectVersion) error {
return nil
}
m := semver.Manipulator{}
pre, _ := m.MakePrerelease("testpre")
p, err := pvs.Bump(svermaker.MAJOR, pre)
Expect(err).To(BeNil())
Expect(serializer.ExistsInvoked).To(BeTrue())
Expect(serializer.SerializerInvoked).To(BeTrue())
Expect(serializer.DeserializerInvoked).To(BeTrue())
expected.Current, _ = m.SetPrerelease(expected.Next, pre)
Expect(p).To(Equal(expected))
})
})
Context("When a prerelease version is not set", func() {
It("should set the prerelease to rc for current version", func() {
current := svermaker.Version{1, 1, 1, nil, nil}
next := svermaker.Version{2, 0, 0, nil, nil}
expected := &svermaker.ProjectVersion{Current: current, Next: next}
saved := &svermaker.ProjectVersion{Current: current, Next: current}
serializer.ExistsFn = func() bool {
return true
}
serializer.DeserializeFn = func() (*svermaker.ProjectVersion, error) {
return saved, nil
}
serializer.SerializerFn = func(p svermaker.ProjectVersion) error {
return nil
}
p, err := pvs.Bump(svermaker.MAJOR, nil)
m := semver.Manipulator{}
pre, _ := m.MakePrerelease("rc")
Expect(err).To(BeNil())
Expect(serializer.ExistsInvoked).To(BeTrue())
Expect(serializer.SerializerInvoked).To(BeTrue())
Expect(serializer.DeserializerInvoked).To(BeTrue())
expected.Current, _ = m.SetPrerelease(expected.Next, pre)
Expect(p).To(Equal(expected))
})
})
})
})
Describe("Release()", func() {
It("should set the current version to the next version", func() {
current := svermaker.Version{1, 1, 1, nil, nil}
next := svermaker.Version{2, 0, 0, nil, nil}
expected := &svermaker.ProjectVersion{Current: next, Next: next}
saved := &svermaker.ProjectVersion{Current: current, Next: next}
serializer.ExistsFn = func() bool {
return true
}
serializer.DeserializeFn = func() (*svermaker.ProjectVersion, error) {
return saved, nil
}
serializer.SerializerFn = func(p svermaker.ProjectVersion) error {
return nil
}
p, err := pvs.Release()
Expect(err).To(BeNil())
Expect(serializer.ExistsInvoked).To(BeTrue())
Expect(serializer.SerializerInvoked).To(BeTrue())
Expect(serializer.DeserializerInvoked).To(BeTrue())
Expect(p).To(Equal(expected))
})
})
})
| mit |
COLORFULBOARD/revision | revision/client_manager.py | 2324 | # -*- coding: utf-8 -*-
"""
revision.client_manager
~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2018 by SENSY Inc.
:license: MIT, see LICENSE for more details.
"""
from revision.client import Client
from revision.exceptions import InvalidArgType
__all__ = (
"ClientManager",
)
class ClientManager(dict):
def __init__(self, clients=None):
"""
:param clients: An list of Client instances.
:type clients: list
"""
if isinstance(clients, list):
for config in clients:
self.add_client(self.instantiate_client(config))
def instantiate_client(self, config):
"""
:param config: The config object.
:type config: dict
:return: The instantiated class.
:rtype: :class:`revision.client.Client`
"""
modules = config.module.split('.')
class_name = modules.pop()
module_path = '.'.join(modules)
client_instance = getattr(
__import__(module_path, {}, {}, ['']),
class_name
)()
client_instance.add_config(config)
return client_instance
def has_client(self, client_key):
"""
:param client_key: The client key.
:type client_key: str
:return: Returns True if client_key is found.
:rtype: boolean
"""
return client_key in self
def get_client(self, client_key):
"""
:param client_key: The client key.
:type client_key: str
:return: Returns client instance or None if not found.
:rtype: :class:`revision.client.Client`
"""
return self.get(client_key, None)
def add_client(self, client):
"""
Adds the specified client to this manager.
:param client: The client to add into this manager.
:type client: :class:`revision.client.Client`
:return: The ClientManager instance (method chaining)
:rtype: :class:`revision.client_manager.ClientManager`
"""
if not isinstance(client, Client):
raise InvalidArgType()
if self.has_client(client.key):
return self
self[client.key] = client
return self
def __repr__(self):
return "<class 'revision.client_manager.ClientManager'>"
| mit |
milkcat/MilkCat | src/segmenter/out_of_vocabulary_word_recognizer.cc | 6143 | //
// The MIT License (MIT)
//
// Copyright 2013-2014 The MilkCat Project Developers
//
// 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.
//
// named_entity_recognitioin.cc --- Created at 2013-08-26
// out_of_vocabulary_word_recognitioin.cc --- Created at 2013-09-03
//
#include "segmenter/out_of_vocabulary_word_recognizer.h"
#include <stdio.h>
#include <string.h>
#include "common/model.h"
#include "common/reimu_trie.h"
#include "include/milkcat.h"
#include "segmenter/crf_segmenter.h"
#include "segmenter/term_instance.h"
#include "tokenizer/token_instance.h"
#include "util/util.h"
namespace milkcat {
OutOfVocabularyWordRecognizer *OutOfVocabularyWordRecognizer::New(
Model *model_factory,
Status *status) {
OutOfVocabularyWordRecognizer *self = new OutOfVocabularyWordRecognizer();
self->crf_segmenter_ = CRFSegmenter::New(model_factory, status);
if (status->ok()) {
self->term_instance_ = new TermInstance();
self->oov_property_ = model_factory->OOVProperty(status);
}
if (status->ok()) {
return self;
} else {
delete self;
return NULL;
}
}
OutOfVocabularyWordRecognizer::~OutOfVocabularyWordRecognizer() {
delete crf_segmenter_;
crf_segmenter_ = NULL;
delete term_instance_;
term_instance_ = NULL;
}
OutOfVocabularyWordRecognizer::OutOfVocabularyWordRecognizer():
term_instance_(NULL),
crf_segmenter_(NULL) {
}
void OutOfVocabularyWordRecognizer::GetOOVProperties(
TermInstance *term_instance) {
for (int i = 0; i < term_instance->size(); ++i)
oov_properties_[i] = kNoRecognize;
for (int i = 0; i < term_instance->size(); ++i) {
int token_number = term_instance->token_number_at(i);
int term_type = term_instance->term_type_at(i);
if (token_number > 1) {
continue;
} else if (term_type != Parser::kChineseWord) {
continue;
} else {
const char *term_text = term_instance->term_text_at(i);
int oov_property = oov_property_->Get(term_text, -1);
if (oov_property < 0) {
oov_properties_[i] = kDoRecognize;
} else {
switch (oov_property) {
case kOOVBeginOfWord:
oov_properties_[i] = kDoRecognize;
if (i < term_instance->size() - 1) {
oov_properties_[i + 1] = kDoRecognize;
}
break;
case kOOVEndOfWord:
oov_properties_[i] = kDoRecognize;
if (i > 0 && oov_properties_[i - 1] != kNeverRecognize) {
oov_properties_[i - 1] = kDoRecognize;
}
break;
case kOOVFilteredWord:
oov_properties_[i] = kNeverRecognize;
break;
}
}
}
}
}
void OutOfVocabularyWordRecognizer::Recognize(
TermInstance *term_instance,
TermInstance *in_term_instance,
TokenInstance *in_token_instance) {
int current_token = 0;
int current_term = 0;
int term_token_number;
int oov_begin_token = 0;
int oov_token_num = 0;
GetOOVProperties(in_term_instance);
for (int i = 0; i < in_term_instance->size(); ++i) {
term_token_number = in_term_instance->token_number_at(i);
if (oov_properties_[i] == kDoRecognize) {
oov_token_num++;
} else {
// Recognize token from oov_begin_token to current_token
if (oov_token_num > 1) {
RecognizeRange(in_token_instance, oov_begin_token, current_token);
for (int j = 0; j < term_instance_->size(); ++j) {
CopyTermValue(term_instance, current_term, term_instance_, j);
current_term++;
}
} else if (oov_token_num == 1) {
CopyTermValue(term_instance, current_term, in_term_instance, i - 1);
current_term++;
}
CopyTermValue(term_instance, current_term, in_term_instance, i);
oov_begin_token = current_token + term_token_number;
current_term++;
oov_token_num = 0;
}
current_token += term_token_number;
}
// Recognize remained tokens
if (oov_token_num > 1) {
RecognizeRange(in_token_instance, oov_begin_token, current_token);
for (int j = 0; j < term_instance_->size(); ++j) {
CopyTermValue(term_instance, current_term, term_instance_, j);
current_term++;
}
} else if (oov_token_num == 1) {
CopyTermValue(term_instance,
current_term,
in_term_instance,
in_term_instance->size() - 1);
current_term++;
}
term_instance->set_size(current_term);
}
void OutOfVocabularyWordRecognizer::CopyTermValue(
TermInstance *dest_term_instance,
int dest_postion,
TermInstance *src_term_instance,
int src_position) {
dest_term_instance->set_value_at(
dest_postion,
src_term_instance->term_text_at(src_position),
src_term_instance->token_number_at(src_position),
src_term_instance->term_type_at(src_position),
src_term_instance->term_id_at(src_position));
}
void OutOfVocabularyWordRecognizer::RecognizeRange(
TokenInstance *token_instance,
int begin,
int end) {
crf_segmenter_->SegmentRange(term_instance_, token_instance, begin, end);
}
} // namespace milkcat
| mit |
jrhorn424/recruiter | app/models/registration.rb | 639 | require 'composite_primary_keys'
class Registration < ActiveRecord::Base
self.primary_keys = :user_id, :session_id
belongs_to :user
belongs_to :session
validate :validate_allowness
def validate_allowness
if not self.user.experiments.exists?(id: self.session.experiment.id)
errors.add(:user, "isn't assigned to the corresponding experiment")
end
if Registration.where.not(session_id: self.session).exists?(session_id: self.session.experiment.sessions, user_id: self.user.id, participated: true)
errors.add(:session, "already participated")
end
end
self.primary_keys = :user_id, :session_id
end
| mit |
liuxx001/BodeAbp | src/modules/BodeAbp.Product/Attributes/ModelConfigs/ProductAttributeConfiguration.cs | 233 | using Abp.EntityFramework;
using BodeAbp.Product.Attributes.Domain;
namespace BodeAbp.Product.Attributes.ModelConfigs
{
public class ProductAttributeConfiguration : EntityConfigurationBase<ProductAttribute,int>
{
}
}
| mit |
gero3/three.js | test/unit/src/renderers/webgl/WebGLAttributes.tests.js | 732 | /* global QUnit */
import { WebGLAttributes } from '../../../../../src/renderers/webgl/WebGLAttributes';
export default QUnit.module( 'Renderers', () => {
QUnit.module( 'WebGL', () => {
QUnit.module( 'WebGLAttributes', () => {
// INSTANCING
QUnit.todo( 'Instancing', ( assert ) => {
assert.ok( false, 'everything\'s gonna be alright' );
} );
// PUBLIC STUFF
QUnit.todo( 'get', ( assert ) => {
assert.ok( false, 'everything\'s gonna be alright' );
} );
QUnit.todo( 'remove', ( assert ) => {
assert.ok( false, 'everything\'s gonna be alright' );
} );
QUnit.todo( 'update', ( assert ) => {
assert.ok( false, 'everything\'s gonna be alright' );
} );
} );
} );
} );
| mit |
ZWkang/simple-vue-project | src/lib/lazyload/index.js | 191 | /* eslint-disable*/
import lazyload from './lazy.js'
var MyPlugin = {}
MyPlugin.install = function(Vue,option){
Vue.prototype.lazyload = lazyload.init(option)
}
export default MyPlugin | mit |
NicoPennec/protractor | scripts/interactive_tests/interactive_test.js | 1987 | var env = require('../../spec/environment.js');
var InteractiveTest = require('./interactive_test_util').InteractiveTest;
var port = env.interactiveTestPort;
var test = new InteractiveTest('node lib/cli.js --elementExplorer true', port);
// Check state persists.
test.addCommandExpectation('var x = 3');
test.addCommandExpectation('x', '3');
// Check can return functions.
test.addCommandExpectation('var y = function(param) {return param;}');
test.addCommandExpectation('y', 'function (param) {return param;}');
// Check promises complete.
test.addCommandExpectation('browser.driver.getCurrentUrl()', 'data:,');
test.addCommandExpectation('browser.get("http://localhost:' + env.webServerDefaultPort + '")');
test.addCommandExpectation('browser.getCurrentUrl()',
'http://localhost:' + env.webServerDefaultPort + '/#/form');
// Check promises are resolved before being returned.
test.addCommandExpectation('var greetings = element(by.binding("greeting"))');
test.addCommandExpectation('greetings.getText()', 'Hiya');
// Check require is injected.
test.addCommandExpectation('var q = require("q")');
test.addCommandExpectation(
'var deferred = q.defer(); ' +
'setTimeout(function() {deferred.resolve(1)}, 100); ' +
'deferred.promise',
'1');
// Check errors are handled gracefully
test.addCommandExpectation('element(by.binding("nonexistent"))');
test.addCommandExpectation('element(by.binding("nonexistent")).getText()',
'ERROR: NoSuchElementError: No element found using locator: ' +
'by.binding("nonexistent")');
// Check complete calls
test.addCommandExpectation('\t',
'[["element(by.id(\'\'))","element(by.css(\'\'))",' +
'"element(by.name(\'\'))","element(by.binding(\'\'))",' +
'"element(by.xpath(\'\'))","element(by.tagName(\'\'))",' +
'"element(by.className(\'\'))"],""]');
test.addCommandExpectation('ele\t', '[["element"],"ele"]');
test.addCommandExpectation('br\t', '[["break","","browser"],"br"]');
test.run();
| mit |
0xbaadf00d/partialize | src/test/java/converters/BigDecimalConverter.java | 1967 | /*
* The MIT License (MIT)
*
* Copyright (c) 2016 Thibault Meyer
*
* 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 converters;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.zero_x_baadf00d.partialize.converter.Converter;
import java.math.BigDecimal;
/**
* BigDecimalConverter.
*
* @author Thibault Meyer
* @version 16.10.04
* @since 16.10.04
*/
public class BigDecimalConverter implements Converter<BigDecimal> {
@Override
public void convert(final String fieldName, final BigDecimal data, final ObjectNode node) {
node.put(fieldName, data.doubleValue());
}
@Override
public void convert(final String fieldName, final BigDecimal data, final ArrayNode node) {
node.add(data.doubleValue());
}
@Override
public Class<BigDecimal> getManagedObjectClass() {
return BigDecimal.class;
}
}
| mit |
ttoth/thesis | JavaProgram/integration-system/WekaConnector/src/main/java/hu/bme/aait/hermes/dialog/web/handler/GlobalWebSocketHandlerService.java | 2749 | package hu.bme.aait.hermes.dialog.web.handler;
import hu.bme.aait.hermes.dialog.web.dto.message.ClientMessage;
import hu.bme.aait.hermes.dialog.web.service.messageprocessor.MessageProcessorService;
import hu.bme.aait.hermes.dialog.web.service.messageprocessor.ProcessMessageType;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.PostConstruct;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.WebSocketSession;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/**
* Per connectiod based service for WS endpoints.
* Able to store clients in synchronizedSet.
* Maps messageProcessor services by enum type.
*/
@Service
public class GlobalWebSocketHandlerService {
final static Logger LOG = Logger.getLogger(GlobalWebSocketHandlerService.class);
@Autowired
private List<MessageProcessorService> messageProcessorServices;
private Set<WebSocketSession> connectedSockets = Collections.synchronizedSet(new HashSet<WebSocketSession>());
private EnumMap<ProcessMessageType, MessageProcessorService> messageProcessorServiceMap = new EnumMap<>(ProcessMessageType.class);
@PostConstruct
public void init() {
for (MessageProcessorService messageProcessorService : messageProcessorServices) {
messageProcessorServiceMap.put(messageProcessorService.getProcessMessageType(), messageProcessorService);
}
}
public void registerOpenConnection(WebSocketSession session) {
if (!connectedSockets.contains(session)) {
connectedSockets.add(session);
LOG.info("New connection opened by: " + session.getId() + " Totally connected current users: " + connectedSockets.size());
}
}
public void registerCloseConnection(WebSocketSession session) {
connectedSockets.remove(session);
LOG.info("Connection lost to user: " + session.getId() + " Totally connected current users: " + connectedSockets.size());
}
public void processMessage(WebSocketSession session, String message) throws Exception {
Gson gson = new GsonBuilder().create();
ClientMessage clientMessage = gson.fromJson(message, ClientMessage.class);
LOG.info("Websocket process message: " + clientMessage.getType() + "from: " + session.getId());
if (messageProcessorServiceMap.get(clientMessage.getType()) != null) {
messageProcessorServiceMap.get(clientMessage.getType()).processMessage(session, clientMessage);
} else {
throw new Exception("No registered message processor found for: " + clientMessage.getType().toString());
}
}
}
| mit |
retaxJS/retax-seed | src/reducers/loading.js | 1044 | import { reducerFactory } from 'retax';
import { fromJS } from 'immutable';
import * as ACTIONS from 'constants/actions';
function getInitialState() {
return fromJS({
value: {},
});
}
function startLoading(ACTION, state) {
const currentValue = state.getIn(['value', ACTION, 'value']);
const currentMax = state.getIn(['value', ACTION, 'max']);
return state.mergeIn(['value'], {
[ACTION]: {
isLoading: true,
value: currentValue || 0,
max: currentMax || 0,
},
});
}
function finishLoading(ACTION, state) {
return state.setIn(['value', ACTION], fromJS({}));
}
const reducers = Object.values(ACTIONS).reduce((res, ACTION) => {
if (!ACTION.LOADING || !ACTION.ERROR || !ACTION.SUCCESS) return res;
return {
...res,
[ACTION.LOADING]: startLoading.bind(null, ACTION.value),
[ACTION.ERROR]: finishLoading.bind(null, ACTION.value),
[ACTION.SUCCESS]: finishLoading.bind(null, ACTION.value),
};
}, {});
export default reducerFactory(
getInitialState(),
{
...reducers,
}
);
| mit |
paparony03/osu-framework | osu.Framework.Testing/Drawables/Steps/AssertButton.cs | 912 | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using OpenTK.Graphics;
namespace osu.Framework.Testing.Drawables.Steps
{
public class AssertButton : StepButton
{
public Func<bool> Assertion;
public string ExtendedDescription;
public AssertButton()
{
BackgroundColour = Color4.OrangeRed;
Action += checkAssert;
}
private void checkAssert()
{
if (Assertion())
{
Success();
BackgroundColour = Color4.YellowGreen;
}
else
throw new Exception($"{Text} {ExtendedDescription}");
}
public override string ToString() => "Assert: " + base.ToString();
}
} | mit |
dicarlo2/ScalaEquals | core-test/src/main/scala/org/scalaequals/test/ParameterizedClass.scala | 1522 | /*
* Copyright (c) 2013 Alex DiCarlo
*
* 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 org.scalaequals.test
import org.scalaequals.ScalaEquals
class ParameterizedClass[A, +B, -C](val x: A, val y: B) {
def testContravariant(param: C): Boolean = true
override def equals(other: Any): Boolean = ScalaEquals.equal
override def hashCode(): Int = ScalaEquals.hash
def canEqual(other: Any): Boolean = ScalaEquals.canEquals
override def toString: String = ScalaEquals.genString
} | mit |
gabhijit/ipgiri | ipv4_routing_table.py | 9854 | #
# Refer to LICENSE file and README file for licensing information.
#
"""
An implementation of IPv4 Routing table that does longest prefix match.
This implementation is based on ideas from the following sources (though it is
not an actual implementation of any of these ideas).
Click Modular Router - RadixIPLookup Element
(http://www.read.cs.ucla.edu/click/elements/radixiplookup)
Broad scheme is as follows -
There are 4 levels of buckets.
First level is a list of 64K entries for first 16 bits
Second level is a list of 256 entries for each of the 'third' octet
Third level is a list of 16 entries for the higher nibble of the last octet
Final level is a list of 16 entries for the lower nibble of the last octet.
Each Entry looks like following
- final (there's a routing prefix corresponding to this entry)
- children (empty or a table of entries)
- prefix len (Length of the prefix that filled this entry - see below. why
this may be needed).
Lookup
- First we match 'upper 16 bits with an entry'. If that has got 'final' bit
set, we 'remember' match.
- If it's got 'children' we index into the child corresponding to third byte
If it's got a 'final' flag set we 'update' the match. If no children
the current match is the best match. If has children continue looking into
next level remembering match
Update
Update is a bit tricky. Let's say we've a 12.0.0.0/8 prefix. Now we've to
mark entries in the first list from 12.0 - 12.255. with this. What if we now
encounter a 12.1.0.0/16 route? Update the 12.1 entry with the latest info
leaving others untouched so the table would look like
12.0 -> A (final)
12.1 -> B (final)
12.3 -> A (final)
...
...
12.255 -> A (final)
We'd overwrite 12.1 -> A with B, because when we are updating 12.1, we'c check
the current prefix length (8 for 12.0.0.0/8) with new prefix length
(16 for 12.1.0.0/16) and update the higher prefix length.
What if the order of prefixes learnt was reversed? ie. We learn about
12.1.0.0/16 first and later about 12.0.0.0/8
12.1 can be populated as
12.1 -> B (final)
Now when we want to populate 12.0 (a lesser prefix), when we encounter
12.1 -> B, we'd check for prefix length. Prefix length of the entry is longer
we'd not overwrite the entry
"""
from socket import inet_aton
import struct
import numpy as np
RouteEntryNP = np.dtype([('final', 'u1'), ('prefix_len', 'u1'),
('output_idx', '>u4'), ('children', 'O')])
class RouteEntry:
def __init__(self, pre_len, final, output_idx):
"""Prefix Length of this Entry. Whether this entry is final or not and
output index for this entry (only valid if this entry is final)."""
self.prefix_len = pre_len
self.final = final
self.output_idx = output_idx
self.children = None
#self.table_idx = -1
#self.table_level = -1
#def add_childrens(self, entry_table):
# """ Adds children to a given entry."""
# self.children = entry_table
def __repr__(self):
if self.children is None and self.output_idx == -1:
return ''
s = '%stable_idx:%d,final:%r,output_idx:%s\n' % \
("\t"*self.table_level, self.table_idx,
self.final, self.output_idx)
s = 'final:%r, output_idx:%s' % (self.final, self.output_idx)
if self.children is None:
return s
for child in self.children:
s += repr(child)
return s
# The class below is deprecated, but still is here for reference which depicts
# basic structre. Numpy 'dtype' RouteEntryNP does exactly the same
class RouteTable:
def __init__(self, filename=None):
self.table_sizes = [ 1 << 16, 1 << 8, 1 << 4, 1 << 4]
self.levels = [16, 24, 28, 32]
if filename is None:
self.level0_table = np.zeros(self.table_sizes[0], RouteEntryNP)
self.rtentries_alloced = 0
self.rtentries_alloced += self.table_sizes[0]
else:
self._load_table(filename)
# FIXME : Get this right
self.rtentries_alloced = 0
#for i in range(self.table_sizes[0]):
#self.level0_table.append(RouteEntry(0,0,0))
def lookup(self, ip_address):
""" Looks up an IP address and returns an output Index"""
ip_arr = [ord(x) for x in inet_aton(ip_address)]
match = None
tbl = self.level0_table
for i, level in enumerate(self.levels):
idx, _ = self._idx_from_tuple(ip_arr, 32, i)
entry = tbl[idx]
if entry['final'] == 1:
match = entry['output_idx']
if entry['children'] != 0:
tbl = entry['children']
else:
break
return match
def add(self, prefix, length, dest_idx):
""" Adds a prefix to routing table."""
prefix_arr = [ord(x) for x in inet_aton(prefix)]
level = 0
tbl = self.level0_table
while level < len(self.levels):
idx_base, span = self._idx_from_tuple(prefix_arr,
length, level)
lvl_prelen = self.levels[level]
tblsz = self.table_sizes[level]
nxtsz = self.table_sizes[level+1] if level < 3 else 0
i = 0
while i < span:
assert tbl is not None
entry = tbl[idx_base+i]
#entry.table_idx = idx_base + i
#entry.table_level = level
if length <= lvl_prelen:
#entry.entry = struct.pack('>BBI', True, length, dest_idx)
entry['final'] = 1
entry['prefix_len'] = length
entry['output_idx'] = dest_idx
else:
if entry['children'] != 0:
break
tbl = np.zeros(nxtsz, RouteEntryNP)
self.rtentries_alloced += nxtsz
entry['children'] = tbl
i += 1
if lvl_prelen >= length: # Break from outer loop
break
level += 1
tbl = entry['children']
def delete(self, prefix, length):
"Deletes an entry in the routing table."
prefix_arr = [ord(x) for x in inet_aton(prefix)]
level = 0
tbl = self.level0_table
while level < len(self.levels):
idx_base, span = self._idx_from_tuple(prefix_arr,
length, level)
lvl_prelen = self.levels[level]
tblsz = self.table_sizes[level]
nxtsz = self.table_sizes[level+1] if level < 3 else 0
i = 0
while i < span:
entry = tbl[idx_base+i]
if length <= lvl_prelen:
#entry.entry = struct.pack('>BBI', False, 0, 0)
entry['final'] = 0
entry['prefix_len'] = 0
entry['output_idx'] = 0
else:
tbl = entry['children']
# FIXME : Add code to delete the entry.children
# if occupation of table is zero
i += 1
level += 1
def _idx_from_tuple(self, prefix_arr, prelen, level):
_levels = [16, 24, 28, 32]
_level_edges = [(0,2),(2,3), (3,4), (3,4)]
begin, end = _level_edges[level]
leveloff = _levels[level]
if prelen > leveloff:
span = 1
else:
span = 1 << (leveloff - prelen)
prefix_arr = prefix_arr[begin:end][::-1]
idx = reduce(lambda x,y: x+ ((1 << (8*y[0])) * y[1]),
enumerate(prefix_arr), 0)
if level == 2:
idx = idx >> 4
if level == 3:
idx = idx & 0x0F
return idx, span
def print_entry(self, entry, tblidx, level):
if entry['output_idx'] != 0 or entry['children'] != 0:
print "%sidx:%d,final:%d,output:%d" % \
('\t'*level, tblidx, entry['final'], entry['output_idx'])
if entry['children'] != 0:
for i, entry2 in enumerate(entry['children']):
self.print_entry(entry2, i, level+1)
def print_table(self):
for i, entry in enumerate(self.level0_table):
self.print_entry(entry, i, 0)
def save_table(self, filename):
allocced = np.zeros(1, '>u4')
allocced[0] = self.rtentries_alloced
with open(filename, 'wb+') as f:
np.savez(f, allocced=allocced, tbl0=self.level0_table)
def _load_table(self, filename):
x = np.load(filename)
self.level0_table = x['tbl0']
self.rtentries_alloced = x['allocced'][0]
if __name__ == '__main__':
r = RouteTable()
#r.add('12.0.0.0', 8, 2000)
#r.add('12.0.1.0', 24, 2001)
#r.add('12.0.2.16', 28, 2004)
#r.add('12.0.2.0', 24, 2005)
#r.add('12.1.128.0', 23, 2003)
#r.add('12.0.0.0', 16, 2002)
#r.add('212.85.129.0', 24, '134.222.85.45')
#r.add('210.51.225.0', 24, '193.251.245.6')
#r.add('209.136.89.0', 24, '12.0.1.63')
#r.add('209.34.243.0', 24, '12.0.1.63')
r.add('202.209.199.0', 24, 230)
r.add('202.209.199.0', 28, 231)
r.add('202.209.199.8', 29, 232)
r.add('202.209.199.48',29, 233)
r.print_table()
print r.lookup('202.209.199.49')
print r.lookup('202.209.199.8')
print r.lookup('202.209.199.9')
print r.lookup('202.209.199.7')
r.delete('202.209.199.0', 28)
r.delete('202.209.199.8', 29)
r.print_table()
r.add('202.209.199.8', 29, 232)
r.add('202.209.199.0', 28, 231)
r.print_table()
r.save_table('rttable.now')
print "****************************"
r2 = RouteTable('rttable.now')
r2.print_table()
| mit |
shoelzer/SharpDX | Source/Toolkit/SharpDX.Toolkit.Graphics/GraphicsResourceContentReaderBase.cs | 2319 | // Copyright (c) 2010-2013 SharpDX - Alexandre Mutel
//
// 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.
using System;
using System.IO;
using SharpDX.Toolkit.Content;
namespace SharpDX.Toolkit.Graphics
{
/// <summary>
/// Base class for all GraphicsResource content reader.
/// </summary>
/// <typeparam name="T"></typeparam>
abstract class GraphicsResourceContentReaderBase<T> : IContentReader
{
object IContentReader.ReadContent(IContentManager readerManager, string assetName, Stream stream, out bool keepStreamOpen, object options)
{
keepStreamOpen = false;
var service = readerManager.ServiceProvider.GetService(typeof (IGraphicsDeviceService)) as IGraphicsDeviceService;
if (service == null)
throw new InvalidOperationException("Unable to retrieve a IGraphicsDeviceService service provider");
if (service.GraphicsDevice == null)
throw new InvalidOperationException("GraphicsDevice is not initialized");
return ReadContent(readerManager, service.GraphicsDevice, assetName, stream);
}
protected abstract T ReadContent(IContentManager readerManager, GraphicsDevice device, string assetName, Stream stream, object options = null);
}
} | mit |
akromm/.NetRayTracer | NetRayTracer/Properties/AssemblyInfo.cs | 1400 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("NetRayTracer")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("NetRayTracer")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("cd696c45-f76d-468b-acf6-855b8076f5ad")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit |
navalev/azure-sdk-for-java | sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventProcessorClientBuilderTest.java | 3624 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.messaging.eventhubs;
import com.azure.messaging.eventhubs.implementation.ClientConstants;
import org.junit.jupiter.api.Test;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Locale;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* Unit tests for {@link EventProcessorClientBuilder}.
*/
public class EventProcessorClientBuilderTest {
private static final String NAMESPACE_NAME = "dummyNamespaceName";
private static final String DEFAULT_DOMAIN_NAME = "servicebus.windows.net/";
private static final String EVENT_HUB_NAME = "eventHubName";
private static final String SHARED_ACCESS_KEY_NAME = "dummySasKeyName";
private static final String SHARED_ACCESS_KEY = "dummySasKey";
private static final String ENDPOINT = getURI(ClientConstants.ENDPOINT_FORMAT, NAMESPACE_NAME, DEFAULT_DOMAIN_NAME)
.toString();
private static final String CORRECT_CONNECTION_STRING = String
.format("Endpoint=%s;SharedAccessKeyName=%s;SharedAccessKey=%s;EntityPath=%s",
ENDPOINT, SHARED_ACCESS_KEY_NAME, SHARED_ACCESS_KEY, EVENT_HUB_NAME);
private static URI getURI(String endpointFormat, String namespace, String domainName) {
try {
return new URI(String.format(Locale.US, endpointFormat, namespace, domainName));
} catch (URISyntaxException exception) {
throw new IllegalArgumentException(String.format(Locale.US,
"Invalid namespace name: %s", namespace), exception);
}
}
@Test
public void testEventProcessorBuilderMissingProperties() {
assertThrows(NullPointerException.class, () -> {
EventProcessorClient eventProcessorClient = new EventProcessorClientBuilder()
.checkpointStore(new InMemoryCheckpointStore())
.processEvent(eventContext -> {
System.out.println("Partition id = " + eventContext.getPartitionContext().getPartitionId() + " and "
+ "sequence number of event = " + eventContext.getEventData().getSequenceNumber());
})
.processError(errorContext -> {
System.out.printf("Error occurred in partition processor for partition {}, {}",
errorContext.getPartitionContext().getPartitionId(),
errorContext.getThrowable());
})
.buildEventProcessorClient();
});
}
@Test
public void testEventProcessorBuilderWithProcessEvent() {
EventProcessorClient eventProcessorClient = new EventProcessorClientBuilder()
.connectionString(CORRECT_CONNECTION_STRING)
.consumerGroup("consumer-group")
.processEvent(eventContext -> {
System.out.println("Partition id = " + eventContext.getPartitionContext().getPartitionId() + " and "
+ "sequence number of event = " + eventContext.getEventData().getSequenceNumber());
})
.processError(errorContext -> {
System.out.printf("Error occurred in partition processor for partition {}, {}",
errorContext.getPartitionContext().getPartitionId(),
errorContext.getThrowable());
})
.checkpointStore(new InMemoryCheckpointStore())
.buildEventProcessorClient();
assertNotNull(eventProcessorClient);
}
}
| mit |
jdurbin/sandbox | python/args/multiple.py | 226 | #!/usr/bin/env python3
import sys,argparse
parser = argparse.ArgumentParser()
parser.add_argument('-foo', nargs='+', help='foo values', required=False)
args = parser.parse_args()
for foo in args.foo:
print("Foo: ",foo) | mit |
bgaborg/aut-j2ee-hw | ebank-ejb/src/main/java/com/bg/ebank/entity/Groups.java | 2551 | /**
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
*
* You may not modify, use, reproduce, or distribute this software except in
* compliance with the terms of the License at:
* http://java.net/projects/javaeetutorial/pages/BerkeleyLicense
*/
package com.bg.ebank.entity;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author b
*/
@Entity
@Table(name = "GROUPS")
@NamedQueries({
@NamedQuery(name = "Group.findAll", query = "SELECT g FROM Groups g"),
@NamedQuery(name = "Group.findByName", query = "SELECT g FROM Groups g WHERE g.name = :name"),
@NamedQuery(name = "Group.findByDescription", query = "SELECT g FROM Groups g WHERE g.description = :description")})
public class Groups implements Serializable {
@Id
@NotNull
@Size(min = 1, max = 50)
@Column(name = "name", unique = true)
private String name;
@Size(max = 300)
@Column(name = "description")
private String description;
@ManyToMany(mappedBy = "groupsList", fetch = FetchType.EAGER)
private List<User> userList;
public Groups() {
this.userList = new ArrayList<>();
}
public Groups(String name, String description) {
this.name = name;
this.description = description;
this.userList = new ArrayList<>();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<User> getUserList() {
return userList;
}
public void setUserList(List<User> UserList) {
this.userList = UserList;
}
@Override
public int hashCode() {
int hash = 0;
hash += (name != null ? name.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
if (!(object instanceof Groups)) {
return false;
}
Groups other = (Groups) object;
if ((this.name == null && other.name != null) || (this.name != null && !this.name.equals(other.name))) {
return false;
}
return true;
}
@Override
public String toString() {
return name;
}
}
| mit |
unrealities/warning-track | models/master_scoreboard.go | 4184 | package models
import "time"
type Scoreboard struct {
Dates []struct {
Date string `json:"date"`
Games []struct {
GamePk int `json:"gamePk"`
GameType string `json:"gameType"`
Season string `json:"season"`
GameDate time.Time `json:"gameDate"`
Teams struct {
Away struct {
Team struct {
ID int64 `json:"id"`
Abbreviation string `json:"abbreviation"`
} `json:"team"`
} `json:"away"`
Home struct {
Team struct {
ID int64 `json:"id"`
Abbreviation string `json:"abbreviation"`
} `json:"team"`
} `json:"home"`
} `json:"teams"`
Linescore struct {
CurrentInning int `json:"currentInning"`
CurrentInningOrdinal string `json:"currentInningOrdinal"`
InningState string `json:"inningState"`
InningHalf string `json:"inningHalf"`
IsTopInning bool `json:"isTopInning"`
ScheduledInnings int `json:"scheduledInnings"`
Innings []struct {
Num int `json:"num"`
OrdinalNum string `json:"ordinalNum"`
Home struct {
Runs int `json:"runs"`
Hits int `json:"hits"`
Errors int `json:"errors"`
LeftOnBase int `json:"leftOnBase"`
} `json:"home"`
Away struct {
Runs int `json:"runs"`
Hits int `json:"hits"`
Errors int `json:"errors"`
LeftOnBase int `json:"leftOnBase"`
} `json:"away"`
} `json:"innings"`
Teams struct {
Home struct {
Runs int `json:"runs"`
Hits int `json:"hits"`
Errors int `json:"errors"`
LeftOnBase int `json:"leftOnBase"`
} `json:"home"`
Away struct {
Runs int `json:"runs"`
Hits int `json:"hits"`
Errors int `json:"errors"`
LeftOnBase int `json:"leftOnBase"`
} `json:"away"`
} `json:"teams"`
Defense struct {
Batter struct {
ID int `json:"id"`
FullName string `json:"fullName"`
Link string `json:"link"`
} `json:"batter"`
OnDeck struct {
ID int `json:"id"`
FullName string `json:"fullName"`
Link string `json:"link"`
} `json:"onDeck"`
InHole struct {
ID int `json:"id"`
FullName string `json:"fullName"`
Link string `json:"link"`
} `json:"inHole"`
} `json:"defense"`
Offense Offense `json:"offense"`
Balls int `json:"balls"`
Strikes int `json:"strikes"`
Outs int `json:"outs"`
} `json:"linescore,omitempty"`
Content struct {
Media struct {
Epg []struct {
Title string `json:"title"`
Items []struct {
ID int `json:"id"`
ContentID string `json:"contentId"`
CallLetters string `json:"callLetters"`
FoxAuthRequired bool `json:"foxAuthRequired"`
TbsAuthRequired bool `json:"tbsAuthRequired"`
EspnAuthRequired bool `json:"espnAuthRequired"`
Fs1AuthRequired bool `json:"fs1AuthRequired"`
MlbnAuthRequired bool `json:"mlbnAuthRequired"`
FreeGame bool `json:"freeGame"`
} `json:"items"`
FreeGame bool `json:"freeGame"`
EnhancedGame bool `json:"enhancedGame"`
} `json:"epg"`
} `json:"media"`
} `json:"content"`
Status struct {
AbstractGameState string `json:"abstractGameState"`
CodedGameState string `json:"codedGameState"`
DetailedState string `json:"detailedState"`
StatusCode string `json:"statusCode"`
AbstractGameCode string `json:"abstractGameCode"`
} `json:"status"`
} `json:"games"`
} `json:"dates"`
}
type Offense struct {
First struct {
ID int `json:"id"`
FullName string `json:"fullName"`
Link string `json:"link"`
} `json:"first,omitempty"`
Second struct {
ID int `json:"id"`
FullName string `json:"fullName"`
Link string `json:"link"`
} `json:"second,omitempty"`
Third struct {
ID int `json:"id"`
FullName string `json:"fullName"`
Link string `json:"link"`
} `json:"third,omitempty"`
}
| mit |
openpprn/opn | test/controllers/blog_controller_test.rb | 237 | require 'test_helper'
class BlogControllerTest < ActionController::TestCase
test "User can see only accepted posts" do
login(users(:user_1))
get :blog
assert_equal [posts(:accepted_blog_post)], assigns(:posts)
end
end | mit |
M4rk07/matey-rest-api | src/App/Controllers/AbstractController.php | 808 | <?php
/**
* Created by PhpStorm.
* User: marko
* Date: 4.10.16.
* Time: 01.08
*/
namespace App\Controllers;
use App\Paths\Paths;
use App\Services\BaseService;
use App\Services\Redis\RedisService;
use App\Validators\UnsignedInteger;
use AuthBucket\OAuth2\Exception\InvalidRequestException;
use AuthBucket\OAuth2\Model\ModelManagerFactoryInterface;
use GuzzleHttp\Client;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Constraints\GreaterThan;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Type;
use Symfony\Component\Validator\Validator\ValidatorInterface;
/*
* Controller that is used as main controller for every other
*/
abstract class AbstractController
{
} | mit |
lizconlan/html-diff | models/sourcefile.rb | 628 | # encoding: utf-8
class Sourcefile
attr_reader :raw_text, :lines, :header
def initialize(text)
sanitize_text(text)
@raw_text = text
@lines = @raw_text.split("\n")
if @lines.first =~ /^diff --git/
line = ""
header_lines = []
@lines.reverse!
until line =~ /^@@ [^@]* @@/
line = @lines.pop
header_lines << line
end
@lines.reverse!
@header = header_lines.join("\n")
end
end
private
def sanitize_text(text)
text.encode!('UTF-16LE', 'UTF-8', :invalid => :replace, :replace => '')
text.encode!('UTF-8', 'UTF-16LE')
end
end | mit |
renotoaster/flame.js | views/lazy_tree_view.js | 12609 | //= require ./lazy_list_view
//= require ./lazy_tree_item_view
/**
The tree in the `LazyTreeView` is being rendered as a flat list, with items
being indented to give the impression of a tree structure.
We keep a number of internal caches to easily map this flat list onto the
tree we're rendering.
TODO * `LazyTreeView` currently has the limitation that it does not allow
dragging items between different levels.
@class LazyTreeView
@extends LazyListView
*/
Flame.LazyTreeView = Flame.LazyListView.extend({
classNames: ['flame-tree-view', 'flame-lazy-tree-view'],
itemViewClass: Flame.LazyTreeItemView,
_rowToItemCache: null,
_itemToRowCache: null,
_itemToLevelCache: null,
_itemToParentCache: null,
_expandedItems: null,
_numberOfCachedRows: null,
init: function() {
this._invalidateRowCache();
this._expandedItems = Ember.Set.create();
// Call the super-constructor last as Flame.ListView constructor calls #_selectionDidChange() which causes
// calls to #_setIsSelectedStatus() that calls #rowForItem() which expects the caches to be set up.
this._super();
},
numberOfRowsChanged: function() {
this._invalidateRowCache();
this.loadCache();
this._super();
},
numberOfRows: function() {
return this._numberOfCachedRows;
},
loadItemIntoCache: function(item, level, parent) {
this._rowToItemCache[this._numberOfCachedRows] = item;
this._itemToRowCache.set(item, this._numberOfCachedRows);
this._itemToLevelCache.set(item, level);
if (parent) this._itemToParentCache.set(item, parent);
this._numberOfCachedRows++;
// If an item is not expanded, we don't care about its children
if (!this._expandedItems.contains(item)) return;
// Handle children
var children = item.get('treeItemChildren');
if (children) {
var length = children.get('length');
for (var i = 0; i < length; i++) {
this.loadItemIntoCache(children.objectAt(i), level + 1, item);
}
}
},
loadCache: function() {
var content = this.get('content');
var length = content.get('length');
for (var i = 0; i < length; i++) {
this.loadItemIntoCache(content.objectAt(i), 0);
}
},
viewClassForItem: function(item) {
var itemViewClasses = this.get('itemViewClasses');
return itemViewClasses[item.constructor.toString()];
},
itemForRow: function(row) {
return this._rowToItemCache[row];
},
rowForItem: function(item) {
return this._itemToRowCache.get(item);
},
levelForItem: function(item) {
return this._itemToLevelCache.get(item);
},
/** The tree view needs to additionally set the correct indentation level */
viewForRow: function(row) {
var item = this.itemForRow(row);
var isExpanded = this._expandedItems.contains(item);
var view = this._super(row, { isExpanded: isExpanded });
view.set('isExpanded', isExpanded);
var level = this._itemToLevelCache.get(item);
// Check if we already have the correct indentation level
if (view._indentationLevel !== level) {
var classNames = view.get('classNames');
classNames.removeObject('level-' + (view._indentationLevel + 1));
classNames.pushObject('level-' + (level + 1));
view._indentationLevel = level;
}
return view;
},
_invalidateRowCache: function() {
this._rowToItemCache = [];
this._itemToRowCache = Ember.Map.create();
this._itemToLevelCache = Ember.Map.create();
this._itemToParentCache = Ember.Map.create();
this._numberOfCachedRows = 0;
},
isExpandable: function(item) {
return true;
},
collapseItem: function(item) {
this.changeIsExpanded(item, false);
},
expandItem: function(item) {
this.changeIsExpanded(item, true);
},
changeIsExpanded: function(item, status) {
if (status) {
this._expandedItems.add(item);
} else {
this._expandedItems.remove(item);
}
var row = this.rowForItem(item);
var view = this.childViewForIndex(row);
if (view && !view.get('isExpanded')) {
view.set('isExpanded', status);
if (status) {
this.toggleItem(view);
}
}
},
/**
This is where we expand or collapse an item in the `LazyTreeView`.
The expanding or collapsing is done in these steps:
1. Record the expanded/collapsed status of the item.
2. Update the position of views that have shifted due to an item being
expanded or collapsed.
3. Remove views that were used to render a subtree that is now collapsed.
4. Render missing views; When collapsing an item, we might need to render
extra views to fill up the gap created at the bottom of the visible area.
This also renders the subtree of the item we just expanded.
@param view {Flame.LazyListItemView} The view that was clicked to expand or collapse the item
*/
toggleItem: function(view) {
var item = view.get('content');
var isExpanded = view.get('isExpanded');
if (isExpanded) {
this._expandedItems.add(item);
} else {
this._expandedItems.remove(item);
}
this.numberOfRowsChanged();
// Update rendering
var indices = [];
var range = this._rowsToRenderRange(this._lastScrollHeight, this._lastScrollTop);
this.forEach(function(view) {
var contentIndex = view.get('contentIndex');
var content = view.get('content');
var row = this.rowForItem(content);
if (typeof row === 'undefined' && typeof contentIndex !== 'undefined') {
this._recycleView(view);
} else if (typeof contentIndex !== 'undefined') {
indices.push(row);
if (contentIndex !== row) {
view.set('contentIndex', row);
var itemHeight = this.itemHeightForRow(row);
view.$().css('top', row * itemHeight + 'px');
}
if (row < range.start || row > range.end) {
this._recycleView(view);
}
}
}, this);
// Render missing views
for (var i = range.start; i <= range.end; i++) {
if (indices.indexOf(i) === -1) {
this.viewForRow(i);
}
}
this._hideRecycledViews();
},
moveRight: function() {
return this._collapseOrExpandSelection('expand');
},
moveLeft: function() {
return this._collapseOrExpandSelection('collapse');
},
_collapseOrExpandSelection: function(action) {
var selection = this.get('selection');
if (selection) {
var row = this.rowForItem(selection);
var view = this.childViewForIndex(row);
if (view) {
if (action === 'collapse' && view.get('isExpanded')) {
view.set('isExpanded', false);
this.toggleItem(view);
return true;
} else if (action === 'expand' && !view.get('isExpanded')) {
view.set('isExpanded', true);
this.toggleItem(view);
return true;
}
} else {
// The view is currently not visible, just record the status
if (this._expandedItems.contains(selection)) {
this._expandedItems.remove(selection);
} else {
this._expandedItems.add(selection);
}
return true;
}
}
return false;
},
closestCommonAncestor: function(item1, item2) {
var ancestor = this._itemToParentCache.get(item1);
var parent = this._itemToParentCache.get(item2);
while (parent) {
if (parent === ancestor) {
return parent;
} else {
parent = this._itemToParentCache.get(parent);
}
}
},
isValidDrop: function(item, dropParent) {
return true;
},
/**
@param {Object} draggingInfo
@param {Number} proposedIndex
@param {Number} originalIndex
*/
indexForMovedItem: function(draggingInfo, proposedIndex, originalIndex) {
// Get items of interest
var itemFrom = this.itemForRow(originalIndex);
var itemAbove = this.itemForRow(proposedIndex - 1);
var itemBelow = this.itemForRow(proposedIndex);
// Bounds checking
if (proposedIndex < 0) proposedIndex = 0;
if (proposedIndex > this.numberOfRows()) proposedIndex = this.numberOfRows();
// Only allow moving between the same level
var itemLevel = this.levelForItem(itemFrom);
var acceptedIndex,
toParent,
toPosition;
if (itemBelow && this.levelForItem(itemBelow) === itemLevel) {
acceptedIndex = proposedIndex;
toParent = this._itemToParentCache.get(itemBelow);
toPosition = (toParent && toParent.get('treeItemChildren') || this.get('content')).indexOf(itemBelow);
} else if (itemAbove && this.levelForItem(itemAbove) === itemLevel && !this._expandedItems.contains(itemAbove)) {
acceptedIndex = proposedIndex;
toParent = this._itemToParentCache.get(itemAbove);
toPosition = toParent ? toParent.get('treeItemChildren.length') : this.get('content.length');
} else if ((!itemBelow || (itemBelow && this.levelForItem(itemBelow) < itemLevel)) &&
itemAbove && this.levelForItem(itemAbove) > itemLevel) {
acceptedIndex = proposedIndex;
toParent = this.closestCommonAncestor(itemFrom, itemAbove);
toPosition = toParent ? toParent.get('treeItemChildren.length') : this.get('content.length');
} else if (itemAbove && itemLevel - 1 === this.levelForItem(itemAbove) && this._expandedItems.contains(itemAbove)) {
// Dragging into parent item that is currently empty and open
acceptedIndex = proposedIndex;
toParent = itemAbove;
toPosition = 0;
} else {
return draggingInfo;
}
if (!this.isValidDrop(itemFrom, toParent)) return draggingInfo;
return { currentIndex: acceptedIndex, toParent: toParent, toPosition: toPosition };
},
moveItem: function(from, draggingInfo) {
var movedView = this.childViewForIndex(from);
var to = draggingInfo.currentIndex;
var direction = from < to ? -1 : 1;
var itemHeight = this.get('itemHeight');
this.forEachChildView(function(view) {
var contentIndex = view.get('contentIndex');
if (contentIndex > from && contentIndex < to ||
contentIndex < from && contentIndex >= to) {
view.set('contentIndex', contentIndex + direction);
view.$().animate({top: view.get('contentIndex') * itemHeight + 'px'});
}
});
if (direction < 0) to--;
movedView.set('contentIndex', to);
movedView.$().animate({top: to * itemHeight + 'px'});
if (direction < 0) to++;
var fromItem = this.itemForRow(from);
var fromParent = this._itemToParentCache.get(fromItem);
var toParent = draggingInfo.toParent || fromParent;
var fromContent = fromParent ? fromParent.get('treeItemChildren') : this.get('content');
var toContent = toParent ? toParent.get('treeItemChildren') : this.get('content');
if (fromContent === toContent && from < to) draggingInfo.toPosition--;
this._suppressObservers = true;
fromContent.removeObject(fromItem);
toContent.insertAt(draggingInfo.toPosition, fromItem);
this.numberOfRowsChanged();
// Keep suppressing observers until the next runloop
Ember.run.next(this, function() {
this._suppressObservers = false;
});
var delegate = this.get('reorderDelegate');
if (delegate) {
Ember.run.next(this, function() {
delegate.didReorderContent(toContent);
});
}
}
});
| mit |
fetus-hina/stat.ink | resources/react/saga/myLatestBattles.js | 746 | import axios from 'axios';
import {
call,
put,
takeLatest
} from 'redux-saga/effects';
import {
FETCH_MY_LATEST_BATTLES,
fetchMyLatestBattlesFailed,
fetchMyLatestBattlesSuccess
} from '../actions/myLatestBattles';
function requestGetApi () {
return axios
.get('/api/internal/my-latest-battles')
.then(response => {
return {
data: response.data
};
})
.catch(error => {
return {
error: error
};
});
}
function * fetch () {
const { data, error } = yield call(requestGetApi);
if (data) {
yield put(fetchMyLatestBattlesSuccess(data));
} else {
yield put(fetchMyLatestBattlesFailed(error));
}
}
export default [takeLatest(FETCH_MY_LATEST_BATTLES, fetch)];
| mit |
Szab/dmlib | src/operations/filter.js | 236 | import { DataSource } from '../dataSources/DataSource';
DataSource.registerOperation('filter', function filter(data, filteringFn) {
if (!Array.isArray(data)) {
data = [data];
}
return data.filter(filteringFn);
});
| mit |
Alex-Sokolov/vuejs.org | themes/vue/source/js/common.js | 13632 | (function () {
initMobileMenu()
initVideoModal()
if (PAGE_TYPE) {
initVersionSelect()
initApiSpecLinks()
initSubHeaders()
initLocationHashFuzzyMatching()
}
function initApiSpecLinks () {
var apiContent = document.querySelector('.content.api')
if (apiContent) {
var apiTitles = [].slice.call(apiContent.querySelectorAll('h3'))
apiTitles.forEach(function (titleNode) {
var methodMatch = titleNode.textContent.match(/^([^(]+)\(/)
if (methodMatch) {
var idWithoutArguments = slugize(methodMatch[1])
titleNode.setAttribute('id', idWithoutArguments)
titleNode.querySelector('a').setAttribute('href', '#' + idWithoutArguments)
}
var ulNode = titleNode.parentNode.nextSibling
if (ulNode.tagName !== 'UL') {
ulNode = ulNode.nextSibling
if (!ulNode) return
}
if (ulNode.tagName === 'UL') {
var specNode = document.createElement('li')
var specLink = createSourceSearchPath(titleNode.textContent)
specNode.innerHTML = '<a href="' + specLink + '" target="_blank">Source</a>'
ulNode.appendChild(specNode)
}
})
}
function createSourceSearchPath (query) {
query = query
.replace(/\([^\)]*?\)/g, '')
.replace(/(Vue\.)(\w+)/g, '$1$2" OR "$2')
.replace(/vm\./g, 'Vue.prototype.')
return 'https://github.com/search?utf8=%E2%9C%93&q=repo%3Avuejs%2Fvue+extension%3Ajs+' + encodeURIComponent('"' + query + '"') + '&type=Code'
}
}
function parseRawHash (hash) {
// Remove leading hash
if (hash.charAt(0) === '#') {
hash = hash.substr(1)
}
// Escape characters
try {
hash = decodeURIComponent(hash)
} catch (e) {}
return CSS.escape(hash)
}
function initLocationHashFuzzyMatching () {
var rawHash = window.location.hash
if (!rawHash) return
var hash = parseRawHash(rawHash)
var hashTarget = document.getElementById(hash)
if (!hashTarget) {
var normalizedHash = normalizeHash(hash)
var possibleHashes = [].slice.call(document.querySelectorAll('[id]'))
.map(function (el) { return el.id })
possibleHashes.sort(function (hashA, hashB) {
var distanceA = levenshteinDistance(normalizedHash, normalizeHash(hashA))
var distanceB = levenshteinDistance(normalizedHash, normalizeHash(hashB))
if (distanceA < distanceB) return -1
if (distanceA > distanceB) return 1
return 0
})
window.location.hash = '#' + possibleHashes[0]
}
function normalizeHash (rawHash) {
return rawHash
.toLowerCase()
.replace(/\-(?:deprecated|removed|replaced|changed|obsolete)$/, '')
}
function levenshteinDistance (a, b) {
var m = []
if (!(a && b)) return (b || a).length
for (var i = 0; i <= b.length; m[i] = [i++]) {}
for (var j = 0; j <= a.length; m[0][j] = j++) {}
for (var i = 1; i <= b.length; i++) {
for (var j = 1; j <= a.length; j++) {
m[i][j] = b.charAt(i - 1) === a.charAt(j - 1)
? m[i - 1][j - 1]
: m[i][j] = Math.min(
m[i - 1][j - 1] + 1,
Math.min(m[i][j - 1] + 1, m[i - 1][j] + 1))
}
}
return m[b.length][a.length]
}
}
/**
* Mobile burger menu button and gesture for toggling sidebar
*/
function initMobileMenu () {
var mobileBar = document.getElementById('mobile-bar')
var sidebar = document.querySelector('.sidebar')
var menuButton = mobileBar.querySelector('.menu-button')
menuButton.addEventListener('click', function () {
sidebar.classList.toggle('open')
})
document.body.addEventListener('click', function (e) {
if (e.target !== menuButton && !sidebar.contains(e.target)) {
sidebar.classList.remove('open')
}
})
// Toggle sidebar on swipe
var start = {}, end = {}
document.body.addEventListener('touchstart', function (e) {
start.x = e.changedTouches[0].clientX
start.y = e.changedTouches[0].clientY
})
document.body.addEventListener('touchend', function (e) {
end.y = e.changedTouches[0].clientY
end.x = e.changedTouches[0].clientX
var xDiff = end.x - start.x
var yDiff = end.y - start.y
if (Math.abs(xDiff) > Math.abs(yDiff)) {
if (xDiff > 0 && start.x <= 80) sidebar.classList.add('open')
else sidebar.classList.remove('open')
}
})
}
/**
* Modal Video Player
*/
function initVideoModal () {
var modalButton = document.getElementById('modal-player')
var videoModal = document.getElementById('video-modal')
if (!modalButton || !videoModal) {
return
}
var iframe = document.querySelector('iframe')
var player = new Vimeo.Player(iframe)
var overlay = document.createElement('div')
overlay.className = 'overlay'
modalButton.addEventListener('click', function(event) {
event.stopPropagation()
videoModal.classList.toggle('open')
document.body.classList.toggle('stop-scroll')
document.body.appendChild(overlay)
player.play()
})
document.body.addEventListener('click', function(e) {
if (e.target !== modalButton && !videoModal.contains(e.target)) {
videoModal.classList.remove('open')
document.body.classList.remove('stop-scroll')
document.body.removeChild(overlay)
player.unload()
}
})
}
/**
* Doc version select
*/
function initVersionSelect () {
// version select
var versionSelect = document.querySelector('.version-select')
versionSelect && versionSelect.addEventListener('change', function (e) {
var version = e.target.value
var section = window.location.pathname.match(/\/v\d\/(\w+?)\//)[1]
if (version === 'SELF') return
window.location.assign(
'https://' +
version +
(version && '.') +
'vuejs.org/' + section + '/'
)
})
}
/**
* Sub headers in sidebar
*/
function initSubHeaders () {
var each = [].forEach
var main = document.getElementById('main')
var header = document.getElementById('header')
var sidebar = document.querySelector('.sidebar')
var content = document.querySelector('.content')
// build sidebar
var currentPageAnchor = sidebar.querySelector('.sidebar-link.current')
var contentClasses = document.querySelector('.content').classList
var isAPIOrStyleGuide = (
contentClasses.contains('api') ||
contentClasses.contains('style-guide')
)
if (currentPageAnchor || isAPIOrStyleGuide) {
var allHeaders = []
var sectionContainer
if (isAPIOrStyleGuide) {
sectionContainer = document.querySelector('.menu-root')
} else {
sectionContainer = document.createElement('ul')
sectionContainer.className = 'menu-sub'
currentPageAnchor.parentNode.appendChild(sectionContainer)
}
var headers = content.querySelectorAll('h2')
if (headers.length) {
each.call(headers, function (h) {
sectionContainer.appendChild(makeLink(h))
var h3s = collectH3s(h)
allHeaders.push(h)
allHeaders.push.apply(allHeaders, h3s)
if (h3s.length) {
sectionContainer.appendChild(makeSubLinks(h3s, isAPIOrStyleGuide))
}
})
} else {
headers = content.querySelectorAll('h3')
each.call(headers, function (h) {
console.log(h)
sectionContainer.appendChild(makeLink(h))
allHeaders.push(h)
})
}
var animating = false
sectionContainer.addEventListener('click', function (e) {
// Not prevent hashchange for smooth-scroll
// e.preventDefault()
if (e.target.classList.contains('section-link')) {
sidebar.classList.remove('open')
setActive(e.target)
animating = true
setTimeout(function () {
animating = false
}, 400)
}
}, true)
// make links clickable
allHeaders.forEach(makeHeaderClickable)
smoothScroll.init({
speed: 400,
offset: 0
})
}
var hoveredOverSidebar = false
sidebar.addEventListener('mouseover', function () {
hoveredOverSidebar = true
})
sidebar.addEventListener('mouseleave', function () {
hoveredOverSidebar = false
})
// listen for scroll event to do positioning & highlights
window.addEventListener('scroll', updateSidebar)
window.addEventListener('resize', updateSidebar)
function updateSidebar () {
var doc = document.documentElement
var top = doc && doc.scrollTop || document.body.scrollTop
if (animating || !allHeaders) return
var last
for (var i = 0; i < allHeaders.length; i++) {
var link = allHeaders[i]
if (link.offsetTop > top) {
if (!last) last = link
break
} else {
last = link
}
}
if (last)
setActive(last.id, !hoveredOverSidebar)
}
function makeLink (h) {
var link = document.createElement('li')
window.arst = h
var text = [].slice.call(h.childNodes).map(function (node) {
if (node.nodeType === Node.TEXT_NODE) {
return node.nodeValue
} else if (['CODE', 'SPAN'].indexOf(node.tagName) !== -1) {
return node.textContent
} else {
return ''
}
}).join('').replace(/\(.*\)$/, '')
link.innerHTML =
'<a class="section-link" data-scroll href="#' + h.id + '">' +
htmlEscape(text) +
'</a>'
return link
}
function htmlEscape (text) {
return text
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/</g, '<')
.replace(/>/g, '>')
}
function collectH3s (h) {
var h3s = []
var next = h.nextSibling
while (next && next.tagName !== 'H2') {
if (next.tagName === 'H3') {
h3s.push(next)
}
next = next.nextSibling
}
return h3s
}
function makeSubLinks (h3s, small) {
var container = document.createElement('ul')
if (small) {
container.className = 'menu-sub'
}
h3s.forEach(function (h) {
container.appendChild(makeLink(h))
})
return container
}
function setActive (id, shouldScrollIntoView) {
var previousActive = sidebar.querySelector('.section-link.active')
var currentActive = typeof id === 'string'
? sidebar.querySelector('.section-link[href="#' + id + '"]')
: id
if (currentActive !== previousActive) {
if (previousActive) previousActive.classList.remove('active')
currentActive.classList.add('active')
if (shouldScrollIntoView) {
var currentPageOffset = currentPageAnchor
? currentPageAnchor.offsetTop - 8
: 0
var currentActiveOffset = currentActive.offsetTop + currentActive.parentNode.clientHeight
var sidebarHeight = sidebar.clientHeight
var currentActiveIsInView = (
currentActive.offsetTop >= sidebar.scrollTop &&
currentActiveOffset <= sidebar.scrollTop + sidebarHeight
)
var linkNotFurtherThanSidebarHeight = currentActiveOffset - currentPageOffset < sidebarHeight
var newScrollTop = currentActiveIsInView
? sidebar.scrollTop
: linkNotFurtherThanSidebarHeight
? currentPageOffset
: currentActiveOffset - sidebarHeight
sidebar.scrollTop = newScrollTop
}
}
}
function makeHeaderClickable (header) {
var link = header.querySelector('a')
link.setAttribute('data-scroll', '')
// transform DOM structure from
// `<h2><a></a>Header</a>` to <h2><a>Header</a></h2>`
// to make the header clickable
var nodes = Array.prototype.slice.call(header.childNodes)
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i]
if (node !== link) {
link.appendChild(node)
}
}
}
}
// Stolen from: https://github.com/hexojs/hexo-util/blob/master/lib/escape_regexp.js
function escapeRegExp(str) {
if (typeof str !== 'string') throw new TypeError('str must be a string!');
// http://stackoverflow.com/a/6969486
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
}
// Stolen from: https://github.com/hexojs/hexo-util/blob/master/lib/slugize.js
function slugize(str, options) {
if (typeof str !== 'string') throw new TypeError('str must be a string!')
options = options || {}
var rControl = /[\u0000-\u001f]/g
var rSpecial = /[\s~`!@#\$%\^&\*\(\)\-_\+=\[\]\{\}\|\\;:"'<>,\.\?\/]+/g
var separator = options.separator || '-'
var escapedSep = escapeRegExp(separator)
var result = str
// Remove control characters
.replace(rControl, '')
// Replace special characters
.replace(rSpecial, separator)
// Remove continous separators
.replace(new RegExp(escapedSep + '{2,}', 'g'), separator)
// Remove prefixing and trailing separtors
.replace(new RegExp('^' + escapedSep + '+|' + escapedSep + '+$', 'g'), '')
switch (options.transform) {
case 1:
return result.toLowerCase()
case 2:
return result.toUpperCase()
default:
return result
}
}
})()
| mit |
eginwong/555-Job-Scheduling | code/LPT_heapq.py | 8050 | import datetime
import csv
import heapq
def printDate( current_date ):
switcher = {
0: "Monday",
1: "Tuesday",
2: "Wednesday",
3: "Thursday",
4: "Friday",
}
print "++++++++++++++++++++++++++++++++++++++++++++++++ It is currently " + switcher[current_date.weekday()] + " " + str(current_date) + " ++++++++++++++++++++++++++++++++++++++++++++++++"
return None
def process_time (queue, time):
global current_date
global current_hour
finishedService = queue[0]
tNew = finishedService[0]
print "The new time is: " + str(tNew)
# take difference in t1 and t2
tdelta = tNew - time
# update actual date as well.
# while difference between t1 and t2 > 0:
while tdelta > 0:
if current_date.weekday() < 4: #Mon-Thurs
if (current_hour + tdelta) > 15*0.8: #means that it's more than one day
current_hour = 0 #reset
current_date += datetime.timedelta(days=1)
tdelta -= 15*0.8 - current_hour
printDate(current_date)
else:
current_hour += tdelta
tdelta = 0
if current_date.weekday() == 4: #Fri
if (current_hour + tdelta) > 7.5*0.8: #means that it's more than one day
current_hour = 0 #reset
current_date += datetime.timedelta(days=3) #move to Monday
tdelta -= 7.5*0.8 - current_hour
printDate(current_date)
else:
current_hour += tdelta
tdelta = 0
return tNew
dictJobs = {}
dictMachines = {}
#read in the csv.
with open('input.csv', 'rb') as f:
reader = csv.reader(f)
for i, line in enumerate(reader):
if(line[0].isdigit() and line[0] > 0):
key = int(line[0])
machine = line[3]
#Define job as array of job#, stage, release, end, lateness, actual data of stages.
if key in dictJobs:
dictJobs[key]["data"].append([line[3],line[4]])
else:
dictJobs[key] = {"stage": 1, "status": "AWAITING", "release": datetime.datetime.strptime(line[1], "%d-%b-%y"), "end": datetime.datetime.strptime(line[2], "%d-%b-%y"), "data": [[line[3], line[4]]]}
#For machines:
if machine not in dictMachines:
dictMachines[machine] = False
print("################################ STATS ################################")
print "Total number of jobs in the dictionary: " + str(len(dictJobs))
print "Total number of machines: " + str(len(dictMachines))
#qtransit: we will just use a list and store [job, machine, transitendtime]
qTransit = []
#qArrival: Stages of jobs that are released and available.
qArrival = []
#qService: Machines that are in use.
qService = []
#qLeft: to signify jobs that have been completed.
qLeft = []
# t is most important counter, date is only to indicate ending date + release date
t = 0
# Makes sense to start with the first job's release date. Hard code to 1 as there is no job #0.
current_date = dictJobs[1]['release']
current_hour = 0
# no "do-while" loop in python, using similar construct. http://stackoverflow.com/questions/1662161/is-there-a-do-until-in-python
while True:
###### Check what's in transit
while len(qTransit) > 0 :
# if job.time > t : push onto regular queue
if t >= qTransit[0][0]:
job = heapq.heappop(qTransit)
dictJobs[job[1]]["status"] = "AWAITING"
else:
break
# Check date and add available jobs to queue - What's released by date
for job in dictJobs:
if dictJobs[job]["release"] <= current_date:
if dictJobs[job]["status"] == "AWAITING":
#add to queue
refer = dictJobs[job]["data"][dictJobs[job]["stage"] - 1]
# Add negation for LPT
heapq.heappush(qArrival, (-1*float(refer[1]), refer[0], job))
dictJobs[job]["status"] = "ARRIVING"
else: break # as the q is sorted, we know nothing afterwards is released.
# Refresh machines (Complete any jobs that are there)
# create an empty array for free machines (dictMachines)
for machine in qService:
# peek to see earliest time. If t > current_time, pop and do something.
if t >= qService[0][0]:
temp = heapq.heappop(qService)
# release the machine.
dictMachines[temp[1]] = False;
# If the job has further stages
if dictJobs[temp[2]]["stage"] < len(dictJobs[temp[2]]["data"]):
dictJobs[temp[2]]["stage"] += 1
# toss into transit queue with time it's finished
heapq.heappush(qTransit, (t + 6, temp[2]))
dictJobs[temp[2]]["status"] = "TRANSITIONING"
# else: calculate lateness (job is finished)
else:
qLeft.append(temp[2])
dictJobs[temp[2]]["status"] = "COMPLETED"
# Assume that lateness is by days and not by hours, rounded up.
# Do not need to factor in i because we don't care about the hour of the day
difference = (current_date - dictJobs[temp[2]]["end"]).days
if difference > 0:
dictJobs[temp[2]]["lateness"] = difference
else:
dictJobs[temp[2]]["lateness"] = 0
# If earliest time is still in future, break.
else:
break
print "############################ BEFORE JOB ASSIGNMENT ############################"
print "qArrival contains: " + str(qArrival)
print "qService contains: " + str(qService)
print "qTransit contains: " + str(qTransit)
print "qLeft contains: " + str(qLeft)
# for each job in qArrival, check if machine is free from dictMachines. If yes, assign job to machine queue. PRIORITY QUEUE FOR MACHINE QUEUE.
qHolding = [] # Temporary queue to hold popped off jobs.
while len(qArrival) > 0:
tempJob = heapq.heappop(qArrival)
print "Currently looking at assigning: " + str(tempJob)
# if machine is empty for that job
if not dictMachines[tempJob[1]]:
print "ASSIGNED: " + str(tempJob[2])
# add to priority queue (job, + t=expected)
heapq.heappush(qService, (t + -1*tempJob[0], tempJob[1], tempJob[2]))
dictJobs[tempJob[2]]["status"] = "SERVING"
# Set machine index to true.
dictMachines[tempJob[1]] = True
else:
heapq.heappush(qHolding, tempJob)
# When the process has finished, replace arrival with holding to restore any previously popped values.
qArrival = qHolding
print "############################ AFTER JOB ASSIGNMENT ############################"
print "qArrival is: ",
print qArrival
print "qService is: ",
print qService
# update time to next event (machine is free). Pop from the machine priority queue and take the new t.
#~~~~~~~~If there is no service left, advance the time to the next arrival. Generally won't happen.
if len(qService) > 0: t = process_time(qService, t)
elif len(qTransit) > 0: t = process_time(qTransit, t)
# While jobs are in queue or in transit
if len(qArrival) == 0 and len (qTransit) == 0 and len (qService) == 0 and len(qLeft) == len(dictJobs):
print "loop complete"
break
################################ RESULTS ################################
max_lateness = 0
percentage_late = 0
for job in dictJobs:
temp = dictJobs[job]["lateness"]
if temp > max_lateness:
max_lateness = temp
if temp > 1:
percentage_late += 1
print percentage_late
percentage_late = round(float(percentage_late) / len(dictJobs) * 100, 2)
# print "################################ RESULTS ################################"
print "The max lateness is: " + str(max_lateness) + "."
print "The percentage late is: " + str(percentage_late) + "%."
| mit |
michelleduer/archives | php5-3/Chapter-7-Functions/return_statement.php | 564 | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Normal and Bold Text</title>
<link rel="stylesheet" type="text/css" href="common.css" />
</head>
<body>
<h1>Normal and Bold Text</h1>
<?php
function makeBold($text) {
return "<b>$text</b>";
}
$normalText = "This is a normal text.";
$boldText = makeBold("This is a bold text.");
echo "<p>$normalText</p>";
echo "<p>$boldText</p>";
?>
</body>
</html>
| mit |
mdelpozobanos/mixpy | mixpy/__init__.py | 177 | """
===============================
mixpy
===============================
"""
__author__ = 'Marcos DelPozo-Banos'
__email__ = 'mdelpozobanos@gmail.com'
__version__ = '0.0.0' | mit |
elado/isotope | examples/rails3-example/config/environments/development.rb | 993 | Rails3Example::Application.configure do
# Settings specified here will take precedence over those in config/environment.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the webserver when you make code changes.
config.cache_classes = false
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_view.debug_rjs = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger
config.active_support.deprecation = :log
# Only use best-standards-support built into browsers
config.action_dispatch.best_standards_support = :builtin
end
| mit |
maxpert/raspchat | src/chat-handler.js | 2554 | const Inflector = require('inflected');
const bluebird = require('bluebird');
const Figlet = bluebird.promisifyAll(require('figlet'));
const ChatUser = require('./chat-user');
const ChatRoom = require('./chat-room');
const JSONMessage = require('./json-message');
const CommandHandlers = require('./command-handlers');
const NickRegistery = require('./nick-registery');
const {genId} = require('./utils');
const DefaultConfig = {
commandRoom: 'SERVER'
};
const Rooms = new Map();
const Users = new Map();
function GetRoom(maybeName) {
const name = maybeName || DefaultConfig.commandRoom;
const chatRoom = Rooms.has(name) ? Rooms.get(name) : new ChatRoom(name, name !== DefaultConfig.commandRoom);
Rooms.set(name, chatRoom);
return chatRoom;
}
function UserDisconnected(id) {
if (Users.has(id)) {
const user = Users.get(id);
user.events.removeAllListeners('message');
user.events.removeAllListeners('close');
NickRegistery.delete(id);
Users.delete(id);
}
}
function UserMessage(message, user) {
const command = message.parsed['@'].replace('-', '_');
const methodName = Inflector.camelize(command, false);
const commandMethod = CommandHandlers[methodName];
if (!commandMethod) {
console.error('Invalid command', command, methodName);
return;
}
commandMethod(user, GetRoom, message.parsed).catch(console.error);
}
async function SendWelcome(user) {
const serverRoom = GetRoom();
const normalized_nick = user.nick.replace(/[^\d\w]/, ' ');
const message = '```\n'+ await Figlet.textAsync('Hi ' + normalized_nick, {
font: 'The Edge'
}) + '\n```';
user.send(JSONMessage.fromObject({
'@': serverRoom.roomName,
'!id': genId(),
'utc_timestamp': new Date().getTime(),
'msg': message
}));
}
module.exports = function () {
return function (req, res) {
if (!res.websocket) {
res.status(500).send('Not a websocket connection');
return;
}
let id = genId({short: true});
while (Users.has(id)) {
id = genId({short: true});
}
res.websocket(function (ws) {
const user = new ChatUser(id, ws, NickRegistery.create(id));
SendWelcome(user);
user.events.once('close', UserDisconnected);
user.events.on('message', UserMessage);
// Make user join SERVER
user.join(GetRoom());
Users.set(id, user);
});
};
};
| mit |
pricingassistant/mongokat | docs/conf.py | 9805 | # -*- coding: utf-8 -*-
#
# MongoKat documentation build configuration file, created by
# sphinx-quickstart on Thu Apr 30 14:21:09 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
import shlex
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.autosummary',
'sphinx.ext.coverage',
'sphinx.ext.viewcode',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = 'MongoKat'
copyright = '2015, Pricing Assistant'
author = 'Pricing Assistant'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.1'
# The full version, including alpha/beta/rc tags.
release = '0.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
# on_rtd is whether we are on readthedocs.org, this line of code grabbed from docs.readthedocs.org
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
if not on_rtd: # only import and set the theme if we're building docs locally
import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
import mongokat
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr'
#html_search_language = 'en'
# A dictionary with options for the search language support, empty by default.
# Now only 'ja' uses this config value
#html_search_options = {'type': 'default'}
# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#html_search_scorer = 'scorer.js'
# Output file base name for HTML help builder.
htmlhelp_basename = 'MongoKatdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
# Latex figure (float) alignment
#'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'MongoKat.tex', 'MongoKat Documentation',
'Pricing Assistant', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'mongokat', 'MongoKat Documentation',
[author], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'MongoKat', 'MongoKat Documentation',
author, 'MongoKat', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
# http://sphinx-doc.org/ext/autodoc.html#module-sphinx.ext.autodoc
autodoc_member_order = "bysource"
| mit |
Promact/trappist | Trappist/src/Promact.Trappist.Web/Migrations/20170725061921_AddedPropertyToTestAttendee.Designer.cs | 27413 | using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Promact.Trappist.DomainModel.DbContext;
using Promact.Trappist.DomainModel.Enum;
namespace Promact.Trappist.Web.Migrations
{
[DbContext(typeof(TrappistDbContext))]
[Migration("20170725061921_AddedPropertyToTestAttendee")]
partial class AddedPropertyToTestAttendee
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.1.1")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasMaxLength(256);
b.Property<string>("NormalizedName")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasName("RoleNameIndex");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("LoginProvider");
b.Property<string>("Name");
b.Property<string>("Value");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("Promact.Trappist.DomainModel.Models.Category.Category", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("CategoryName")
.IsRequired()
.HasMaxLength(150);
b.Property<DateTime>("CreatedDateTime");
b.Property<DateTime?>("UpdateDateTime");
b.HasKey("Id");
b.ToTable("Category");
});
modelBuilder.Entity("Promact.Trappist.DomainModel.Models.Question.CodeSnippetQuestion", b =>
{
b.Property<int>("Id");
b.Property<bool>("CheckCodeComplexity");
b.Property<bool>("CheckTimeComplexity");
b.Property<DateTime>("CreatedDateTime");
b.Property<bool>("RunBasicTestCase");
b.Property<bool>("RunCornerTestCase");
b.Property<bool>("RunNecessaryTestCase");
b.Property<DateTime?>("UpdateDateTime");
b.HasKey("Id");
b.ToTable("CodeSnippetQuestion");
});
modelBuilder.Entity("Promact.Trappist.DomainModel.Models.Question.CodeSnippetQuestionTestCases", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("CodeSnippetQuestionId");
b.Property<DateTime>("CreatedDateTime");
b.Property<string>("TestCaseDescription");
b.Property<string>("TestCaseInput")
.IsRequired();
b.Property<double>("TestCaseMarks");
b.Property<string>("TestCaseOutput")
.IsRequired();
b.Property<string>("TestCaseTitle")
.IsRequired();
b.Property<int>("TestCaseType");
b.Property<DateTime?>("UpdateDateTime");
b.HasKey("Id");
b.HasIndex("CodeSnippetQuestionId");
b.ToTable("CodeSnippetQuestionTestCases");
});
modelBuilder.Entity("Promact.Trappist.DomainModel.Models.Question.CodingLanguage", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreatedDateTime");
b.Property<string>("Language")
.IsRequired();
b.Property<DateTime?>("UpdateDateTime");
b.HasKey("Id");
b.ToTable("CodingLanguage");
});
modelBuilder.Entity("Promact.Trappist.DomainModel.Models.Question.Question", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("CategoryID");
b.Property<string>("CreatedByUserId");
b.Property<DateTime>("CreatedDateTime");
b.Property<int>("DifficultyLevel");
b.Property<string>("QuestionDetail")
.IsRequired();
b.Property<int>("QuestionType");
b.Property<DateTime?>("UpdateDateTime");
b.Property<string>("UpdatedByUserId");
b.HasKey("Id");
b.HasIndex("CategoryID");
b.HasIndex("CreatedByUserId");
b.HasIndex("UpdatedByUserId");
b.ToTable("Question");
});
modelBuilder.Entity("Promact.Trappist.DomainModel.Models.Question.QuestionLanguageMapping", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreatedDateTime");
b.Property<int>("LanguageId");
b.Property<int>("QuestionId");
b.Property<DateTime?>("UpdateDateTime");
b.HasKey("Id");
b.HasIndex("LanguageId");
b.HasIndex("QuestionId");
b.ToTable("QuestionLanguageMapping");
});
modelBuilder.Entity("Promact.Trappist.DomainModel.Models.Question.SingleMultipleAnswerQuestion", b =>
{
b.Property<int>("Id");
b.Property<DateTime>("CreatedDateTime");
b.Property<DateTime?>("UpdateDateTime");
b.HasKey("Id");
b.ToTable("SingleMultipleAnswerQuestion");
});
modelBuilder.Entity("Promact.Trappist.DomainModel.Models.Question.SingleMultipleAnswerQuestionOption", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreatedDateTime");
b.Property<bool>("IsAnswer");
b.Property<string>("Option")
.IsRequired();
b.Property<int>("SingleMultipleAnswerQuestionID");
b.Property<DateTime?>("UpdateDateTime");
b.HasKey("Id");
b.HasIndex("SingleMultipleAnswerQuestionID");
b.ToTable("SingleMultipleAnswerQuestionOption");
});
modelBuilder.Entity("Promact.Trappist.DomainModel.Models.Report.Report", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreatedDateTime");
b.Property<double>("Percentage");
b.Property<double>("Percentile");
b.Property<int>("TestAttendeeId");
b.Property<int>("TestStatus");
b.Property<int>("TimeTakenByAttendee");
b.Property<double>("TotalMarksScored");
b.Property<DateTime?>("UpdateDateTime");
b.HasKey("Id");
b.HasIndex("TestAttendeeId")
.IsUnique();
b.ToTable("Report");
});
modelBuilder.Entity("Promact.Trappist.DomainModel.Models.Test.Test", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("AllowTestResume");
b.Property<int>("BrowserTolerance");
b.Property<decimal>("CorrectMarks");
b.Property<string>("CreatedByUserId");
b.Property<DateTime>("CreatedDateTime");
b.Property<int>("Duration");
b.Property<DateTime>("EndDate");
b.Property<string>("FromIpAddress");
b.Property<decimal>("IncorrectMarks");
b.Property<bool>("IsLaunched");
b.Property<bool>("IsPaused");
b.Property<string>("Link");
b.Property<int>("OptionOrder");
b.Property<int>("QuestionOrder");
b.Property<DateTime>("StartDate");
b.Property<string>("TestName")
.IsRequired()
.HasMaxLength(150);
b.Property<string>("ToIpAddress");
b.Property<DateTime?>("UpdateDateTime");
b.Property<string>("WarningMessage");
b.Property<int?>("WarningTime");
b.HasKey("Id");
b.HasIndex("CreatedByUserId");
b.ToTable("Test");
});
modelBuilder.Entity("Promact.Trappist.DomainModel.Models.Test.TestCategory", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("CategoryId");
b.Property<int>("TestId");
b.HasKey("Id");
b.HasIndex("CategoryId");
b.HasIndex("TestId");
b.ToTable("TestCategory");
});
modelBuilder.Entity("Promact.Trappist.DomainModel.Models.Test.TestQuestion", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("QuestionId");
b.Property<int>("TestId");
b.HasKey("Id");
b.HasIndex("QuestionId");
b.HasIndex("TestId");
b.ToTable("TestQuestion");
});
modelBuilder.Entity("Promact.Trappist.DomainModel.Models.TestConduct.AttendeeAnswers", b =>
{
b.Property<int>("Id");
b.Property<string>("Answers");
b.Property<DateTime>("CreatedDateTime");
b.Property<double>("TimeElapsed");
b.Property<DateTime?>("UpdateDateTime");
b.HasKey("Id");
b.ToTable("AttendeeAnswers");
});
modelBuilder.Entity("Promact.Trappist.DomainModel.Models.TestConduct.TestAnswers", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("AnsweredCodeSnippet");
b.Property<int?>("AnsweredOption");
b.Property<DateTime>("CreatedDateTime");
b.Property<int>("TestConductId");
b.Property<DateTime?>("UpdateDateTime");
b.HasKey("Id");
b.HasIndex("TestConductId");
b.ToTable("TestAnswers");
});
modelBuilder.Entity("Promact.Trappist.DomainModel.Models.TestConduct.TestAttendees", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<bool>("CheckedCandidate");
b.Property<string>("ContactNumber")
.HasMaxLength(15);
b.Property<DateTime>("CreatedDateTime");
b.Property<string>("Email")
.IsRequired()
.HasMaxLength(255);
b.Property<string>("FirstName")
.IsRequired()
.HasMaxLength(255);
b.Property<string>("LastName")
.IsRequired()
.HasMaxLength(255);
b.Property<string>("RollNumber")
.IsRequired();
b.Property<bool>("StarredCandidate");
b.Property<int>("TestId");
b.Property<DateTime?>("UpdateDateTime");
b.HasKey("Id");
b.HasIndex("TestId");
b.ToTable("TestAttendees");
});
modelBuilder.Entity("Promact.Trappist.DomainModel.Models.TestConduct.TestConduct", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreatedDateTime");
b.Property<int>("QuestionId");
b.Property<int>("QuestionStatus");
b.Property<int>("TestAttendeeId");
b.Property<DateTime?>("UpdateDateTime");
b.HasKey("Id");
b.HasIndex("QuestionId");
b.HasIndex("TestAttendeeId");
b.ToTable("TestConduct");
});
modelBuilder.Entity("Promact.Trappist.Web.Models.ApplicationUser", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<DateTime>("CreatedDateTime");
b.Property<string>("Email")
.HasMaxLength(256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(150);
b.Property<string>("NormalizedEmail")
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.HasMaxLength(256);
b.Property<string>("OrganizationName")
.HasMaxLength(150);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<DateTime?>("UpdatedDateTime");
b.Property<string>("UserName")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
.WithMany("Claims")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
{
b.HasOne("Promact.Trappist.Web.Models.ApplicationUser")
.WithMany("Claims")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
{
b.HasOne("Promact.Trappist.Web.Models.ApplicationUser")
.WithMany("Logins")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
.WithMany("Users")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Promact.Trappist.Web.Models.ApplicationUser")
.WithMany("Roles")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Promact.Trappist.DomainModel.Models.Question.CodeSnippetQuestion", b =>
{
b.HasOne("Promact.Trappist.DomainModel.Models.Question.Question", "Question")
.WithOne("CodeSnippetQuestion")
.HasForeignKey("Promact.Trappist.DomainModel.Models.Question.CodeSnippetQuestion", "Id")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Promact.Trappist.DomainModel.Models.Question.CodeSnippetQuestionTestCases", b =>
{
b.HasOne("Promact.Trappist.DomainModel.Models.Question.CodeSnippetQuestion", "CodeSnippetQuestion")
.WithMany("CodeSnippetQuestionTestCases")
.HasForeignKey("CodeSnippetQuestionId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Promact.Trappist.DomainModel.Models.Question.Question", b =>
{
b.HasOne("Promact.Trappist.DomainModel.Models.Category.Category", "Category")
.WithMany("Question")
.HasForeignKey("CategoryID")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Promact.Trappist.Web.Models.ApplicationUser", "CreatedByUser")
.WithMany()
.HasForeignKey("CreatedByUserId");
b.HasOne("Promact.Trappist.Web.Models.ApplicationUser", "UpdatedByUser")
.WithMany()
.HasForeignKey("UpdatedByUserId");
});
modelBuilder.Entity("Promact.Trappist.DomainModel.Models.Question.QuestionLanguageMapping", b =>
{
b.HasOne("Promact.Trappist.DomainModel.Models.Question.CodingLanguage", "CodeLanguage")
.WithMany("QuestionLanguangeMapping")
.HasForeignKey("LanguageId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Promact.Trappist.DomainModel.Models.Question.CodeSnippetQuestion", "CodeSnippetQuestion")
.WithMany("QuestionLanguangeMapping")
.HasForeignKey("QuestionId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Promact.Trappist.DomainModel.Models.Question.SingleMultipleAnswerQuestion", b =>
{
b.HasOne("Promact.Trappist.DomainModel.Models.Question.Question", "Question")
.WithOne("SingleMultipleAnswerQuestion")
.HasForeignKey("Promact.Trappist.DomainModel.Models.Question.SingleMultipleAnswerQuestion", "Id")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Promact.Trappist.DomainModel.Models.Question.SingleMultipleAnswerQuestionOption", b =>
{
b.HasOne("Promact.Trappist.DomainModel.Models.Question.SingleMultipleAnswerQuestion", "SingleMultipleAnswerQuestion")
.WithMany("SingleMultipleAnswerQuestionOption")
.HasForeignKey("SingleMultipleAnswerQuestionID")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Promact.Trappist.DomainModel.Models.Report.Report", b =>
{
b.HasOne("Promact.Trappist.DomainModel.Models.TestConduct.TestAttendees", "TestAttendee")
.WithOne("Report")
.HasForeignKey("Promact.Trappist.DomainModel.Models.Report.Report", "TestAttendeeId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Promact.Trappist.DomainModel.Models.Test.Test", b =>
{
b.HasOne("Promact.Trappist.Web.Models.ApplicationUser", "CreatedByUser")
.WithMany()
.HasForeignKey("CreatedByUserId");
});
modelBuilder.Entity("Promact.Trappist.DomainModel.Models.Test.TestCategory", b =>
{
b.HasOne("Promact.Trappist.DomainModel.Models.Category.Category", "Category")
.WithMany()
.HasForeignKey("CategoryId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Promact.Trappist.DomainModel.Models.Test.Test", "Test")
.WithMany("TestCategory")
.HasForeignKey("TestId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Promact.Trappist.DomainModel.Models.Test.TestQuestion", b =>
{
b.HasOne("Promact.Trappist.DomainModel.Models.Question.Question", "Question")
.WithMany()
.HasForeignKey("QuestionId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Promact.Trappist.DomainModel.Models.Test.Test", "Test")
.WithMany("TestQuestion")
.HasForeignKey("TestId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Promact.Trappist.DomainModel.Models.TestConduct.AttendeeAnswers", b =>
{
b.HasOne("Promact.Trappist.DomainModel.Models.TestConduct.TestAttendees", "TestAttendees")
.WithOne("AttendeeAnswers")
.HasForeignKey("Promact.Trappist.DomainModel.Models.TestConduct.AttendeeAnswers", "Id")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Promact.Trappist.DomainModel.Models.TestConduct.TestAnswers", b =>
{
b.HasOne("Promact.Trappist.DomainModel.Models.TestConduct.TestConduct", "TestConduct")
.WithMany("TestAnswers")
.HasForeignKey("TestConductId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Promact.Trappist.DomainModel.Models.TestConduct.TestAttendees", b =>
{
b.HasOne("Promact.Trappist.DomainModel.Models.Test.Test", "Test")
.WithMany("TestAttendees")
.HasForeignKey("TestId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Promact.Trappist.DomainModel.Models.TestConduct.TestConduct", b =>
{
b.HasOne("Promact.Trappist.DomainModel.Models.Question.Question", "Question")
.WithMany()
.HasForeignKey("QuestionId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Promact.Trappist.DomainModel.Models.TestConduct.TestAttendees", "TestAttendees")
.WithMany("TestConduct")
.HasForeignKey("TestAttendeeId")
.OnDelete(DeleteBehavior.Cascade);
});
}
}
}
| mit |
tychio/when | js/main.js | 751 | requirejs.config({
baseUrl: 'js',
paths: {
jquery: '../lib/jquery/dist/jquery.min',
audiojs: '../lib/audiojs/audiojs/audio'
}
});
requirejs(['jquery', 'update', 'timer', 'tabata', 'mod/wind', 'audiojs'], function ($, Update, Timer, Tabata, Wind) {
var tabataMod = false;
var timer = Timer();
timer.start();
var tabata = Tabata({
onEnd: toTimerMod
}).init();
Wind(function (angle) {
tabataMod ? toTimerMod() : toTabataMod();
});
function toTimerMod () {
tabataMod = false;
tabata.hide().stop();
timer.counter.show();
}
function toTabataMod () {
tabataMod = true;
tabata.show().start();
timer.counter.hide();
}
});
| mit |
HerrB92/obp | OpenBeaconPackage/libraries/hibernate-release-4.2.7.SP1/project/hibernate-core/src/main/java/org/hibernate/cfg/beanvalidation/ValidationMode.java | 2927 | /*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2013, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.cfg.beanvalidation;
import java.util.HashSet;
import java.util.Set;
import org.hibernate.HibernateException;
/**
* Duplicates the javax.validation enum (because javax validation might not be on the runtime classpath)
*
* @author Steve Ebersole
*/
public enum ValidationMode {
AUTO( "auto" ),
CALLBACK( "callback" ),
NONE( "none" ),
DDL( "ddl" );
private final String externalForm;
private ValidationMode(String externalForm) {
this.externalForm = externalForm;
}
public static Set<ValidationMode> getModes(Object modeProperty) {
Set<ValidationMode> modes = new HashSet<ValidationMode>(3);
if (modeProperty == null) {
modes.add( ValidationMode.AUTO );
}
else {
final String[] modesInString = modeProperty.toString().split( "," );
for ( String modeInString : modesInString ) {
modes.add( getMode(modeInString) );
}
}
if ( modes.size() > 1 && ( modes.contains( ValidationMode.AUTO ) || modes.contains( ValidationMode.NONE ) ) ) {
throw new HibernateException( "Incompatible validation modes mixed: " + loggable( modes ) );
}
return modes;
}
private static ValidationMode getMode(String modeProperty) {
if (modeProperty == null || modeProperty.length() == 0) {
return AUTO;
}
else {
try {
return valueOf( modeProperty.trim().toUpperCase() );
}
catch ( IllegalArgumentException e ) {
throw new HibernateException( "Unknown validation mode in " + BeanValidationIntegrator.MODE_PROPERTY + ": " + modeProperty );
}
}
}
public static String loggable(Set<ValidationMode> modes) {
if ( modes == null || modes.isEmpty() ) {
return "[<empty>]";
}
StringBuilder buffer = new StringBuilder( "[" );
String sep = "";
for ( ValidationMode mode : modes ) {
buffer.append( sep ).append( mode.externalForm );
sep = ", ";
}
return buffer.append( "]" ).toString();
}
}
| mit |
sonkul9x/tintuc | application/modules/admin_products/views/products_add.php | 7892 | <?php $this->load->view('head-product'); ?>
<div class="line"></div>
<!-- Message -->
<!-- Main content wrapper -->
<div class="wrapper"> <!-- Form -->
<form class="form" id="form" action="<?php echo admin_url('san-pham/add'); ?>" method="post" enctype="multipart/form-data">
<fieldset>
<div class="widget">
<div class="title">
<img src="<?php echo public_url('admin'); ?>/images/icons/dark/add.png" class="titleIcon" />
<h6>Thêm mới Sản phẩm</h6>
</div>
<ul class="tabs">
<li><a href="#tab1">Thông tin chung</a></li>
<li><a href="#tab2">SEO Onpage</a></li>
<li><a href="#tab3">Bài viết</a></li>
</ul>
<div class="tab_container">
<div id='tab1' class="tab_content pd0">
<div class="formRow">
<label class="formLeft" for="param_name">Tên:<span class="req">*</span></label>
<div class="formRight">
<span class="oneTwo"><input name="name" id="param_name" _autocheck="true" type="text" /></span>
<span name="name_autocheck" class="autocheck"></span>
<div name="name_error" class="clear error"><?php echo form_error('name'); ?></div>
</div>
<div class="clear"></div>
</div>
<div class="formRow">
<label class="formLeft">Hình ảnh:<span class="req">*</span></label>
<div class="formRight">
<div class="left"><input type="file" id="image" name="image" ></div>
<div name="image_error" class="clear error"><?php echo form_error('image'); ?></div>
</div>
<div class="clear"></div>
</div>
<div class="formRow">
<label class="formLeft">Ảnh kèm theo:</label>
<div class="formRight">
<div class="left"><input type="file" id="image_list" name="image_list[]" multiple></div>
<div name="image_list_error" class="clear error"><?php echo form_error('image_list'); ?></div>
</div>
<div class="clear"></div>
</div>
<!-- Price -->
<div class="formRow">
<label class="formLeft" for="param_price">
Giá :
<span class="req">*</span>
</label>
<div class="formRight">
<span class="oneTwo">
<input name="price" style='width:100px' id="param_price" class="format_number" _autocheck="true" type="text" />
<img class='tipS' title='Giá bán sử dụng để giao dịch' style='margin-bottom:-8px' src='<?php echo public_url('admin'); ?>/crown/images/icons/notifications/information.png'/>
</span>
<span name="price_autocheck" class="autocheck"></span>
<div name="price_error" class="clear error"><?php echo form_error('price'); ?></div>
</div>
<div class="clear"></div>
</div>
<!-- Price -->
<div class="formRow">
<label class="formLeft" for="param_discount">
Giảm giá (%)
<span></span>:
</label>
<div class="formRight">
<span>
<input name="discount" style='width:100px' id="param_discount" class="format_number" type="text" />
<img class='tipS' title='phần trăm giảm giá' style='margin-bottom:-8px' src='<?php echo public_url('admin'); ?>/crown/images/icons/notifications/information.png'/>
</span>
<span name="discount_autocheck" class="autocheck"></span>
<div name="discount_error" class="clear error"><?php echo form_error('discount'); ?></div>
</div>
<div class="clear"></div>
</div>
<div class="formRow">
<label class="formLeft" for="param_cat">Thể loại:<span class="req">*</span></label>
<div class="formRight">
<?php if (isset($catalogs) && !empty($catalogs)) { ?>
<select name="catalog" _autocheck="true" id='param_cat' class="left">
<option value="">Chọn danh mục</option>
<?php foreach ($catalogs as $vcatalog) {
if (count($vcatalog->subs) > 1) { ?>
<optgroup label="<?php echo $vcatalog->name; ?>">
<?php foreach ($vcatalog->subs as $value) { ?>
<option value="<?php echo $value->id; ?>" ><?php echo $value->name; ?> </option>
<?php }; ?>
</optgroup>
<?php }else{ ?>
<option value="<?php echo $vcatalog->id; ?>" ><?php echo $vcatalog->name; ?></option>
<?php } ?>
<?php } ?>
</select>
<?php } ?>
<span name="cat_autocheck" class="autocheck"></span>
<div name="cat_error" class="clear error"><?php echo form_error('catalog'); ?></div>
</div>
<div class="clear"></div>
</div>
<div class="formRow">
<label class="formLeft" for="param_video">
Video giới thiệu :
</label>
<div class="formRight">
<span class="oneFour"><input name="video" id="param_video" type="text" /></span>
<span name="video_autocheck" class="autocheck"></span>
<div name="video_error" class="clear error"><?php echo form_error('video'); ?></div>
</div>
<div class="clear"></div>
</div>
<!-- warranty -->
<div class="formRow">
<label class="formLeft" for="param_warranty">
Bảo hành :
</label>
<div class="formRight">
<span class="oneFour"><input name="warranty" id="param_warranty" type="text" /></span>
<span name="warranty_autocheck" class="autocheck"></span>
<div name="warranty_error" class="clear error"><?php echo form_error('warranty'); ?></div>
</div>
<div class="clear"></div>
</div>
<div class="formRow">
<label class="formLeft" for="param_sale">Tặng quà:</label>
<div class="formRight">
<span class="oneTwo"><textarea name="gifts" id="param_gifts" rows="4" cols=""></textarea></span>
<span name="gifts_autocheck" class="autocheck"></span>
<div name="gifts_error" class="clear error"><?php echo form_error('gifts'); ?></div>
</div>
<div class="clear"></div>
</div> <div class="formRow hide"></div>
</div>
<div id='tab2' class="tab_content pd0" >
<div class="formRow">
<label class="formLeft" for="param_site_title">Title:</label>
<div class="formRight">
<span class="oneTwo"><textarea name="site_title" id="param_site_title" _autocheck="true" rows="4" cols=""></textarea></span>
<span name="site_title_autocheck" class="autocheck"></span>
<div name="site_title_error" class="clear error"><?php echo form_error('site_title'); ?></div>
</div>
<div class="clear"></div>
</div>
<div class="formRow">
<label class="formLeft" for="param_meta_desc">Meta description:</label>
<div class="formRight">
<span class="oneTwo"><textarea name="meta_desc" id="param_meta_desc" _autocheck="true" rows="4" cols=""></textarea></span>
<span name="meta_desc_autocheck" class="autocheck"></span>
<div name="meta_desc_error" class="clear error"><?php echo form_error('meta_desc'); ?></div>
</div>
<div class="clear"></div>
</div>
<div class="formRow">
<label class="formLeft" for="param_meta_key">Meta keywords:</label>
<div class="formRight">
<span class="oneTwo"><textarea name="meta_key" id="param_meta_key" _autocheck="true" rows="4" cols=""></textarea></span>
<span name="meta_key_autocheck" class="autocheck"></span>
<div name="meta_key_error" class="clear error"><?php echo form_error('meta_key'); ?></div>
</div>
<div class="clear"></div>
</div>
<div class="formRow hide"></div>
</div>
<div id='tab3' class="tab_content pd0">
<div class="formRow">
<label class="formLeft">Nội dung:</label>
<div class="formRight">
<textarea name="content" id="param_content" class="editor"></textarea>
<div name="content_error" class="clear error"><?php echo form_error('content'); ?></div>
</div>
<div class="clear"></div>
</div>
<div class="formRow hide"></div>
</div>
</div><!-- End tab_container-->
<div class="formSubmit">
<input type="submit" value="Thêm mới" class="redB" />
<input type="reset" value="Làm lại" class="basic" />
</div>
<div class="clear"></div>
</div>
</fieldset>
</form>
</div>
<div class="clear mt30"></div> | mit |
bradlys/checkin | backend/checkin.php | 14139 | <?php
require_once 'settings.php';
require_once 'customer.php';
require_once 'organization.php';
/**
* Below are functions related to checking in and checking out customers.
* Typically, one of these two functions is called through an AJAX request,
* and it is to check in a brand new customer, check in an existing customer,
* edit an existing check in, or to check out a customer.
*
* If a new customer is being checked in then we have to create the customer in
* the customer table as well as create an entry in the checkins table for them.
*
* If an existing customer is being checked in then we need to update their
* information in the customers table appropriately (along with any possible
* information that goes in the customerattributes table) and check them in.
*
* If an existing customer is simply updating their customer information or
* check in information (their name, payment amount, number of free entrances,
* etc.) then we need to find their checkin entry and update it. Perform
* the same for their customer entry.
*
* If an existing customer who is checked in needs to be checked out then
* we need to update their customer information and turn off the checkin entry.
*
* Events have many checkins and customers have many checkins. In other words,
* events are one to many checkins and customers are one to many checkins.
*
* checkins are stored in the events table with this schema
* Field | Type | Null | Key | Default | Extra
* id | int(11) | NO | PRI | NULL | auto_increment
* customer_id | int(11) | NO | MUL | NULL |
* event_id | int(11) | NO | MUL | NULL |
* payment | int(11) | NO | | NULL |
* status | tinyint(1) | NO | | 1 |
* timestamp | timestamp | NO | | CURRENT_TIMESTAMP |
*/
/**
* Creates an entry in the checkin table
*
* @param int $cid customer ID
* @param int $eventID event ID
* @param int $payment payment
* @param boolean $useFreeEntrance
* @return int checkinID
* @throws Exception if $cid is not a positive integer
* @throws Exception if $eventID is not a positive integer
* @throws Exception if $payment is not a non-negative integer
* @throws Exception if $cid, $eventID checkin combination already exists
*/
function createCheckin($cid, $eventID, $payment){
if(empty($cid) || !isInteger($cid) || $cid < 1){
throw new Exception("cid must be a positive integer");
}
if(empty($eventID) || !isInteger($eventID) || $eventID < 1){
throw new Exception("eventID must be a positive integer");
}
if(!isInteger($payment) || $payment < 0){
throw new Exception("payment must be a non-negative integer");
}
$countExistingCheckinsSQL = "
SELECT COUNT(*) as count
FROM checkins
WHERE checkins.event_id = '$eventID'
AND checkins.customer_id '$cid'
AND checkins.status = '1'";
$countExistingCheckinsQuery = mysql_query($countExistingCheckinsSQL) or die(mysql_error());
$count = mysql_fetch_array($countExistingCheckinsQuery);
$count = $count['count'];
if($count > 0){
throw new Exception("checkin already exists for current customer");
} else {
$insertNewCheckinSQL = "INSERT INTO checkins VALUES('', '$cid', '$eventID', '$payment', '1', CURRENT_TIMESTAMP)";
mysql_query($insertNewCheckinSQL) or die(mysql_error());
return mysql_insert_id();
}
}
/**
* Reads a checkin
* @param int $checkinID checkin ID
* @return array
* @throws Exception if $checkinID is not a positive integer
* @throws Exception if $checkinID checkin doesn't exists
*/
function readCheckin($checkinID){
if(!isInteger($checkinID) || $checkinID < 1){
throw new Exception("checkinID must be a positive integer");
}
$selectExistingCheckinSQL = "
SELECT *
FROM checkins
WHERE checkins.id = '$checkinID'";
$selectExistingCheckinQuery = mysql_query($selectExistingCheckinSQL) or die(mysql_error());
$existingCheckin = mysql_fetch_array($selectExistingCheckinQuery);
if($existingCheckin){
return $existingCheckin;
} else {
throw new Exception("checkinID must refer to an existing checkin");
}
}
/**
* Updates an existing checkin
* @param int $checkinID checkin ID
* @param int $cid customer ID
* @param int $eventID event ID
* @param int $payment payment
* @throws Exception if $checkinID is not a positive integer
* @throws Exception if $cid is not a positive integer
* @throws Exception if $eventID is not a positive integer
* @throws Exception if $payment is not a non-negative integer
* @throws Exception if $checkinID checkin doesn't exists
*/
function updateCheckin($checkinID, $cid, $eventID, $payment){
if(!isInteger($checkinID) || $checkinID < 1){
throw new Exception("checkinID must be a positive integer");
}
if(empty($cid) || !isInteger($cid) || $cid < 1){
throw new Exception("cid must be a positive integer");
}
if(empty($eventID) || !isInteger($eventID) || $eventID < 1){
throw new Exception("eventID must be a positive integer");
}
if(!isInteger($payment) || $payment < 0){
throw new Exception("payment must be a non-negative integer");
}
$existingCheckin = readCheckin($checkinID);
if($existingCheckin){
$updateExistingCheckinSQL = "
UPDATE checkins
SET checkins.customer_id = '$cid', checkins.event_id = '$eventID',
checkins.payment = '$payment'
WHERE checkins.id = '$checkinID'";
mysql_query($updateExistingCheckinSQL) or die(mysql_query());
} else {
throw new Exception("checkinID must refer to an existing checkin");
}
}
/**
* Deletes a checkin
* @param int $checkinID checkin ID
* @throws Exception if $checkinID is not a positive integer
* @throws Exception if $checkinID checkin doesn't exists
*/
function deleteCheckin($checkinID){
if(!isInteger($checkinID) || $checkinID < 1){
throw new Exception("checkinID must be a positive integer");
}
$existingCheckin = readCheckin($checkinID);
if($existingCheckin){
$deleteCheckinSQL = "
UPDATE checkins
SET checkins.status = '0'
WHERE checkins.id = '$checkinID'";
mysql_query($deleteCheckinSQL) or die(mysql_query());
} else {
throw new Exception("checkinID must refer to an existing checkin");
}
}
/**
* Checks in the customer
* @param string $birthday Customer's birthday in YYYY-MM-DD H:i:s format
* @param int $checkinID Customer's previous checkin ID, if applicable. This is
* used to update the previous checkin. (Say you changed the payment amount or
* the customer birthday, etc.) Put in 0 if a new checkin.
* @param int $cid Customer ID number
* @param string $email Customer's email address
* @param int $eventID Event ID that the customer is being checked into
* @param string $name Customer name
* @param int $numberOfFreeEntrances Number of free entrances they have currently
* @param int $payment Amount they paid for this checkin
* @param boolean $useFreeEntrance Whether or not to use a free entrance for this
* checkin
* @return int Returns the checkin ID number of the current checkin. If the
* checkin is a new one then it returns that. If it is an old one then it returns
* the checkin ID you gave for $checkinID.
* @throws Exception if $name is empty
* @throws Exception if $eventID is not a positive integer
* @throws Exception if $payment is not a non-negative integer
* @throws Exception if $checkinID is not a non-negative integer
* @throws Exception if $numberOfFreeEntrances is not a non-negative integer
* @throws Exception if $numberOfFreeEntrances is 0, the checkin hasn't already used
* a free entrance, and you try to use a free entrance for the current checkin
* @throws Exception if $payment is 0, a free entrance hasn't already been used
* for the current checkin and you don't use a free entrance to get in.
*/
function checkinCustomer($birthday, $checkinID, $cid, $email, $eventID, $name, $numberOfFreeEntrances, $payment, $useFreeEntrance){
$organizationID = inferOrganizationID($eventID);
$isFreeEntranceEnabled = isFreeEntranceEnabled($organizationID);
if(empty($name)){
throw new Exception("name must be not empty");
}
if(empty($eventID) || !isInteger($eventID) || $eventID < 1){
throw new Exception("eventID must be a positive integer");
}
if(!isInteger($payment) || $payment < 0){
throw new Exception("payment must be a non-negative integer");
}
if(!isInteger($checkinID) || $checkinID < 0){
throw new Exception("checkinID must be a non-negative integer");
}
//if customer doesn't exist then make them
if(empty($cid)){
$sql = "INSERT INTO customers VALUES ('', '$name', '$email', NULL, NULL, 0, 1, CURRENT_TIMESTAMP)";
$query = mysql_query($sql) or die (mysql_error());
$cid = mysql_insert_id();
}
$sql = "SELECT ch.id as checkin_id, ch.status as checkin_status
FROM checkins AS ch
JOIN customers AS cu
ON ch.customer_id = cu.id
WHERE ch.customer_id = '$cid'
AND ch.event_id = '$eventID'";
$query = mysql_query($sql) or die (mysql_error());
$result = mysql_fetch_array($query);
if($checkinID == 0){
$checkinID = $result['checkin_id'];
}
if($isFreeEntranceEnabled){
if($useFreeEntrance == "false"){
$useFreeEntrance = false;
}
if(!isInteger($numberOfFreeEntrances) || $numberOfFreeEntrances < 0){
throw new Exception("Free Entrances must be non-negative integer");
}
if($checkinID){
$hasUsedFreeEntrance = hasCustomerUsedFreeEntrance($cid, $checkinID);
}
if($useFreeEntrance && $numberOfFreeEntrances == 0 && !$hasUsedFreeEntrance){
throw new Exception("Not enough Free Entrances to use a Free Entrance");
}
if(empty($payment) && $payment != "0" && !$useFreeEntrance && !$hasUsedFreeEntrance){
throw new Exception("Please input payment or use Free Entrance");
}
$databaseNumberOfFreeEntrances = getCustomerNumberOfFreeEntrances($cid);
if($databaseNumberOfFreeEntrances != $numberOfFreeEntrances){
editCustomerNumberOfFreeEntrances($cid, $numberOfFreeEntrances);
}
} else {
if(empty($payment) && $payment != "0"){
throw new Exception("Please input payment");
}
}
if(!$result){
$sql = "INSERT INTO checkins VALUES
('', '$cid', '$eventID', '$payment', '1', CURRENT_TIMESTAMP)";
$query = mysql_query($sql) or die (mysql_error());
if($isFreeEntranceEnabled && $useFreeEntrance){
useFreeEntrance($cid, mysql_insert_id());
}
incrementCustomerVisits($cid);
} else {
if($result['checkin_status'] == 0){
incrementCustomerVisits($cid);
}
$sql = "UPDATE checkins
SET payment = '$payment', checkins.status = '1'
WHERE id = '$checkinID'";
$query = mysql_query($sql) or die (mysql_error());
$sql = "UPDATE customers
SET name = '$name', email = '$email', customers.status = '1'
WHERE id = '$cid'";
$query = mysql_query($sql) or die (mysql_error());
if($isFreeEntranceEnabled && $hasUsedFreeEntrance && !$useFreeEntrance && $checkinID){
unuseFreeEntrance($cid, $checkinID);
}
if($isFreeEntranceEnabled && $useFreeEntrance && !$hasUsedFreeEntrance && $checkinID){
useFreeEntrance($cid, $checkinID);
}
}
editCustomerBirthday($cid, $birthday);
$toReturn = array();
$toReturn['checkinID'] = $checkinID;
return $toReturn;
}
/**
* Checks out the customer.
* @param int $checkinID Checkin ID
* @param int $cid Customer ID
* @param int $eventID Event ID
* @throws Exception if $eventID is not a non-negative integer
* @throws Exception if $cid is not a non-negative integer
* @throws Exception if $checkinID is not a non-negative integer
* @throws Exception if customer is not checked in
*/
function checkoutCustomer($checkinID, $cid, $eventID){
if(!isInteger($eventID) || intval($eventID) < 1){
throw new Exception("Event ID must be a positive integer.");
}
if(!isInteger($cid) || intval($cid) < 1){
throw new Exception("Customer ID must be a positive integer.");
}
$hasCheckedIn = hasCustomerCheckedIn($cid, $eventID);
if(!$hasCheckedIn){
throw new Exception("Cannot checkout a customer who is not checked in.");
}
if(!isInteger($checkinID) || intval($checkinID) < 1){
throw new Exception("Checkin ID must be a positive integer.");
}
$hasCustomerUsedFreeEntrance = hasCustomerUsedFreeEntrance($cid, $checkinID);
if($hasCustomerUsedFreeEntrance){
unuseFreeEntrance($cid, $checkinID);
}
$checkoutCustomerSQL =
"UPDATE checkins
SET checkins.status = '0'
WHERE checkins.id = '$checkinID'";
mysql_query($checkoutCustomerSQL) or die (mysql_error());
$decrementCustomerVisitsSQL =
"UPDATE customers
SET customers.visits = customers.visits - 1
WHERE customers.id = '$cid'";
mysql_query($decrementCustomerVisitsSQL) or die (mysql_error());
$toReturn = array();
$toReturn['checkinID'] = $checkinID;
$toReturn['numberOfFreeEntrances'] = getCustomerNumberOfFreeEntrances($cid);
return $toReturn;
} | mit |
brijeshsmita/commons-spring | 15SpringCustomValidator/src/main/java/com/cg/mvc/controllers/EmployeeController.java | 2120 | package com.cg.mvc.controllers;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.cg.mvc.model.Employee;
@Controller
public class EmployeeController {
private static final Logger logger = LoggerFactory
.getLogger(EmployeeController.class);
private Map<Integer, Employee> emps = null;
@Autowired
@Qualifier("employeeValidator")
private Validator validator;
@InitBinder
private void initBinder(WebDataBinder binder) {
binder.setValidator(validator);
}
public EmployeeController() {
emps = new HashMap<Integer, Employee>();
}
@ModelAttribute("employee")
public Employee createEmployeeModel() {
// ModelAttribute value should be same as used in the empSave.jsp
return new Employee();
}
@RequestMapping(value = "/emp/save", method = RequestMethod.GET)
public String saveEmployeePage(Model model) {
logger.info("Returning empSave.jsp page");
return "empSave";
}
@RequestMapping(value = "/emp/save.do", method = RequestMethod.POST)
public String saveEmployeeAction(
@ModelAttribute("employee") @Validated Employee employee,
BindingResult bindingResult, Model model) {
if (bindingResult.hasErrors()) {
logger.info("Returning empSave.jsp page");
return "empSave";
}
logger.info("Returning empSaveSuccess.jsp page");
model.addAttribute("emp", employee);
emps.put(employee.getId(), employee);
return "empSaveSuccess";
}
}
| mit |
BeejLuig/yt-tutorial-dashboard | db/migrate/20170420222006_remove_locked_from_videos.rb | 129 | class RemoveLockedFromVideos < ActiveRecord::Migration[5.0]
def change
remove_column :videos, :locked?, :boolean
end
end
| mit |
BinaryMuse/battlenet | lib/battlenet.rb | 30 | require 'battlenet/battlenet'
| mit |
danieljameswilliams/tabletennis-tracker | public/assets/javascripts/partials/user/_create.js | 2294 | var App = App || {};
App.SignUp = (function() {
'use strict';
var dom = {},
selectors = {
facebookLoginBtn : 'user-create__btn--facebook'
};
function initialize() {
_setupDOM();
_addEventListeners();
}
function _setupDOM() {
dom.$submit = $('.js-user-create-btn');
dom.$form = $('.js-user-create-form');
}
function _addEventListeners() {
dom.$submit.on('click', _onSubmitClicked );
}
function _onSubmitClicked() {
event.preventDefault();
var $this = $(this);
if( $this.hasClass( selectors.facebookLoginBtn ) ) {
$.when( App.Authentication.Facebook.getLoginStatus() )
.done( function() {
_prepareAuthenticationWithRemote( $this );
} );
}
else {
_prepareAuthenticationWithRemote( $this );
}
}
function _prepareAuthenticationWithRemote( $this ) {
var $this = $this || $(this);
if( $this.hasClass( selectors.facebookLoginBtn ) ) {
FB.api('/me', { fields: 'name' }, function( response ) {
$('input[name=\'name\']', dom.$form).val( response.name );
$('input[name=\'username\']', dom.$form).val( response.id );
});
}
var loginData = dom.$form.serializeArray();
_authenticateWithRemote( loginData );
}
function _authenticateWithRemote( loginData ) {
$.ajax({
type: 'POST',
url: dom.$form.attr('action'),
data: loginData
})
.done(function( response ) {
var data = $.parseJSON( response );
/**
* We are now waiting for some response from the server,
* Which can return 3 types of string status:
* [pending], [active] and [reserved].
*/
if(data.status == 'pending' || data.status == 'active') {
_loginSuccess();
}
else if (data.status == 'reserved') {
alert('Der findes allerde en bruger med dette brugernavn');
}
else {
App.Parse.loginError( data );
alert('Der skete en fejl, supporten er underrettet.');
}
});
}
/**
* Changes the UI to act logged in and personal.
*/
function _loginSuccess() {
dom.$form.html('Du er logget ind som: ' + data.Name);
}
////////////////
// Public API //
////////////////
return {
initialize: initialize
};
})();
| mit |
yuchan/nandacloud | chef/site-cookbooks/nandalxc/metadata.rb | 280 | name 'nandalxc'
maintainer 'YOUR_COMPANY_NAME'
maintainer_email 'YOUR_EMAIL'
license 'All rights reserved'
description 'Installs/Configures nandalxc'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version '0.1.0'
| mit |
KingPixil/ice | src/art/map/__init__.py | 3773 | import math
from ...loader import load
from ...color import generateColors
from ...seed import generateSeed
from ...random import random, randomNoise2DOctaves
from ...graphics import generateData, generatePoints, putColor, clearMargins, writeImage
# Generate
def generate():
# Initialize
seedText = generateSeed() # Seed
data = generateData() # Image data
p = generatePoints(1) # Points
color1, color2 = generateColors()
heights = {} # Heights
coasts = [] # Coasts
level = 0.5 # Sea Level
# Heights
for pcol in p:
for pc in pcol:
x = pc[0]
y = pc[1]
height = heights[(x, y)] = randomNoise2DOctaves(x / 1000.0, y / 1000.0)
if height <= level:
putColor(x, y, data, color1, 0.5, 0.75)
if height > level:
putColor(x, y, data, color2, 0.5, 0.7 - 0.4 * (height - level) / (1.0 - level))
# Coasts
for pcol in p:
for pc in pcol:
x = pc[0]
y = pc[1]
if heights[(x, y)] <= level and (heights.get((x + 1, y), -1) > level or heights.get((x + 1, y - 1), -1) > level or heights.get((x, y - 1), -1) > level or heights.get((x - 1, y - 1), -1) > level or heights.get((x - 1, y), -1) > level or heights.get((x - 1, y + 1), -1) > level or heights.get((x, y + 1), -1) > level or heights.get((x + 1, y + 1), -1) > level):
coasts.append((x, y))
putColor(x, y, data, 0.0, 0.0, 0.0)
# Rivers
for river in range(0, 75):
riverLength = int(100 * random() / 0xFFFFFFFFFFFFFFFF)
x, y = coasts[int(len(coasts) * random() / 0xFFFFFFFFFFFFFFFF)]
currentHeight = heights[(x, y)]
putColor(x, y, data, 0.0, 0.0, 0.0)
# Noise rivers
for part in range(0, riverLength):
va = 2.0 * math.pi * currentHeight
x += math.cos(va)
y += math.sin(va)
xi = int(x)
yi = int(y)
currentHeight = heights.get((xi, yi), None)
if currentHeight is None or currentHeight <= level:
break
else:
coasts.append((xi, yi))
putColor(x, y, data, 0.0, 0.0, 0.0)
# Guided rivers
# for part in range(0, riverHalfLength):
# putColor(x, y, data, 0.0, 0.0, 0.0)
#
# nextHeightCoordinates = [(x + 1, y), (x + 1, y - 1), (x, y - 1), (x - 1, y - 1), (x - 1, y), (x - 1, y + 1), (x, y + 1), (x + 1, y + 1)]
# nextHeights = [heights.get(nextHeightCoordinate, -1) for nextHeightCoordinate in nextHeightCoordinates]
#
# x, y = nextHeightCoordinates[nextHeights.index(max(nextHeights))]
#
# currentHeight = heights.get((x, y), None)
# if currentHeight is None or currentHeight <= level:
# break
# Mountains
for pcolIndex in range(0, len(p), 20):
pcol = p[pcolIndex]
for pcIndex in range(0, len(pcol), 20):
pc = pcol[pcIndex]
x = pc[0]
y = pc[1]
if heights[(x, y)] > (1.5 * level):
putColor(x, y, data, 0.0, 0.0, 0.0)
putColor(x + 1, y + 1, data, 0.0, 0.0, 0.0)
putColor(x + 2, y + 2, data, 0.0, 0.0, 0.0)
putColor(x + 3, y + 3, data, 0.0, 0.0, 0.0)
putColor(x + 4, y + 4, data, 0.0, 0.0, 0.0)
putColor(x + 5, y + 3, data, 0.0, 0.0, 0.0)
putColor(x + 6, y + 2, data, 0.0, 0.0, 0.0)
putColor(x + 7, y + 1, data, 0.0, 0.0, 0.0)
putColor(x + 8, y, data, 0.0, 0.0, 0.0)
# Clear margins
clearMargins(data)
# Write image
writeImage(data)
return seedText
| mit |
Voleking/ICPC | references/aoapc-book/BeginningAlgorithmContests/exercises/ch5/UVa575.cpp | 468 | // UVa575 Skew Binary
// Rujia Liu
// 题意:输入一个Skew Binary,转化成10进制。Skew Binary的右数第k位(k>=0)代表2^(k+1)-1
#include<cstdio>
#include<cstring>
const int maxn = 100;
int main() {
char s[maxn];
while(scanf("%s", s) == 1) {
int n = strlen(s);
if(n == 1 && s[0] == '0') break;
long long v = 0;
for(int k = 0; k < n; k++)
v += (s[n-1-k] - '0') * ((1<<(k+1)) - 1);
printf("%lld\n", v);
}
return 0;
}
| mit |
KatharineOzil/DocPress | application/models/setting_model.php | 1089 | <?php
class Setting_model extends CI_Model {
function __construct()
{
parent::__construct();
}
function get_mail()
{
$this->db->select('value');
$this->db->from('settings');
$this->db->where('key', 'email');
$data = $this->db->get()->result();
if (!count($data)) {
return array('smtp'=>'', 'email'=>'', 'password'=>'');
} else {
return unserialize($data[0]->value);
}
}
function set_mail($smtp, $email, $password)
{
$data = array('smtp'=>$smtp, 'email'=>$email, 'password'=>$password);
$data = serialize($data);
$this->db->select('value');
$this->db->from('settings');
$this->db->where('key', 'email');
$email = $this->db->get()->result();
if (count($email)) {
$this->db->where('key', 'email');
$this->db->update('settings', array('key'=>'email', 'value'=>$data));
} else {
$this->db->insert('settings', array('key'=>'email', 'value'=>$data));
}
}
}
| mit |
yenbekbay/clinic | core/lexicon/ja/category.inc.php | 2376 | <?php
/**
* Category Japanese lexicon topic
*
* @language ja
* @package modx
* @subpackage lexicon
* @author enogu http://www.kuroienogu.net/
* @author honda http://kogus.org
* @author Nick http://smallworld.west-tokyo.com
* @author shimojo http://www.priqia.com/
* @author yamamoto http://kyms.jp
*/
$_lang['categories'] = 'カテゴリー';
$_lang['category_confirm_delete'] = 'カテゴリーを削除しますか?このカテゴリーに属している全てのエレメントは「カテゴリーなし」に分類されます。';
$_lang['category_create'] = 'カテゴリーを作成';
$_lang['category_err_ae'] = '同じ名前のカテゴリーが既に存在するため、このカテゴリーを保存できませんでした。';
$_lang['category_err_create'] = 'カテゴリーの作成中にエラーが発生しました。';
$_lang['category_err_not_found'] = 'カテゴリーが見つかりませんでした。';
$_lang['category_err_nf'] = 'カテゴリーが見つかりませんでした。.';
$_lang['category_err_nfs'] = '%sに関連するカテゴリーは見つかりませんでした。';
$_lang['category_err_ns'] = 'カテゴリーが指定されていません。';
$_lang['category_err_ns_name'] = '正しいカテゴリー名を指定して下さい。';
$_lang['category_err_remove'] = 'カテゴリーの削除中にエラーが発生しました。';
$_lang['category_err_save'] = 'カテゴリーの保存中にエラーが発生しました。';
$_lang['category_existing'] = '存在するカテゴリー';
$_lang['category_heading'] = 'カテゴリー';
$_lang['category_msg'] = 'カテゴリーに属する全てのリソースを閲覧・編集できます。';
$_lang['category_no_chunks'] = 'このカテゴリーに属するチャンクはありません。';
$_lang['category_no_plugins'] = 'このカテゴリーに属するプラグインはありません。';
$_lang['category_no_snippets'] = 'このカテゴリーに関するスニペットはありません。';
$_lang['category_no_templates'] = 'このカテゴリーに属するテンプレートはありません。';
$_lang['category_no_template_variables'] = 'このカテゴリーに属するテンプレート変数はありません。';
$_lang['category_rename'] = 'カテゴリー名の変更';
$_lang['category_remove'] = 'カテゴリーの削除'; | mit |
RevansChen/online-judge | Codewars/8kyu/remove-exclamation-marks/Python/solution1.py | 74 | # Python - 3.6.0
remove_exclamation_marks = lambda s: s.replace('!', '')
| mit |
draffensperger/miletracker | db/migrate/20131101195411_change_events_html_link_to_text.rb | 127 | class ChangeEventsHtmlLinkToText < ActiveRecord::Migration
def change
change_column :events, :html_link, :text
end
end
| mit |
martinski74/SoftUni | C#_Basic/Задачи/ProgrammingBasicJuly2015/05.WiggleWigle/Properties/AssemblyInfo.cs | 1404 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("05.WiggleWigle")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("05.WiggleWigle")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e9c09b31-940e-4f9e-9772-fc4cc9766901")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit |
alexnbio/test | app/DoctrineMigrations/Version20170305141309.php | 1173 | <?php
namespace Application\Migrations;
use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;
/**
* Auto-generated Migration: Please modify to your needs!
*/
class Version20170305141309 extends AbstractMigration
{
/**
* @param Schema $schema
*/
public function up(Schema $schema)
{
// this up() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('CREATE TABLE user (id INT AUTO_INCREMENT NOT NULL, email VARCHAR(255) NOT NULL, UNIQUE INDEX UNIQ_8D93D649E7927C74 (email), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB');
}
/**
* @param Schema $schema
*/
public function down(Schema $schema)
{
// this down() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('DROP TABLE user');
}
}
| mit |
McDirty/Cup_Stacking | Assets/TextMesh Pro/Scripts/TextMeshProUGUI.cs | 40379 | // Copyright (C) 2014 - 2015 Stephan Bouchard - All Rights Reserved
// This code can only be used under the standard Unity Asset Store End User License Agreement
// A Copy of the EULA APPENDIX 1 is available at http://unity3d.com/company/legal/as_terms
// Beta Release 0.1.52 Beta 1c
#if UNITY_4_6 || UNITY_5
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine.EventSystems;
#pragma warning disable 0414 // Disabled a few warnings related to serialized variables not used in this script but used in the editor.
namespace TMPro
{
[ExecuteInEditMode]
[DisallowMultipleComponent]
[RequireComponent(typeof(RectTransform))]
[RequireComponent(typeof(CanvasRenderer))]
[AddComponentMenu("UI/TextMeshPro Text", 12)]
//[SelectionBase]
public partial class TextMeshProUGUI : MaskableGraphic, ILayoutElement
{
// Public Properties & Serializable Properties
/// <summary>
/// A string containing the text to be displayed.
/// </summary>
public string text
{
get { return m_text; }
set { m_inputSource = TextInputSources.Text; havePropertiesChanged = true; m_isCalculateSizeRequired = true; isInputParsingRequired = true; MarkLayoutForRebuild(); m_text = value; /* ScheduleUpdate(); */ }
}
/// <summary>
/// The TextMeshPro font asset to be assigned to this text object.
/// </summary>
public TextMeshProFont font
{
get { return m_fontAsset; }
set { if (m_fontAsset != value) { m_fontAsset = value; LoadFontAsset(); havePropertiesChanged = true; m_isCalculateSizeRequired = true; MarkLayoutForRebuild();/* ScheduleUpdate(); */ } }
}
/// <summary>
/// The material to be assigned to this text object. An instance of the material will be assigned to the object's renderer.
/// </summary>
public Material fontMaterial
{
// Return a new Instance of the Material if none exists. Otherwise return the current Material Instance.
get
{
if (m_fontMaterial == null)
{
SetFontMaterial(m_sharedMaterial);
return m_sharedMaterial;
}
return m_sharedMaterial;
}
// Assigning fontMaterial always returns an instance of the material.
set { SetFontMaterial(value); havePropertiesChanged = true; /* ScheduleUpdate(); */ }
}
///// <summary>
/////
///// </summary>
//public override Material material
//{
// get
// {
// Debug.Log("material property called.");
// return m_sharedMaterial;
// }
// set
// {
// m_sharedMaterial = value;
// }
//}
/// <summary>
/// The material to be assigned to this text object.
/// </summary>
public Material fontSharedMaterial
{
get { return m_uiRenderer.GetMaterial(); }
set { if (m_uiRenderer.GetMaterial() != value) { m_isNewBaseMaterial = true; SetSharedFontMaterial(value); havePropertiesChanged = true; /* ScheduleUpdate(); */ } }
}
/// <summary>
/// The material to be assigned to this text object.
/// </summary>
protected Material fontBaseMaterial
{
get { return m_baseMaterial; }
set { if (m_baseMaterial != value) { SetFontBaseMaterial(value); havePropertiesChanged = true; /* ScheduleUpdate(); */ } }
}
/// <summary>
/// Sets the RenderQueue along with Ztest to force the text to be drawn last and on top of scene elements.
/// </summary>
public bool isOverlay
{
get { return m_isOverlay; }
set { if (m_isOverlay != value) { m_isOverlay = value; SetShaderDepth(); havePropertiesChanged = true; /* ScheduleUpdate(); */ } }
}
/// <summary>
/// This is the default vertex color assigned to each vertices. Color tags will override vertex colors unless the overrideColorTags is set.
/// </summary>
public new Color color
{
get { return m_fontColor; }
set { if (m_fontColor != value) { havePropertiesChanged = true; m_fontColor = value;/* ScheduleUpdate(); */ } }
}
/// <summary>
/// Sets the vertex color alpha value.
/// </summary>
public float alpha
{
get { return m_fontColor.a; }
set { Color c = m_fontColor; c.a = value; m_fontColor = c; havePropertiesChanged = true; }
}
/// <summary>
/// Sets the vertex colors for each of the 4 vertices of the character quads.
/// </summary>
/// <value>The color gradient.</value>
public VertexGradient colorGradient
{
get { return m_fontColorGradient;}
set { havePropertiesChanged = true; m_fontColorGradient = value; }
}
/// <summary>
/// Determines if Vertex Color Gradient should be used
/// </summary>
/// <value><c>true</c> if enable vertex gradient; otherwise, <c>false</c>.</value>
public bool enableVertexGradient
{
get { return m_enableVertexGradient; }
set { havePropertiesChanged = true; m_enableVertexGradient = value; }
}
/// <summary>
/// Sets the color of the _FaceColor property of the assigned material. Changing face color will result in an instance of the material.
/// </summary>
public Color32 faceColor
{
get { return m_faceColor; }
set { if (m_faceColor.Compare(value) == false) { SetFaceColor(value); havePropertiesChanged = true; m_faceColor = value; /* ScheduleUpdate(); */ } }
}
/// <summary>
/// Sets the color of the _OutlineColor property of the assigned material. Changing outline color will result in an instance of the material.
/// </summary>
public Color32 outlineColor
{
get { return m_outlineColor; }
set { if (m_outlineColor.Compare(value) == false) { SetOutlineColor(value); havePropertiesChanged = true; m_outlineColor = value; /* ScheduleUpdate(); */ } }
}
/// <summary>
/// Sets the thickness of the outline of the font. Setting this value will result in an instance of the material.
/// </summary>
public float outlineWidth
{
get { return m_outlineWidth; }
set { SetOutlineThickness(value); havePropertiesChanged = true; checkPaddingRequired = true; m_outlineWidth = value; /* ScheduleUpdate(); */ }
}
/// <summary>
/// The size of the font.
/// </summary>
public float fontSize
{
get { return m_fontSize; }
set { havePropertiesChanged = true; m_isCalculateSizeRequired = true; MarkLayoutForRebuild(); m_fontSize = value; if (!m_enableAutoSizing) m_fontSizeBase = m_fontSize; }
}
/// <summary>
/// The style of the text
/// </summary>
public FontStyles fontStyle
{
get { return m_fontStyle; }
set { m_fontStyle = value; havePropertiesChanged = true; checkPaddingRequired = true; }
}
/// <summary>
/// The amount of additional spacing between characters.
/// </summary>
public float characterSpacing
{
get { return m_characterSpacing; }
set { if (m_characterSpacing != value) { havePropertiesChanged = true; m_isCalculateSizeRequired = true; MarkLayoutForRebuild(); m_characterSpacing = value; /* ScheduleUpdate(); */ } }
}
/// <summary>
/// The amount of additional spacing to add between each lines of text.
/// </summary>
public float lineSpacing
{
get { return m_lineSpacing; }
set { if (m_lineSpacing != value) { havePropertiesChanged = true; m_isCalculateSizeRequired = true; MarkLayoutForRebuild(); m_lineSpacing = value; /* ScheduleUpdate(); */ } }
}
/// <summary>
/// The amount of additional spacing to add between each lines of text.
/// </summary>
public float paragraphSpacing
{
get { return m_paragraphSpacing; }
set { if (m_paragraphSpacing != value) { havePropertiesChanged = true; m_isCalculateSizeRequired = true; MarkLayoutForRebuild(); m_paragraphSpacing = value; /* ScheduleUpdate(); */ } }
}
/// <summary>
/// Enables or Disables Rich Text Tags
/// </summary>
public bool richText
{
get { return m_isRichText; }
set { m_isRichText = value; havePropertiesChanged = true; m_isCalculateSizeRequired = true; MarkLayoutForRebuild(); isInputParsingRequired = true; }
}
/// <summary>
/// Enables or Disables parsing of CTRL characters in input text.
/// </summary>
public bool parseCtrlCharacters
{
get { return m_parseCtrlCharacters; }
set { m_parseCtrlCharacters = value; havePropertiesChanged = true; m_isCalculateSizeRequired = true; MarkLayoutForRebuild(); isInputParsingRequired = true; }
}
/// <summary>
/// Controls the Text Overflow Mode
/// </summary>
public TextOverflowModes OverflowMode
{
get { return m_overflowMode; }
set { m_overflowMode = value; havePropertiesChanged = true; m_isRecalculateScaleRequired = true; }
}
/// <summary>
///
/// </summary>
public Texture texture;
public override Texture mainTexture
{
get
{
if ((UnityEngine.Object)this.texture == (UnityEngine.Object)null)
return (Texture)Graphic.s_WhiteTexture;
else
return this.texture;
}
}
/// <summary>
/// Contains the bounds of the text object.
/// </summary>
public Bounds bounds
{
get { if (m_uiVertices != null) return m_bounds; return new Bounds(); }
//set { if (_meshExtents != value) havePropertiesChanged = true; _meshExtents = value; }
}
//public Mesh mesh
//{
// get { return m_textInfo.meshInfo.uiVertices; }
//}
/// <summary>
/// Determines the anchor position of the text object.
/// </summary>
//public AnchorPositions anchor
//{
// get { return m_anchor; }
// set { if (m_anchor != value) { havePropertiesChanged = true; m_anchor = value; /* ScheduleUpdate(); */ } }
//}
/// <summary>
/// Text alignment options
/// </summary>
public TextAlignmentOptions alignment
{
get { return m_textAlignment; }
set { if (m_textAlignment != value) { havePropertiesChanged = true; m_textAlignment = value; /* ScheduleUpdate(); */ } }
}
/// <summary>
/// Determines if kerning is enabled or disabled.
/// </summary>
public bool enableKerning
{
get { return m_enableKerning; }
set { if (m_enableKerning != value) { havePropertiesChanged = true; m_isCalculateSizeRequired = true; MarkLayoutForRebuild(); m_enableKerning = value; /* ScheduleUpdate(); */ } }
}
/// <summary>
/// Anchor dampening prevents the anchor position from being adjusted unless the positional change exceeds about 40% of the width of the underline character. This essentially stabilizes the anchor position.
/// </summary>
//public bool anchorDampening
//{
// get { return m_anchorDampening; }
// set { if (m_anchorDampening != value) { havePropertiesChanged = true; m_anchorDampening = value; /* ScheduleUpdate(); */ } }
//}
/// <summary>
/// This overrides the color tags forcing the vertex colors to be the default font color.
/// </summary>
public bool overrideColorTags
{
get { return m_overrideHtmlColors; }
set { if (m_overrideHtmlColors != value) { havePropertiesChanged = true; m_overrideHtmlColors = value; /* ScheduleUpdate(); */ } }
}
/// <summary>
/// Adds extra padding around each character. This may be necessary when the displayed text is very small to prevent clipping.
/// </summary>
public bool extraPadding
{
get { return m_enableExtraPadding; }
set { if (m_enableExtraPadding != value) { havePropertiesChanged = true; checkPaddingRequired = true; m_enableExtraPadding = value; m_isCalculateSizeRequired = true; MarkLayoutForRebuild();/* ScheduleUpdate(); */ } }
}
/// <summary>
/// Controls whether or not word wrapping is applied. When disabled, the text will be displayed on a single line.
/// </summary>
public bool enableWordWrapping
{
get { return m_enableWordWrapping; }
set { if (m_enableWordWrapping != value) { havePropertiesChanged = true; isInputParsingRequired = true; m_isRecalculateScaleRequired = true; m_enableWordWrapping = value; /* ScheduleUpdate(); */ } }
}
/// <summary>
/// Controls how the face and outline textures will be applied to the text object.
/// </summary>
public TextureMappingOptions horizontalMapping
{
get { return m_horizontalMapping; }
set { if (m_horizontalMapping != value) { havePropertiesChanged = true; m_horizontalMapping = value; /* ScheduleUpdate(); */ } }
}
/// <summary>
/// Controls how the face and outline textures will be applied to the text object.
/// </summary>
public TextureMappingOptions verticalMapping
{
get { return m_verticalMapping; }
set { if (m_verticalMapping != value) { havePropertiesChanged = true; m_verticalMapping = value; /* ScheduleUpdate(); */ } }
}
/// <summary>
/// Forces objects that are not visible to get refreshed.
/// </summary>
public bool ignoreVisibility
{
get { return m_ignoreCulling; }
set { if (m_ignoreCulling != value) { havePropertiesChanged = true; m_ignoreCulling = value; /* ScheduleUpdate(); */ } }
}
/// <summary>
/// Sets Perspective Correction to Zero for Orthographic Camera mode & 0.875f for Perspective Camera mode.
/// </summary>
public bool isOrthographic
{
get { return m_isOrthographic; }
set { havePropertiesChanged = true; m_isOrthographic = value; /* ScheduleUpdate(); */ }
}
/// <summary>
/// Sets the culling on the shaders. Note changing this value will result in an instance of the material.
/// </summary>
public bool enableCulling
{
get { return m_isCullingEnabled; }
set { m_isCullingEnabled = value; SetCulling(); havePropertiesChanged = true; }
}
/// <summary>
/// Sets the Renderer's sorting Layer ID
/// </summary>
//public int sortingLayerID
//{
// get { return m_sortingLayerID; }
// set { m_sortingLayerID = value; /*m_renderer.sortingLayerID = value;*/ }
//}
/// <summary>
/// Sets the Renderer's sorting order within the assigned layer.
/// </summary>
//public int sortingOrder
//{
// get { return m_sortingOrder; }
// set { m_sortingOrder = value; /*m_renderer.sortingOrder = value;*/ }
//}
/// <summary>
/// Determines if the Mesh will be uploaded.
/// </summary>
public TextRenderFlags renderMode
{
get { return m_renderMode; }
set { m_renderMode = value; havePropertiesChanged = true; }
}
public bool hasChanged
{
get { return havePropertiesChanged; }
set { havePropertiesChanged = value; }
}
/// <summary>
/// <para>Sets the margin for the text inside the Rect Transform.</para>
/// <para>Vector4 (left, top, right, bottom);</para>
/// </summary>
public Vector4 margin
{
get { return m_margin; }
set { /* if (m_margin != value) */ { m_margin = value; /* Debug.Log("Margin is " + margin); ComputeMarginSize();*/ havePropertiesChanged = true; m_marginsHaveChanged = true; } }
}
/// <summary>
/// Allows to control how many characters are visible from the input.
/// </summary>
public int maxVisibleCharacters
{
get { return m_maxVisibleCharacters; }
set { if (m_maxVisibleCharacters != value) { havePropertiesChanged = true; m_maxVisibleCharacters = value; } }
}
/// <summary>
/// Allows to control how many words are visible from the input.
/// </summary>
public int maxVisibleWords
{
get { return m_maxVisibleWords; }
set { if (m_maxVisibleWords != value) { havePropertiesChanged = true; m_maxVisibleWords = value; } }
}
/// <summary>
/// Allows control over how many lines of text are displayed.
/// </summary>
public int maxVisibleLines
{
get { return m_maxVisibleLines; }
set { if (m_maxVisibleLines != value) { havePropertiesChanged = true; isInputParsingRequired = true; m_maxVisibleLines = value; } }
}
/// <summary>
/// Controls which page of text is shown
/// </summary>
public int pageToDisplay
{
get { return m_pageToDisplay; }
set { havePropertiesChanged = true; m_pageToDisplay = value; }
}
/// <summary>
/// Returns are reference to the RectTransform
/// </summary>
public new RectTransform rectTransform
{
get
{
if (m_rectTransform == null)
m_rectTransform = GetComponent<RectTransform>();
return m_rectTransform;
}
}
//public TMPro_TextMetrics metrics
//{
// get { return m_textMetrics; }
//}
//public int characterCount
//{
// get { return m_textInfo.characterCount; }
//}
//public int lineCount
//{
// get { return m_textInfo.lineCount; }
//}
//public Vector2[] spacePositions
//{
// get { return m_spacePositions; }
//}
public bool enableAutoSizing
{
get { return m_enableAutoSizing; }
set { m_enableAutoSizing = value; }
}
public float fontSizeMin
{
get { return m_fontSizeMin; }
set { m_fontSizeMin = value; }
}
public float fontSizeMax
{
get { return m_fontSizeMax; }
set { m_fontSizeMax = value; }
}
// ILayoutElement Implementation
public float flexibleHeight { get { return m_flexibleHeight; } }
private float m_flexibleHeight;
public float flexibleWidth { get { return m_flexibleWidth; } }
private float m_flexibleWidth;
public float minHeight { get { return m_minHeight; } }
private float m_minHeight;
public float minWidth { get { return m_minWidth; } }
private float m_minWidth;
public float preferredWidth { get { return m_preferredWidth == 9999 ? m_renderedWidth : m_preferredWidth; } }
private float m_preferredWidth = 9999;
public float preferredHeight { get { return m_preferredHeight == 9999 ? m_renderedHeight : m_preferredHeight; } }
private float m_preferredHeight = 9999;
// Used to track actual rendered size of the text object.
private float m_renderedWidth;
private float m_renderedHeight;
public int layoutPriority { get { return m_layoutPriority; } }
private int m_layoutPriority = 0;
private bool m_isRebuildingLayout = false;
private bool m_isLayoutDirty = false;
private enum AutoLayoutPhase { Horizontal, Vertical };
private AutoLayoutPhase m_LayoutPhase;
//private TextOverflowModes m_currentOverflowMode;
private bool m_currentAutoSizeMode;
private float GetPreferredWidth()
{
TextOverflowModes currentOverflowMode = m_overflowMode;
m_overflowMode = TextOverflowModes.Overflow;
m_renderMode = TextRenderFlags.GetPreferredSizes;
GenerateTextMesh();
m_renderMode = TextRenderFlags.Render;
m_overflowMode = currentOverflowMode;
Debug.Log("GetPreferredWidth() Called. Returning width of " + m_preferredWidth);
return m_preferredWidth;
}
private float GetPreferredHeight()
{
TextOverflowModes currentOverflowMode = m_overflowMode;
m_overflowMode = TextOverflowModes.Overflow;
m_renderMode = TextRenderFlags.GetPreferredSizes;
GenerateTextMesh();
m_renderMode = TextRenderFlags.Render;
m_overflowMode = currentOverflowMode;
Debug.Log("GetPreferredHeight() Called. Returning height of " + m_preferredHeight);
return m_preferredHeight;
}
public void CalculateLayoutInputHorizontal()
{
//Debug.Log("CalculateLayoutHorizontal() at Frame: " + Time.frameCount); // called on Object ID " + GetInstanceID());
// Check if object is active
if (!this.gameObject.activeInHierarchy)
return;
IsRectTransformDriven = true;
// Get a Reference to the Driving Layout Controller
//if ((m_layoutController as UIBehaviour) == null)
//{
// m_layoutController = GetComponent(typeof(ILayoutController)) as ILayoutController ?? (transform.parent != null ? transform.parent.GetComponent(typeof(ILayoutController)) as ILayoutController : null);
// if (m_layoutController != null)
// IsRectTransformDriven = true;
// else
// {
// IsRectTransformDriven = false;
// return;
// }
//}
m_currentAutoSizeMode = m_enableAutoSizing;
//if (m_isCalculateSizeRequired || m_rectTransform.hasChanged)
//{
m_LayoutPhase = AutoLayoutPhase.Horizontal;
m_isRebuildingLayout = true;
m_minWidth = 0;
m_flexibleWidth = 0;
m_renderMode = TextRenderFlags.GetPreferredSizes; // Set Text to not Render and exit early once we have new width values.
if (m_enableAutoSizing)
{
m_fontSize = m_fontSizeMax;
}
// Set Margins to Infinity
m_marginWidth = Mathf.Infinity;
m_marginHeight = Mathf.Infinity;
if (isInputParsingRequired || m_isTextTruncated)
ParseInputText();
GenerateTextMesh();
m_renderMode = TextRenderFlags.Render;
m_preferredWidth = m_renderedWidth; // (int)(m_renderedWidth + 1f);
ComputeMarginSize();
//Debug.Log("Preferred Width: " + m_preferredWidth + " Margin Width: " + m_marginWidth + " Preferred Height: " + m_preferredHeight + " Margin Height: " + m_marginHeight + " Rendered Width: " + m_renderedWidth + " Height: " + m_renderedHeight + " RectTransform Width: " + m_rectTransform.rect);
m_isLayoutDirty = true;
//}
}
public void CalculateLayoutInputVertical()
{
// Check if object is active
if (!this.gameObject.activeInHierarchy) // || IsRectTransformDriven == false)
return;
IsRectTransformDriven = true;
//Debug.Log("CalculateLayoutInputVertical() at Frame: " + Time.frameCount); // called on Object ID " + GetInstanceID());
//if (m_isCalculateSizeRequired || m_rectTransform.hasChanged)
//{
m_LayoutPhase = AutoLayoutPhase.Vertical;
m_isRebuildingLayout = true;
m_minHeight = 0;
m_flexibleHeight = 0;
m_renderMode = TextRenderFlags.GetPreferredSizes;
if (m_enableAutoSizing)
{
m_currentAutoSizeMode = true;
m_enableAutoSizing = false;
}
m_marginHeight = Mathf.Infinity;
GenerateTextMesh();
m_enableAutoSizing = m_currentAutoSizeMode;
m_renderMode = TextRenderFlags.Render;
ComputeMarginSize();
m_preferredHeight = m_renderedHeight; // (int)(m_renderedHeight + 1f);
//Debug.Log("Preferred Height: " + m_preferredHeight + " Margin Height: " + m_marginHeight + " Preferred Width: " + m_preferredWidth + " Margin Width: " + m_marginWidth + " Rendered Width: " + m_renderedWidth + " Height: " + m_renderedHeight + " RectTransform Width: " + m_rectTransform.rect);
m_isLayoutDirty = true;
//}
m_isCalculateSizeRequired = false;
}
// ICanvasElement
//public void Rebuild(CanvasUpdate update)
//{
// Debug.Log("Rebuild()");
// LayoutRebuilder.MarkLayoutForRebuild(m_rectTransform);
//}
//public bool IsDestroyed()
//{
// return true;
//}
//public override bool Raycast(Vector2 sp, Camera eventCamera)
//{
// //Debug.Log("Raycast Event. ScreenPoint: " + sp);
// return base.Raycast(sp, eventCamera);
//}
// MASKING RELATED PROPERTIES
/// <summary>
/// Sets the masking offset from the bounds of the object
/// </summary>
public Vector4 maskOffset
{
get { return m_maskOffset; }
set { m_maskOffset = value; UpdateMask(); havePropertiesChanged = true; }
}
//public override Material defaultMaterial
//{
// get { Debug.Log("Default Material called."); return m_sharedMaterial; }
//}
//protected override void OnCanvasHierarchyChanged()
//{
// //Debug.Log("OnCanvasHierarchyChanged...");
//}
/// <summary>
/// Method called when the state of a parent changes.
/// </summary>
public override void RecalculateClipping()
{
//Debug.Log("***** RecalculateClipping() *****");
base.RecalculateClipping();
}
/// <summary>
/// Method called when Stencil Mask needs to be updated on this element and parents.
/// </summary>
public override void RecalculateMasking()
{
//Debug.Log("***** RecalculateMasking() *****");
if (m_fontAsset == null) return;
m_stencilID = MaterialManager.GetStencilID(gameObject);
if (!m_isAwake)
return;
if (m_stencilID == 0)
{
if (m_maskingMaterial != null)
{
MaterialManager.ReleaseStencilMaterial(m_maskingMaterial);
m_maskingMaterial = null;
m_sharedMaterial = m_baseMaterial;
}
else if (m_fontMaterial != null)
m_sharedMaterial = MaterialManager.SetStencil(m_fontMaterial, 0);
}
else
{
ShaderUtilities.GetShaderPropertyIDs();
if (m_fontMaterial != null)
{
m_sharedMaterial = MaterialManager.SetStencil(m_fontMaterial, m_stencilID);
}
else if (m_maskingMaterial == null)
{
m_maskingMaterial = MaterialManager.GetStencilMaterial(m_baseMaterial, m_stencilID);
m_sharedMaterial = m_maskingMaterial;
}
else if (m_maskingMaterial.GetInt(ShaderUtilities.ID_StencilID) != m_stencilID || m_isNewBaseMaterial)
{
MaterialManager.ReleaseStencilMaterial(m_maskingMaterial);
m_maskingMaterial = MaterialManager.GetStencilMaterial(m_baseMaterial, m_stencilID);
m_sharedMaterial = m_maskingMaterial;
}
if (m_isMaskingEnabled)
EnableMasking();
//Debug.Log("Masking Enabled. Assigning " + m_maskingMaterial.name + " with ID " + m_maskingMaterial.GetInstanceID());
}
m_uiRenderer.SetMaterial(m_sharedMaterial, null);
m_padding = ShaderUtilities.GetPadding(m_sharedMaterial, m_enableExtraPadding, m_isUsingBold);
m_alignmentPadding = ShaderUtilities.GetFontExtent(m_sharedMaterial);
}
public override void SetVerticesDirty()
{
//Debug.Log("Set Vertices Dirty called.");
if (m_fontColor != base.color) this.color = base.color;
base.SetVerticesDirty();
}
protected override void UpdateGeometry()
{
//Debug.Log("UpdateGeometry");
//base.UpdateGeometry();
}
protected override void UpdateMaterial()
{
//Debug.Log("UpdateMaterial called.");
// base.UpdateMaterial();
}
/*
/// <summary>
/// Sets the mask type
/// </summary>
public MaskingTypes mask
{
get { return m_mask; }
set { m_mask = value; havePropertiesChanged = true; isMaskUpdateRequired = true; }
}
/// <summary>
/// Set the masking offset mode (as percentage or pixels)
/// </summary>
public MaskingOffsetMode maskOffsetMode
{
get { return m_maskOffsetMode; }
set { m_maskOffsetMode = value; havePropertiesChanged = true; isMaskUpdateRequired = true; }
}
*/
/*
/// <summary>
/// Sets the softness of the mask
/// </summary>
public Vector2 maskSoftness
{
get { return m_maskSoftness; }
set { m_maskSoftness = value; havePropertiesChanged = true; isMaskUpdateRequired = true; }
}
/// <summary>
/// Allows to move / offset the mesh vertices by a set amount
/// </summary>
public Vector2 vertexOffset
{
get { return m_vertexOffset; }
set { m_vertexOffset = value; havePropertiesChanged = true; isMaskUpdateRequired = true; }
}
*/
public TMP_TextInfo textInfo
{
get { return m_textInfo; }
}
//public TMPro_MeshInfo meshInfo
//{
// get { return m_meshInfo; }
//}
public UIVertex[] mesh
{
get { return m_uiVertices; }
}
public new CanvasRenderer canvasRenderer
{
get { return m_uiRenderer; }
}
public InlineGraphicManager inlineGraphicManager
{
get { return m_inlineGraphics; }
}
//public TMP_CharacterInfo[] characterInfo
//{
// get { return m_textInfo.characterInfo; }
//
//}
/// <summary>
/// Function to be used to force recomputing of character padding when Shader / Material properties have been changed via script.
/// </summary>
public void UpdateMeshPadding()
{
m_padding = ShaderUtilities.GetPadding(new Material[] {m_uiRenderer.GetMaterial()}, m_enableExtraPadding, m_isUsingBold);
havePropertiesChanged = true;
/* ScheduleUpdate(); */
}
/// <summary>
/// Function to force regeneration of the mesh before its normal process time. This is useful when changes to the text object properties need to be applied immediately.
/// </summary>
public void ForceMeshUpdate()
{
//Debug.Log("ForceMeshUpdate() called.");
//havePropertiesChanged = true;
OnPreRenderCanvas();
}
public void UpdateFontAsset()
{
LoadFontAsset();
}
/// <summary>
/// Function used to evaluate the length of a text string.
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public TMP_TextInfo GetTextInfo(string text)
{
//TextInfo temp_textInfo = new TextInfo();
StringToCharArray(text, ref m_char_buffer);
m_renderMode = TextRenderFlags.DontRender;
GenerateTextMesh();
m_renderMode = TextRenderFlags.Render;
//this.text = string.Empty;
return this.textInfo;
}
//public Vector2[] SetTextWithSpaces(string text, int numPositions)
//{
// m_spacePositions = new Vector2[numPositions];
// this.text = text;
// return m_spacePositions;
//}
/// <summary>
/// <para>Formatted string containing a pattern and a value representing the text to be rendered.</para>
/// <para>ex. TextMeshPro.SetText ("Number is {0:1}.", 5.56f);</para>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="text">String containing the pattern."</param>
/// <param name="arg0">Value is a float.</param>
public void SetText (string text, float arg0)
{
SetText(text, arg0, 255, 255);
}
/// <summary>
/// <para>Formatted string containing a pattern and a value representing the text to be rendered.</para>
/// <para>ex. TextMeshPro.SetText ("First number is {0} and second is {1:2}.", 10, 5.756f);</para>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="text">String containing the pattern."</param>
/// <param name="arg0">Value is a float.</param>
/// <param name="arg1">Value is a float.</param>
public void SetText (string text, float arg0, float arg1)
{
SetText(text, arg0, arg1, 255);
}
/// <summary>
/// <para>Formatted string containing a pattern and a value representing the text to be rendered.</para>
/// <para>ex. TextMeshPro.SetText ("A = {0}, B = {1} and C = {2}.", 2, 5, 7);</para>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="text">String containing the pattern."</param>
/// <param name="arg0">Value is a float.</param>
/// <param name="arg1">Value is a float.</param>
/// <param name="arg2">Value is a float.</param>
public void SetText (string text, float arg0, float arg1, float arg2)
{
// Early out if nothing has been changed from previous invocation.
if (text == old_text && arg0 == old_arg0 && arg1 == old_arg1 && arg2 == old_arg2)
{
return;
}
old_text = text;
old_arg1 = 255;
old_arg2 = 255;
int decimalPrecision = 0;
int index = 0;
for (int i = 0; i < text.Length; i++)
{
char c = text[i];
if (c == 123) // '{'
{
// Check if user is requesting some decimal precision. Format is {0:2}
if (text[i + 2] == 58) // ':'
{
decimalPrecision = text[i + 3] - 48;
}
switch (text[i + 1] - 48)
{
case 0: // 1st Arg
old_arg0 = arg0;
AddFloatToCharArray(arg0, ref index, decimalPrecision);
break;
case 1: // 2nd Arg
old_arg1 = arg1;
AddFloatToCharArray(arg1, ref index, decimalPrecision);
break;
case 2: // 3rd Arg
old_arg2 = arg2;
AddFloatToCharArray(arg2, ref index, decimalPrecision);
break;
}
if (text[i + 2] == 58)
i += 4;
else
i += 2;
continue;
}
m_input_CharArray[index] = c;
index += 1;
}
m_input_CharArray[index] = (char)0;
m_charArray_Length = index; // Set the length to where this '0' termination is.
#if UNITY_EDITOR
// Create new string to be displayed in the Input Text Box of the Editor Panel.
m_text = new string(m_input_CharArray, 0, index);
#endif
m_inputSource = TextInputSources.SetText;
isInputParsingRequired = true;
havePropertiesChanged = true;
/* ScheduleUpdate(); */
}
/// <summary>
/// Character array containing the text to be displayed.
/// </summary>
/// <param name="charArray"></param>
public void SetCharArray(char[] charArray)
{
if (charArray == null || charArray.Length == 0)
return;
// Check to make sure chars_buffer is large enough to hold the content of the string.
if (m_char_buffer.Length <= charArray.Length)
{
int newSize = Mathf.NextPowerOfTwo(charArray.Length + 1);
m_char_buffer = new int[newSize];
}
int index = 0;
for (int i = 0; i < charArray.Length; i++)
{
if (charArray[i] == 92 && i < charArray.Length - 1)
{
switch ((int)charArray[i + 1])
{
case 110: // \n LineFeed
m_char_buffer[index] = (char)10;
i += 1;
index += 1;
continue;
case 114: // \r LineFeed
m_char_buffer[index] = (char)13;
i += 1;
index += 1;
continue;
case 116: // \t Tab
m_char_buffer[index] = (char)9;
i += 1;
index += 1;
continue;
}
}
m_char_buffer[index] = charArray[i];
index += 1;
}
m_char_buffer[index] = (char)0;
m_inputSource = TextInputSources.SetCharArray;
havePropertiesChanged = true;
isInputParsingRequired = true;
}
}
}
#endif | mit |
QuickOrBeDead/Dynamic-Wcf-Client-Proxy | Labo.ServiceModel.Core/Utils/Reflection/DynamicMethodCompiler.cs | 5739 | using System;
using System.Globalization;
using System.Reflection;
using System.Reflection.Emit;
using Labo.ServiceModel.Core.Utils.Reflection.Exceptions;
namespace Labo.ServiceModel.Core.Utils.Reflection
{
public delegate object GetHandler(object source);
public delegate void SetHandler(object source, object value);
public delegate object InstantiateObjectHandler();
/// <summary>
/// http://www.codeproject.com/KB/cs/Dynamic_Code_Generation.aspx
/// </summary>
internal static class DynamicMethodCompiler
{
internal static InstantiateObjectHandler CreateInstantiateStructHandler(Type type)
{
DynamicMethod dynamicMethod = new DynamicMethod(string.Empty, typeof(object), null, type, true);
ILGenerator generator = dynamicMethod.GetILGenerator();
LocalBuilder tmpLocal = generator.DeclareLocal(type);
generator.Emit(OpCodes.Ldloca, tmpLocal);
generator.Emit(OpCodes.Initobj, type);
generator.Emit(OpCodes.Ldloc, tmpLocal);
generator.Emit(OpCodes.Box, type);
generator.Emit(OpCodes.Ret);
return (InstantiateObjectHandler)dynamicMethod.CreateDelegate(typeof(InstantiateObjectHandler));
}
internal static InstantiateObjectHandler CreateInstantiateObjectHandler(Type type, ConstructorInfo constructorInfo)
{
if (constructorInfo == null)
{
throw new DynamicMethodCompilerException(string.Format(CultureInfo.CurrentCulture, "The type {0} must declare an empty constructor (the constructor may be private, internal, protected, protected internal, or public).", type));
}
DynamicMethod dynamicMethod = new DynamicMethod(".ctor",
MethodAttributes.Static | MethodAttributes.Public, CallingConventions.Standard,
typeof(object), null, type, true);
ILGenerator generator = dynamicMethod.GetILGenerator();
generator.Emit(OpCodes.Newobj, constructorInfo);
generator.Emit(OpCodes.Ret);
return (InstantiateObjectHandler)dynamicMethod.CreateDelegate(typeof(InstantiateObjectHandler));
}
// CreateGetDelegate
internal static GetHandler CreateGetHandler(Type type, PropertyInfo propertyInfo)
{
MethodInfo getMethodInfo = propertyInfo.GetGetMethod(true);
DynamicMethod dynamicGet = CreateGetDynamicMethod(type);
ILGenerator getGenerator = dynamicGet.GetILGenerator();
getGenerator.Emit(OpCodes.Ldarg_0);
getGenerator.Emit(OpCodes.Call, getMethodInfo);
BoxIfNeeded(getMethodInfo.ReturnType, getGenerator);
getGenerator.Emit(OpCodes.Ret);
return (GetHandler)dynamicGet.CreateDelegate(typeof(GetHandler));
}
// CreateGetDelegate
internal static GetHandler CreateGetHandler(Type type, FieldInfo fieldInfo)
{
DynamicMethod dynamicGet = CreateGetDynamicMethod(type);
ILGenerator getGenerator = dynamicGet.GetILGenerator();
getGenerator.Emit(OpCodes.Ldarg_0);
getGenerator.Emit(OpCodes.Ldfld, fieldInfo);
BoxIfNeeded(fieldInfo.FieldType, getGenerator);
getGenerator.Emit(OpCodes.Ret);
return (GetHandler)dynamicGet.CreateDelegate(typeof(GetHandler));
}
// CreateSetDelegate
internal static SetHandler CreateSetHandler(Type type, PropertyInfo propertyInfo)
{
MethodInfo setMethodInfo = propertyInfo.GetSetMethod(true);
DynamicMethod dynamicSet = CreateSetDynamicMethod(type);
ILGenerator setGenerator = dynamicSet.GetILGenerator();
setGenerator.Emit(OpCodes.Ldarg_0);
setGenerator.Emit(OpCodes.Ldarg_1);
UnboxIfNeeded(setMethodInfo.GetParameters()[0].ParameterType, setGenerator);
setGenerator.Emit(OpCodes.Call, setMethodInfo);
setGenerator.Emit(OpCodes.Ret);
return (SetHandler)dynamicSet.CreateDelegate(typeof(SetHandler));
}
// CreateSetDelegate
internal static SetHandler CreateSetHandler(Type type, FieldInfo fieldInfo)
{
DynamicMethod dynamicSet = CreateSetDynamicMethod(type);
ILGenerator setGenerator = dynamicSet.GetILGenerator();
setGenerator.Emit(OpCodes.Ldarg_0);
setGenerator.Emit(OpCodes.Ldarg_1);
UnboxIfNeeded(fieldInfo.FieldType, setGenerator);
setGenerator.Emit(OpCodes.Stfld, fieldInfo);
setGenerator.Emit(OpCodes.Ret);
return (SetHandler)dynamicSet.CreateDelegate(typeof(SetHandler));
}
// CreateGetDynamicMethod
private static DynamicMethod CreateGetDynamicMethod(Type type)
{
return DynamicMethodHelper.CreateDynamicMethod("DynamicGet", type, typeof(object), new [] { typeof(object) });
}
// CreateSetDynamicMethod
private static DynamicMethod CreateSetDynamicMethod(Type type)
{
return DynamicMethodHelper.CreateDynamicMethod("DynamicSet", type, typeof(void), new [] { typeof(object), typeof(object) });
}
// BoxIfNeeded
private static void BoxIfNeeded(Type type, ILGenerator generator)
{
if (type.IsValueType)
{
generator.Emit(OpCodes.Box, type);
}
}
// UnboxIfNeeded
private static void UnboxIfNeeded(Type type, ILGenerator generator)
{
if (type.IsValueType)
{
generator.Emit(OpCodes.Unbox_Any, type);
}
}
}
}
| mit |
gregmcguffey/BagOUtils | src/Guards/Messages/ItemTemplate.cs | 2086 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BagOUtils.Guards.Messages
{
/// <summary>
/// Class that defines templates that take the name of an item.
/// </summary>
public class ItemTemplate
{
//-------------------------------------------------------------------------
//
// Defined Message Templates
//
//-------------------------------------------------------------------------
public static ItemTemplate NotTrue
= new ItemTemplate("The operation requires that '{item}' be true, but it is false.");
public static ItemTemplate NotFalse
= new ItemTemplate("The operation requires that '{item}' be false, but it is true.");
public static ItemTemplate NoElements
= new ItemTemplate("The collection, '{item}', has no elements.");
public static ItemTemplate NoItems
= new ItemTemplate("The collection, '{item}', has no items.");
public static ItemTemplate IsNull
= new ItemTemplate("The value of '{item}' is required but it is null.");
public static ItemTemplate IsSet
= new ItemTemplate("The value of '{item}' must be set to a non-null, non-empty, non-whitespace only string.");
//-------------------------------------------------------------------------
//
// Instance
//
//-------------------------------------------------------------------------
private readonly string template;
private string item;
public ItemTemplate(string template)
{
this.template = template;
}
public ItemTemplate UsingItem(string item)
{
this.item = item.NullToEmpty();
return this;
}
public string Prepare()
{
var preparedMessage = this
.template
.Replace("{item}", this.item);
return preparedMessage;
}
}
}
| mit |
stratton-oakcoin/oakcoin | src/qt/bitcoinstrings.cpp | 24549 |
#include <QtGlobal>
// Automatically generated by extract_strings_qt.py
#ifdef __GNUC__
#define UNUSED __attribute__((unused))
#else
#define UNUSED
#endif
static const char UNUSED *oakcoin_strings[] = {
QT_TRANSLATE_NOOP("oakcoin-core", "Oakcoin Core"),
QT_TRANSLATE_NOOP("oakcoin-core", "The %s developers"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"(1 = keep tx meta data e.g. account owner and payment request information, 2 "
"= drop tx meta data)"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"-maxtxfee is set very high! Fees this large could be paid on a single "
"transaction."),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"A fee rate (in %s/kB) that will be used when fee estimation has insufficient "
"data (default: %s)"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Accept connections from outside (default: 1 if no -proxy or -connect/-"
"noconnect)"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Accept relayed transactions received from whitelisted peers even when not "
"relaying transactions (default: %d)"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Allow JSON-RPC connections from specified source. Valid for <ip> are a "
"single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or "
"a network/CIDR (e.g. 1.2.3.4/24). This option can be specified multiple times"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Bind to given address and always listen on it. Use [host]:port notation for "
"IPv6"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Bind to given address and whitelist peers connecting to it. Use [host]:port "
"notation for IPv6"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Bind to given address to listen for JSON-RPC connections. Use [host]:port "
"notation for IPv6. This option can be specified multiple times (default: "
"bind to all interfaces)"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Cannot obtain a lock on data directory %s. %s is probably already running."),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Connect only to the specified node(s); -noconnect or -connect=0 alone to "
"disable automatic connections"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Create new files with system default permissions, instead of umask 077 (only "
"effective with disabled wallet functionality)"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Delete all wallet transactions and only recover those parts of the "
"blockchain through -rescan on startup"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Discover own IP addresses (default: 1 when listening and no -externalip or -"
"proxy)"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Distributed under the MIT software license, see the accompanying file %s or "
"%s"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Do not keep transactions in the mempool longer than <n> hours (default: %u)"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Equivalent bytes per sigop in transactions for relay and mining (default: %u)"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Error loading %s: You can't enable HD on a already existing non-HD wallet"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Error reading %s! All keys read correctly, but transaction data or address "
"book entries might be missing or incorrect."),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Error: Listening for incoming connections failed (listen returned error %s)"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Execute command when a relevant alert is received or we see a really long "
"fork (%s in cmd is replaced by message)"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Execute command when a wallet transaction changes (%s in cmd is replaced by "
"TxID)"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Execute command when the best block changes (%s in cmd is replaced by block "
"hash)"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Extra transactions to keep in memory for compact block reconstructions "
"(default: %u)"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Fees (in %s/kB) smaller than this are considered zero fee for relaying, "
"mining and transaction creation (default: %s)"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Fees (in %s/kB) smaller than this are considered zero fee for transaction "
"creation (default: %s)"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Force relay of transactions from whitelisted peers even if they violate "
"local relay policy (default: %d)"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"How thorough the block verification of -checkblocks is (0-4, default: %u)"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"If <category> is not supplied or if <category> = 1, output all debugging "
"information."),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"If paytxfee is not set, include enough fee so transactions begin "
"confirmation on average within n blocks (default: %u)"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"If this block is in the chain assume that it and its ancestors are valid and "
"potentially skip their script verification (0 to verify all, default: %s, "
"testnet: %s)"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay "
"fee of %s to prevent stuck transactions)"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Maintain a full transaction index, used by the getrawtransaction rpc call "
"(default: %u)"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Maximum allowed median peer time offset adjustment. Local perspective of "
"time may be influenced by peers forward or backward by this amount. "
"(default: %u seconds)"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Maximum size of data in data carrier transactions we relay and mine "
"(default: %u)"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Maximum total fees (in %s) to use in a single wallet transaction or raw "
"transaction; setting this too low may abort large transactions (default: %s)"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Number of seconds to keep misbehaving peers from reconnecting (default: %u)"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Output debugging information (default: %u, supplying <category> is optional)"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Please check that your computer's date and time are correct! If your clock "
"is wrong, %s will not work properly."),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Please contribute if you find %s useful. Visit %s for further information "
"about the software."),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Prune configured below the minimum of %d MiB. Please use a higher number."),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Prune: last wallet synchronisation goes beyond pruned data. You need to -"
"reindex (download the whole blockchain again in case of pruned node)"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Query for peer addresses via DNS lookup, if low on addresses (default: 1 "
"unless -connect/-noconnect)"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Randomize credentials for every proxy connection. This enables Tor stream "
"isolation (default: %u)"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Reduce storage requirements by enabling pruning (deleting) of old blocks. "
"This allows the pruneblockchain RPC to be called to delete specific blocks, "
"and enables automatic pruning of old blocks if a target size in MiB is "
"provided. This mode is incompatible with -txindex and -rescan. Warning: "
"Reverting this setting requires re-downloading the entire blockchain. "
"(default: 0 = disable pruning blocks, 1 = allow manual pruning via RPC, >%u "
"= automatically prune block files to stay under the specified target size in "
"MiB)"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Rescans are not possible in pruned mode. You will need to use -reindex which "
"will download the whole blockchain again."),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Set lowest fee rate (in %s/kB) for transactions to be included in block "
"creation. (default: %s)"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Set maximum size of high-priority/low-fee transactions in bytes (default: %d)"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Set the number of script verification threads (%u to %d, 0 = auto, <0 = "
"leave that many cores free, default: %d)"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Sets the serialization of raw transaction or block hex returned in non-"
"verbose mode, non-segwit(0) or segwit(1) (default: %d)"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Support filtering of blocks and transaction with bloom filters (default: %u)"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"The block database contains a block which appears to be from the future. "
"This may be due to your computer's date and time being set incorrectly. Only "
"rebuild the block database if you are sure that your computer's date and "
"time are correct"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"The transaction amount is too small to send after the fee has been deducted"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"This is a pre-release test build - use at your own risk - do not use for "
"mining or merchant applications"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"This is the transaction fee you may pay when fee estimates are not available."),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"This product includes software developed by the OpenSSL Project for use in "
"the OpenSSL Toolkit %s and cryptographic software written by Eric Young and "
"UPnP software written by Thomas Bernard."),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Total length of network version string (%i) exceeds maximum length (%i). "
"Reduce the number or size of uacomments."),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Tries to keep outbound traffic under the given target (in MiB per 24h), 0 = "
"no limit (default: %d)"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Unable to rewind the database to a pre-fork state. You will need to "
"redownload the blockchain"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Unsupported argument -socks found. Setting SOCKS version isn't possible "
"anymore, only SOCKS5 proxies are supported."),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Unsupported argument -whitelistalwaysrelay ignored, use -whitelistrelay and/"
"or -whitelistforcerelay."),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Use UPnP to map the listening port (default: 1 when listening and no -proxy)"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Use hierarchical deterministic key generation (HD) after BIP32. Only has "
"effect during wallet creation/first start"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: "
"%s)"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Username and hashed password for JSON-RPC connections. The field <userpw> "
"comes in the format: <USERNAME>:<SALT>$<HASH>. A canonical python script is "
"included in share/rpcuser. The client then connects normally using the "
"rpcuser=<USERNAME>/rpcpassword=<PASSWORD> pair of arguments. This option can "
"be specified multiple times"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Wallet will not create transactions that violate mempool chain limits "
"(default: %u)"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Warning: The network does not appear to fully agree! Some miners appear to "
"be experiencing issues."),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Warning: Unknown block versions being mined! It's possible unknown rules are "
"in effect"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Warning: Wallet file corrupt, data salvaged! Original %s saved as %s in %s; "
"if your balance or transactions are incorrect you should restore from a "
"backup."),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Warning: We do not appear to fully agree with our peers! You may need to "
"upgrade, or other nodes may need to upgrade."),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Whitelist peers connecting from the given IP address (e.g. 1.2.3.4) or CIDR "
"notated network (e.g. 1.2.3.0/24). Can be specified multiple times."),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"Whitelisted peers cannot be DoS banned and their transactions are always "
"relayed, even if they are already in the mempool, useful e.g. for a gateway"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"You need to rebuild the database using -reindex to go back to unpruned "
"mode. This will redownload the entire blockchain"),
QT_TRANSLATE_NOOP("oakcoin-core", ""
"You need to rebuild the database using -reindex-chainstate to change -txindex"),
QT_TRANSLATE_NOOP("oakcoin-core", "%s corrupt, salvage failed"),
QT_TRANSLATE_NOOP("oakcoin-core", "%s is set very high!"),
QT_TRANSLATE_NOOP("oakcoin-core", "(default: %s)"),
QT_TRANSLATE_NOOP("oakcoin-core", "(default: %u)"),
QT_TRANSLATE_NOOP("oakcoin-core", "-maxmempool must be at least %d MB"),
QT_TRANSLATE_NOOP("oakcoin-core", "<category> can be:"),
QT_TRANSLATE_NOOP("oakcoin-core", "Accept command line and JSON-RPC commands"),
QT_TRANSLATE_NOOP("oakcoin-core", "Accept public REST requests (default: %u)"),
QT_TRANSLATE_NOOP("oakcoin-core", "Add a node to connect to and attempt to keep the connection open"),
QT_TRANSLATE_NOOP("oakcoin-core", "Allow DNS lookups for -addnode, -seednode and -connect"),
QT_TRANSLATE_NOOP("oakcoin-core", "Always query for peer addresses via DNS lookup (default: %u)"),
QT_TRANSLATE_NOOP("oakcoin-core", "Append comment to the user agent string"),
QT_TRANSLATE_NOOP("oakcoin-core", "Attempt to recover private keys from a corrupt wallet on startup"),
QT_TRANSLATE_NOOP("oakcoin-core", "Automatically create Tor hidden service (default: %d)"),
QT_TRANSLATE_NOOP("oakcoin-core", "Block creation options:"),
QT_TRANSLATE_NOOP("oakcoin-core", "Cannot downgrade wallet"),
QT_TRANSLATE_NOOP("oakcoin-core", "Cannot resolve -%s address: '%s'"),
QT_TRANSLATE_NOOP("oakcoin-core", "Cannot write default address"),
QT_TRANSLATE_NOOP("oakcoin-core", "Chain selection options:"),
QT_TRANSLATE_NOOP("oakcoin-core", "Change index out of range"),
QT_TRANSLATE_NOOP("oakcoin-core", "Connect through SOCKS5 proxy"),
QT_TRANSLATE_NOOP("oakcoin-core", "Connect to a node to retrieve peer addresses, and disconnect"),
QT_TRANSLATE_NOOP("oakcoin-core", "Connection options:"),
QT_TRANSLATE_NOOP("oakcoin-core", "Copyright (C) %i-%i"),
QT_TRANSLATE_NOOP("oakcoin-core", "Corrupted block database detected"),
QT_TRANSLATE_NOOP("oakcoin-core", "Debugging/Testing options:"),
QT_TRANSLATE_NOOP("oakcoin-core", "Do not load the wallet and disable wallet RPC calls"),
QT_TRANSLATE_NOOP("oakcoin-core", "Do you want to rebuild the block database now?"),
QT_TRANSLATE_NOOP("oakcoin-core", "Done loading"),
QT_TRANSLATE_NOOP("oakcoin-core", "Enable publish hash block in <address>"),
QT_TRANSLATE_NOOP("oakcoin-core", "Enable publish hash transaction in <address>"),
QT_TRANSLATE_NOOP("oakcoin-core", "Enable publish raw block in <address>"),
QT_TRANSLATE_NOOP("oakcoin-core", "Enable publish raw transaction in <address>"),
QT_TRANSLATE_NOOP("oakcoin-core", "Enable transaction replacement in the memory pool (default: %u)"),
QT_TRANSLATE_NOOP("oakcoin-core", "Error initializing block database"),
QT_TRANSLATE_NOOP("oakcoin-core", "Error initializing wallet database environment %s!"),
QT_TRANSLATE_NOOP("oakcoin-core", "Error loading %s"),
QT_TRANSLATE_NOOP("oakcoin-core", "Error loading %s: Wallet corrupted"),
QT_TRANSLATE_NOOP("oakcoin-core", "Error loading %s: Wallet requires newer version of %s"),
QT_TRANSLATE_NOOP("oakcoin-core", "Error loading %s: You can't disable HD on a already existing HD wallet"),
QT_TRANSLATE_NOOP("oakcoin-core", "Error loading block database"),
QT_TRANSLATE_NOOP("oakcoin-core", "Error opening block database"),
QT_TRANSLATE_NOOP("oakcoin-core", "Error reading from database, shutting down."),
QT_TRANSLATE_NOOP("oakcoin-core", "Error"),
QT_TRANSLATE_NOOP("oakcoin-core", "Error: A fatal internal error occurred, see debug.log for details"),
QT_TRANSLATE_NOOP("oakcoin-core", "Error: Disk space is low!"),
QT_TRANSLATE_NOOP("oakcoin-core", "Failed to listen on any port. Use -listen=0 if you want this."),
QT_TRANSLATE_NOOP("oakcoin-core", "Fee (in %s/kB) to add to transactions you send (default: %s)"),
QT_TRANSLATE_NOOP("oakcoin-core", "How many blocks to check at startup (default: %u, 0 = all)"),
QT_TRANSLATE_NOOP("oakcoin-core", "Importing..."),
QT_TRANSLATE_NOOP("oakcoin-core", "Imports blocks from external blk000??.dat file on startup"),
QT_TRANSLATE_NOOP("oakcoin-core", "Include IP addresses in debug output (default: %u)"),
QT_TRANSLATE_NOOP("oakcoin-core", "Incorrect or no genesis block found. Wrong datadir for network?"),
QT_TRANSLATE_NOOP("oakcoin-core", "Information"),
QT_TRANSLATE_NOOP("oakcoin-core", "Initialization sanity check failed. %s is shutting down."),
QT_TRANSLATE_NOOP("oakcoin-core", "Insufficient funds"),
QT_TRANSLATE_NOOP("oakcoin-core", "Invalid -onion address: '%s'"),
QT_TRANSLATE_NOOP("oakcoin-core", "Invalid -proxy address: '%s'"),
QT_TRANSLATE_NOOP("oakcoin-core", "Invalid amount for -%s=<amount>: '%s'"),
QT_TRANSLATE_NOOP("oakcoin-core", "Invalid amount for -fallbackfee=<amount>: '%s'"),
QT_TRANSLATE_NOOP("oakcoin-core", "Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
QT_TRANSLATE_NOOP("oakcoin-core", "Invalid netmask specified in -whitelist: '%s'"),
QT_TRANSLATE_NOOP("oakcoin-core", "Keep at most <n> unconnectable transactions in memory (default: %u)"),
QT_TRANSLATE_NOOP("oakcoin-core", "Keep the transaction memory pool below <n> megabytes (default: %u)"),
QT_TRANSLATE_NOOP("oakcoin-core", "Keypool ran out, please call keypoolrefill first"),
QT_TRANSLATE_NOOP("oakcoin-core", "Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)"),
QT_TRANSLATE_NOOP("oakcoin-core", "Listen for connections on <port> (default: %u or testnet: %u)"),
QT_TRANSLATE_NOOP("oakcoin-core", "Loading addresses..."),
QT_TRANSLATE_NOOP("oakcoin-core", "Loading banlist..."),
QT_TRANSLATE_NOOP("oakcoin-core", "Loading block index..."),
QT_TRANSLATE_NOOP("oakcoin-core", "Loading wallet..."),
QT_TRANSLATE_NOOP("oakcoin-core", "Location of the auth cookie (default: data dir)"),
QT_TRANSLATE_NOOP("oakcoin-core", "Maintain at most <n> connections to peers (default: %u)"),
QT_TRANSLATE_NOOP("oakcoin-core", "Make the wallet broadcast transactions"),
QT_TRANSLATE_NOOP("oakcoin-core", "Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"),
QT_TRANSLATE_NOOP("oakcoin-core", "Maximum per-connection send buffer, <n>*1000 bytes (default: %u)"),
QT_TRANSLATE_NOOP("oakcoin-core", "Need to specify a port with -whitebind: '%s'"),
QT_TRANSLATE_NOOP("oakcoin-core", "Node relay options:"),
QT_TRANSLATE_NOOP("oakcoin-core", "Not enough file descriptors available."),
QT_TRANSLATE_NOOP("oakcoin-core", "Only connect to nodes in network <net> (ipv4, ipv6 or onion)"),
QT_TRANSLATE_NOOP("oakcoin-core", "Options:"),
QT_TRANSLATE_NOOP("oakcoin-core", "Password for JSON-RPC connections"),
QT_TRANSLATE_NOOP("oakcoin-core", "Prepend debug output with timestamp (default: %u)"),
QT_TRANSLATE_NOOP("oakcoin-core", "Print this help message and exit"),
QT_TRANSLATE_NOOP("oakcoin-core", "Print version and exit"),
QT_TRANSLATE_NOOP("oakcoin-core", "Prune cannot be configured with a negative value."),
QT_TRANSLATE_NOOP("oakcoin-core", "Prune mode is incompatible with -txindex."),
QT_TRANSLATE_NOOP("oakcoin-core", "Pruning blockstore..."),
QT_TRANSLATE_NOOP("oakcoin-core", "RPC server options:"),
QT_TRANSLATE_NOOP("oakcoin-core", "Rebuild chain state and block index from the blk*.dat files on disk"),
QT_TRANSLATE_NOOP("oakcoin-core", "Rebuild chain state from the currently indexed blocks"),
QT_TRANSLATE_NOOP("oakcoin-core", "Reducing -maxconnections from %d to %d, because of system limitations."),
QT_TRANSLATE_NOOP("oakcoin-core", "Relay and mine data carrier transactions (default: %u)"),
QT_TRANSLATE_NOOP("oakcoin-core", "Relay non-P2SH multisig (default: %u)"),
QT_TRANSLATE_NOOP("oakcoin-core", "Rescan the block chain for missing wallet transactions on startup"),
QT_TRANSLATE_NOOP("oakcoin-core", "Rescanning..."),
QT_TRANSLATE_NOOP("oakcoin-core", "Rewinding blocks..."),
QT_TRANSLATE_NOOP("oakcoin-core", "Run in the background as a daemon and accept commands"),
QT_TRANSLATE_NOOP("oakcoin-core", "Send trace/debug info to console instead of debug.log file"),
QT_TRANSLATE_NOOP("oakcoin-core", "Send transactions as zero-fee transactions if possible (default: %u)"),
QT_TRANSLATE_NOOP("oakcoin-core", "Send transactions with full-RBF opt-in enabled (default: %u)"),
QT_TRANSLATE_NOOP("oakcoin-core", "Set database cache size in megabytes (%d to %d, default: %d)"),
QT_TRANSLATE_NOOP("oakcoin-core", "Set key pool size to <n> (default: %u)"),
QT_TRANSLATE_NOOP("oakcoin-core", "Set maximum BIP141 block weight (default: %d)"),
QT_TRANSLATE_NOOP("oakcoin-core", "Set maximum block size in bytes (default: %d)"),
QT_TRANSLATE_NOOP("oakcoin-core", "Set the number of threads to service RPC calls (default: %d)"),
QT_TRANSLATE_NOOP("oakcoin-core", "Show all debugging options (usage: --help -help-debug)"),
QT_TRANSLATE_NOOP("oakcoin-core", "Shrink debug.log file on client startup (default: 1 when no -debug)"),
QT_TRANSLATE_NOOP("oakcoin-core", "Signing transaction failed"),
QT_TRANSLATE_NOOP("oakcoin-core", "Specify configuration file (default: %s)"),
QT_TRANSLATE_NOOP("oakcoin-core", "Specify connection timeout in milliseconds (minimum: 1, default: %d)"),
QT_TRANSLATE_NOOP("oakcoin-core", "Specify data directory"),
QT_TRANSLATE_NOOP("oakcoin-core", "Specify pid file (default: %s)"),
QT_TRANSLATE_NOOP("oakcoin-core", "Specify wallet file (within data directory)"),
QT_TRANSLATE_NOOP("oakcoin-core", "Specify your own public address"),
QT_TRANSLATE_NOOP("oakcoin-core", "Spend unconfirmed change when sending transactions (default: %u)"),
QT_TRANSLATE_NOOP("oakcoin-core", "Starting network threads..."),
QT_TRANSLATE_NOOP("oakcoin-core", "The source code is available from %s."),
QT_TRANSLATE_NOOP("oakcoin-core", "The transaction amount is too small to pay the fee"),
QT_TRANSLATE_NOOP("oakcoin-core", "The wallet will avoid paying less than the minimum relay fee."),
QT_TRANSLATE_NOOP("oakcoin-core", "This is experimental software."),
QT_TRANSLATE_NOOP("oakcoin-core", "This is the minimum transaction fee you pay on every transaction."),
QT_TRANSLATE_NOOP("oakcoin-core", "This is the transaction fee you will pay if you send a transaction."),
QT_TRANSLATE_NOOP("oakcoin-core", "Threshold for disconnecting misbehaving peers (default: %u)"),
QT_TRANSLATE_NOOP("oakcoin-core", "Tor control port password (default: empty)"),
QT_TRANSLATE_NOOP("oakcoin-core", "Tor control port to use if onion listening enabled (default: %s)"),
QT_TRANSLATE_NOOP("oakcoin-core", "Transaction amount too small"),
QT_TRANSLATE_NOOP("oakcoin-core", "Transaction amounts must not be negative"),
QT_TRANSLATE_NOOP("oakcoin-core", "Transaction has too long of a mempool chain"),
QT_TRANSLATE_NOOP("oakcoin-core", "Transaction must have at least one recipient"),
QT_TRANSLATE_NOOP("oakcoin-core", "Transaction too large for fee policy"),
QT_TRANSLATE_NOOP("oakcoin-core", "Transaction too large"),
QT_TRANSLATE_NOOP("oakcoin-core", "Unable to bind to %s on this computer (bind returned error %s)"),
QT_TRANSLATE_NOOP("oakcoin-core", "Unable to bind to %s on this computer. %s is probably already running."),
QT_TRANSLATE_NOOP("oakcoin-core", "Unable to start HTTP server. See debug log for details."),
QT_TRANSLATE_NOOP("oakcoin-core", "Unknown network specified in -onlynet: '%s'"),
QT_TRANSLATE_NOOP("oakcoin-core", "Unsupported argument -benchmark ignored, use -debug=bench."),
QT_TRANSLATE_NOOP("oakcoin-core", "Unsupported argument -debugnet ignored, use -debug=net."),
QT_TRANSLATE_NOOP("oakcoin-core", "Unsupported argument -tor found, use -onion."),
QT_TRANSLATE_NOOP("oakcoin-core", "Upgrade wallet to latest format on startup"),
QT_TRANSLATE_NOOP("oakcoin-core", "Use UPnP to map the listening port (default: %u)"),
QT_TRANSLATE_NOOP("oakcoin-core", "Use the test chain"),
QT_TRANSLATE_NOOP("oakcoin-core", "User Agent comment (%s) contains unsafe characters."),
QT_TRANSLATE_NOOP("oakcoin-core", "Username for JSON-RPC connections"),
QT_TRANSLATE_NOOP("oakcoin-core", "Verifying blocks..."),
QT_TRANSLATE_NOOP("oakcoin-core", "Verifying wallet..."),
QT_TRANSLATE_NOOP("oakcoin-core", "Wallet %s resides outside data directory %s"),
QT_TRANSLATE_NOOP("oakcoin-core", "Wallet debugging/testing options:"),
QT_TRANSLATE_NOOP("oakcoin-core", "Wallet needed to be rewritten: restart %s to complete"),
QT_TRANSLATE_NOOP("oakcoin-core", "Wallet options:"),
QT_TRANSLATE_NOOP("oakcoin-core", "Warning"),
QT_TRANSLATE_NOOP("oakcoin-core", "Warning: unknown new rules activated (versionbit %i)"),
QT_TRANSLATE_NOOP("oakcoin-core", "Whether to operate in a blocks only mode (default: %u)"),
QT_TRANSLATE_NOOP("oakcoin-core", "Zapping all transactions from wallet..."),
QT_TRANSLATE_NOOP("oakcoin-core", "ZeroMQ notification options:"),
};
| mit |
jbehuet/blog-app | public/js/components/blog/blog.md.js | 1134 | /*
Create Angular module app.blog and define all states
blog : parent state, is an abstrat state too with templateUrl
blog.list : nested state of state app.blog, display blog-list component
blog.item : nested state of state app.blog, display blog-item component with editable attribute value is true
*/
((app) => {
'use strict'
app.config(['$stateProvider', ($stateProvider, $urlRouterProvider, $locationProvider) => {
/*
Define a state with name 'blog' this state is abstract and url is empty (root of application)
template is ui-view it's used to display nested views
*/
$stateProvider
.state('blog', {
url: '/posts',
abstract: true,
templateUrl: 'js/components/blog/blog.html'
})
.state('blog.list', {
url: '/',
template: '<blog-list></blog-list>'
})
.state('blog.item', {
url: '/:id',
template: '<blog-item editable="true"></blog-item>'
})
}])
})(require('angular').module('app.blog', []))
| mit |
AlexandreProenca/angular-arch | app/modules/components/controllers/FileUploadController.js | 3709 | 'use strict';
define([
], function () {
var FileUploadController = function (BORAYU, $filter, $scope , $http , AuthService , Error , src , types , uri, sizeH , sizeW, ratio, $modalInstance) {
console.log('sizes' , sizeW , sizeH);
$scope.sizeH = sizeH;
$scope.sizeW = sizeW;
$scope.ratio = ratio;
var baseUrl = BORAYU.API_URL + ':' + BORAYU.API_PORT;
$scope.config = {target: '/upload/'};
$scope.crop_view = true;
$scope.upload_view = false;
$scope.originalImage = undefined;
$scope.$on("cropme:done", function(ev, result, canvasEl) {
$scope.originalImage = result.originalImage;
$scope.imageName = result.filename.replace(/ /g,'');
console.log($scope.imageName);
$scope.blobToBase64(result.croppedImage);
$scope.crop_view = false;
});
$scope.backToCrop = function(){
// $scope.croppedImage = undefined;
$scope.upload_view = false;
$scope.crop_view = true;
};
$scope.blobToBase64 = function(blob){
var reader = new window.FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function() {
console.log(reader.result);
$scope.$apply(function () {
$scope.croppedImage = reader.result;
$scope.upload_view = true;
});
};
};
$scope.upload = function(){
$scope.imageName = $filter('date')(new Date(), 'yyyyMMddhhmmss') + $scope.imageName;
$http.post( baseUrl + "/upload/" , {
filename:$scope.imageName,
remote_path:uri,
image:$scope.croppedImage.split(",")[1]
} , AuthService.getHttpOptions()).success(function(data){
$modalInstance.close(data.link);
$scope.status = "Imagem enviada";
$scope.finalImageUri = data.link;
$scope.sending = false;
});
};
// $scope.initialize();
$scope.initialize = function () {
if(typeof src !== "undefined" && src !== ""){
$scope.finalImageUri = src;
$scope.preview = true;
$scope.sending = false;
}
$scope.imageName = undefined;
$scope.base64Image = undefined;
};
$scope.validateImage = function(type){
var _typesArray = types.split(";");
var valid = false;
_.forEach(_typesArray , function(t){
if(type.split("/")[1] === t){
valid = true;
}
});
return valid;
};
$scope.makeTypesString = function(){
var _typesArray = types.split(";");
var text = "";
_.forEach(_typesArray , function(t , i){
if(i === 0){
text += " ";
}
else if(i < (_typesArray.length - 1)){
text += ", ";
}
else{
text += " e ";
}
text += " " + t;
});
return text;
};
$scope.processFiles = function($files){
if($scope.validateImage($files[0].file.type)){
$scope.imageName = $files[0].file.name;
var fileReader = new FileReader();
fileReader.onload = function (event) {
var uri = event.target.result;
$scope.base64Image = uri;
$scope.upload(uri.split(",")[1]);
$scope.preview = true;
$scope.sending = true;
$scope.status = "Enviado...";
};
fileReader.readAsDataURL($files[0].file);
}
else {
Error.msg({}, undefined, "só serão aceitos imagens, do tipo " + $scope.makeTypesString() + ".");
}
};
};
return ['BORAYU', '$filter', '$scope', '$http' , 'AuthService' , 'Error' , 'src' , 'types' , 'uri' , 'sizeH' , 'sizeW' , 'ratio' , '$modalInstance', FileUploadController];
});
| mit |
Bokeefe/EquisiteWarps-Beta | src/Playlist.js | 21786 | import _defaults from 'lodash.defaults';
import h from 'virtual-dom/h';
import diff from 'virtual-dom/diff';
import patch from 'virtual-dom/patch';
import InlineWorker from 'inline-worker';
import { pixelsToSeconds } from './utils/conversions';
import LoaderFactory from './track/loader/LoaderFactory';
import ScrollHook from './render/ScrollHook';
import TimeScale from './TimeScale';
import Track from './Track';
import Playout from './Playout';
import AnnotationList from './annotation/AnnotationList';
import RecorderWorkerFunction from './utils/recorderWorker';
import ExportWavWorkerFunction from './utils/exportWavWorker';
export default class {
constructor() {
this.tracks = [];
this.soloedTracks = [];
this.mutedTracks = [];
this.playoutPromises = [];
this.cursor = 0;
this.playbackSeconds = 0;
this.duration = 0;
this.scrollLeft = 0;
this.scrollTimer = undefined;
this.showTimescale = false;
// whether a user is scrolling the waveform
this.isScrolling = false;
this.fadeType = 'logarithmic';
this.masterGain = 1;
this.annotations = [];
this.durationFormat = 'hh:mm:ss.uuu';
this.isAutomaticScroll = false;
this.resetDrawTimer = undefined;
}
// TODO extract into a plugin
initExporter() {
this.exportWorker = new InlineWorker(ExportWavWorkerFunction);
}
// TODO extract into a plugin
initRecorder(stream) {
this.mediaRecorder = new window.MediaRecorder(stream);
this.mediaRecorder.onstart = () => {
const track = new Track();
track.setName('Recording');
track.setEnabledStates();
track.setEventEmitter(this.ee);
this.recordingTrack = track;
this.tracks.push(track);
this.chunks = [];
};
this.mediaRecorder.ondataavailable = (e) => {
this.chunks.push(e.data);
const recording = new Blob(this.chunks, { type: 'audio/ogg; codecs=opus' });
const loader = LoaderFactory.createLoader(recording, this.ac);
loader.load().then((audioBuffer) => {
// ask web worker for peaks.
this.recorderWorker.postMessage({
samples: audioBuffer.getChannelData(0),
samplesPerPixel: this.samplesPerPixel,
});
this.recordingTrack.setCues(0, audioBuffer.duration);
this.recordingTrack.setBuffer(audioBuffer);
this.recordingTrack.setPlayout(new Playout(this.ac, audioBuffer));
this.adjustDuration();
});
};
this.recorderWorker = new InlineWorker(RecorderWorkerFunction);
// use a worker for calculating recording peaks.
this.recorderWorker.onmessage = (e) => {
this.recordingTrack.setPeaks(e.data);
this.drawRequest();
};
this.recorderWorker.onerror = (e) => {
throw e;
};
}
setShowTimeScale(show) {
this.showTimescale = show;
}
setMono(mono) {
this.mono = mono;
}
setExclSolo(exclSolo) {
this.exclSolo = exclSolo;
}
setSeekStyle(style) {
this.seekStyle = style;
}
getSeekStyle() {
return this.seekStyle;
}
setSampleRate(sampleRate) {
this.sampleRate = sampleRate;
}
setSamplesPerPixel(samplesPerPixel) {
this.samplesPerPixel = samplesPerPixel;
}
setAudioContext(ac) {
this.ac = ac;
}
setControlOptions(controlOptions) {
this.controls = controlOptions;
}
setWaveHeight(height) {
this.waveHeight = height;
}
setColors(colors) {
this.colors = colors;
}
setAnnotations(annotations) {
this.annotationList = new AnnotationList(this, annotations);
}
setEventEmitter(ee) {
this.ee = ee;
}
getEventEmitter() {
return this.ee;
}
setUpEventEmitter() {
const ee = this.ee;
ee.on('automaticscroll', (val) => {
this.isAutomaticScroll = val;
});
ee.on('durationformat', (format) => {
this.durationFormat = format;
this.drawRequest();
});
ee.on('select', (start, end, track) => {
if (this.isPlaying()) {
this.lastSeeked = start;
this.pausedAt = undefined;
this.restartPlayFrom(start);
} else {
// reset if it was paused.
this.seek(start, end, track);
this.ee.emit('timeupdate', start);
this.drawRequest();
}
});
ee.on('startaudiorendering', (type) => {
this.startOfflineRender(type);
});
ee.on('statechange', (state) => {
this.setState(state);
this.drawRequest();
});
ee.on('shift', (deltaTime, track) => {
track.setStartTime(track.getStartTime() + deltaTime);
this.adjustDuration();
this.drawRequest();
});
ee.on('record', () => {
this.record();
});
ee.on('play', (start, end) => {
this.play(start, end);
});
ee.on('pause', () => {
this.pause();
});
ee.on('stop', () => {
this.stop();
});
ee.on('rewind', () => {
this.rewind();
});
ee.on('fastforward', () => {
this.fastForward();
});
ee.on('clear', () => {
this.clear().then(() => {
this.drawRequest();
});
});
ee.on('solo', (track) => {
this.soloTrack(track);
this.adjustTrackPlayout();
this.drawRequest();
});
ee.on('mute', (track) => {
this.muteTrack(track);
this.adjustTrackPlayout();
this.drawRequest();
});
ee.on('volumechange', (volume, track) => {
track.setGainLevel(volume / 100);
});
ee.on('mastervolumechange', (volume) => {
this.masterGain = volume / 100;
this.tracks.forEach((track) => {
track.setMasterGainLevel(this.masterGain);
});
});
ee.on('fadein', (duration, track) => {
track.setFadeIn(duration, this.fadeType);
this.drawRequest();
});
ee.on('fadeout', (duration, track) => {
track.setFadeOut(duration, this.fadeType);
this.drawRequest();
});
ee.on('fadetype', (type) => {
this.fadeType = type;
});
ee.on('newtrack', (file) => {
this.load([{
src: file,
name: file.name,
}]);
});
ee.on('trim', () => {
const track = this.getActiveTrack();
const timeSelection = this.getTimeSelection();
track.trim(timeSelection.start, timeSelection.end);
track.calculatePeaks(this.samplesPerPixel, this.sampleRate);
this.setTimeSelection(0, 0);
this.drawRequest();
});
ee.on('zoomin', () => {
const zoomIndex = Math.max(0, this.zoomIndex - 1);
const zoom = this.zoomLevels[zoomIndex];
if (zoom !== this.samplesPerPixel) {
this.setZoom(zoom);
this.drawRequest();
}
});
ee.on('zoomout', () => {
const zoomIndex = Math.min(this.zoomLevels.length - 1, this.zoomIndex + 1);
const zoom = this.zoomLevels[zoomIndex];
if (zoom !== this.samplesPerPixel) {
this.setZoom(zoom);
this.drawRequest();
}
});
ee.on('scroll', () => {
this.isScrolling = true;
this.drawRequest();
clearTimeout(this.scrollTimer);
this.scrollTimer = setTimeout(() => {
this.isScrolling = false;
}, 200);
});
}
load(trackList) {
const loadPromises = trackList.map((trackInfo) => {
const loader = LoaderFactory.createLoader(trackInfo.src, this.ac, this.ee);
return loader.load();
});
return Promise.all(loadPromises).then((audioBuffers) => {
this.ee.emit('audiosourcesloaded');
const tracks = audioBuffers.map((audioBuffer, index) => {
const info = trackList[index];
const name = info.name || 'Untitled';
const start = info.start || 0;
const states = info.states || {};
const fadeIn = info.fadeIn;
const fadeOut = info.fadeOut;
const cueIn = info.cuein || 0;
const cueOut = info.cueout || audioBuffer.duration;
const gain = info.gain || 1;
const muted = info.muted || false;
const soloed = info.soloed || false;
const selection = info.selected;
const peaks = info.peaks || { type: 'WebAudio', mono: this.mono };
const customClass = info.customClass || undefined;
const waveOutlineColor = info.waveOutlineColor || undefined;
// webaudio specific playout for now.
const playout = new Playout(this.ac, audioBuffer);
const track = new Track();
track.src = info.src;
track.setBuffer(audioBuffer);
track.setName(name);
track.setEventEmitter(this.ee);
track.setEnabledStates(states);
track.setCues(cueIn, cueOut);
track.setCustomClass(customClass);
track.setWaveOutlineColor(waveOutlineColor);
if (fadeIn !== undefined) {
track.setFadeIn(fadeIn.duration, fadeIn.shape);
}
if (fadeOut !== undefined) {
track.setFadeOut(fadeOut.duration, fadeOut.shape);
}
if (selection !== undefined) {
this.setActiveTrack(track);
this.setTimeSelection(selection.start, selection.end);
}
if (peaks !== undefined) {
track.setPeakData(peaks);
}
track.setState(this.getState());
track.setStartTime(start);
track.setPlayout(playout);
track.setGainLevel(gain);
if (muted) {
this.muteTrack(track);
}
if (soloed) {
this.soloTrack(track);
}
// extract peaks with AudioContext for now.
track.calculatePeaks(this.samplesPerPixel, this.sampleRate);
return track;
});
this.tracks = this.tracks.concat(tracks);
this.adjustDuration();
this.draw(this.render());
this.ee.emit('audiosourcesrendered');
});
}
/*
track instance of Track.
*/
setActiveTrack(track) {
this.activeTrack = track;
}
getActiveTrack() {
return this.activeTrack;
}
isSegmentSelection() {
return this.timeSelection.start !== this.timeSelection.end;
}
/*
start, end in seconds.
*/
setTimeSelection(start = 0, end) {
this.timeSelection = {
start,
end: (end === undefined) ? start : end,
};
this.cursor = start;
}
startOfflineRender(type) {
if (this.isRendering) {
return;
}
this.isRendering = true;
this.offlineAudioContext = new OfflineAudioContext(2, 44100 * this.duration, 44100);
const currentTime = this.offlineAudioContext.currentTime;
this.tracks.forEach((track) => {
track.setOfflinePlayout(new Playout(this.offlineAudioContext, track.buffer));
track.schedulePlay(currentTime, 0, 0, {
shouldPlay: this.shouldTrackPlay(track),
masterGain: 1,
isOffline: true,
});
});
/*
TODO cleanup of different audio playouts handling.
*/
this.offlineAudioContext.startRendering().then((audioBuffer) => {
if (type === 'buffer') {
this.ee.emit('audiorenderingfinished', type, audioBuffer);
this.isRendering = false;
return;
}
if (type === 'wav') {
this.exportWorker.postMessage({
command: 'init',
config: {
sampleRate: 44100,
},
});
// callback for `exportWAV`
this.exportWorker.onmessage = (e) => {
this.ee.emit('audiorenderingfinished', type, e.data);
this.isRendering = false;
// clear out the buffer for next renderings.
this.exportWorker.postMessage({
command: 'clear',
});
};
// send the channel data from our buffer to the worker
this.exportWorker.postMessage({
command: 'record',
buffer: [
audioBuffer.getChannelData(0),
audioBuffer.getChannelData(1),
],
});
// ask the worker for a WAV
this.exportWorker.postMessage({
command: 'exportWAV',
type: 'audio/wav',
});
}
}).catch((e) => {
throw e;
});
}
getTimeSelection() {
return this.timeSelection;
}
setState(state) {
this.state = state;
this.tracks.forEach((track) => {
track.setState(state);
});
}
getState() {
return this.state;
}
setZoomIndex(index) {
this.zoomIndex = index;
}
setZoomLevels(levels) {
this.zoomLevels = levels;
}
setZoom(zoom) {
this.samplesPerPixel = zoom;
this.zoomIndex = this.zoomLevels.indexOf(zoom);
this.tracks.forEach((track) => {
track.calculatePeaks(zoom, this.sampleRate);
});
}
muteTrack(track) {
const index = this.mutedTracks.indexOf(track);
if (index > -1) {
this.mutedTracks.splice(index, 1);
} else {
this.mutedTracks.push(track);
}
}
soloTrack(track) {
const index = this.soloedTracks.indexOf(track);
if (index > -1) {
this.soloedTracks.splice(index, 1);
} else if (this.exclSolo) {
this.soloedTracks = [track];
} else {
this.soloedTracks.push(track);
}
}
adjustTrackPlayout() {
this.tracks.forEach((track) => {
track.setShouldPlay(this.shouldTrackPlay(track));
});
}
adjustDuration() {
this.duration = this.tracks.reduce(
(duration, track) => Math.max(duration, track.getEndTime()),
0,
);
}
shouldTrackPlay(track) {
let shouldPlay;
// if there are solo tracks, only they should play.
if (this.soloedTracks.length > 0) {
shouldPlay = false;
if (this.soloedTracks.indexOf(track) > -1) {
shouldPlay = true;
}
} else {
// play all tracks except any muted tracks.
shouldPlay = true;
if (this.mutedTracks.indexOf(track) > -1) {
shouldPlay = false;
}
}
return shouldPlay;
}
isPlaying() {
return this.tracks.reduce(
(isPlaying, track) => isPlaying || track.isPlaying(),
false,
);
}
/*
* returns the current point of time in the playlist in seconds.
*/
getCurrentTime() {
const cursorPos = this.lastSeeked || this.pausedAt || this.cursor;
return cursorPos + this.getElapsedTime();
}
getElapsedTime() {
return this.ac.currentTime - this.lastPlay;
}
setMasterGain(gain) {
this.ee.emit('mastervolumechange', gain);
}
restartPlayFrom(start, end) {
this.stopAnimation();
this.tracks.forEach((editor) => {
editor.scheduleStop();
});
return Promise.all(this.playoutPromises).then(this.play.bind(this, start, end));
}
play(startTime, endTime) {
clearTimeout(this.resetDrawTimer);
const currentTime = this.ac.currentTime;
const selected = this.getTimeSelection();
const playoutPromises = [];
const start = startTime || this.pausedAt || this.cursor;
let end = endTime;
if (!end && selected.end !== selected.start && selected.end > start) {
end = selected.end;
}
if (this.isPlaying()) {
return this.restartPlayFrom(start, end);
}
this.tracks.forEach((track) => {
track.setState('cursor');
playoutPromises.push(track.schedulePlay(currentTime, start, end, {
shouldPlay: this.shouldTrackPlay(track),
masterGain: this.masterGain,
}));
});
this.lastPlay = currentTime;
// use these to track when the playlist has fully stopped.
this.playoutPromises = playoutPromises;
this.startAnimation(start);
return Promise.all(this.playoutPromises);
}
pause() {
if (!this.isPlaying()) {
return Promise.all(this.playoutPromises);
}
this.pausedAt = this.getCurrentTime();
return this.playbackReset();
}
stop() {
if (this.mediaRecorder && this.mediaRecorder.state === 'recording') {
this.mediaRecorder.stop();
}
this.pausedAt = undefined;
this.playbackSeconds = 0;
return this.playbackReset();
}
playbackReset() {
this.lastSeeked = undefined;
this.stopAnimation();
this.tracks.forEach((track) => {
track.scheduleStop();
track.setState(this.getState());
});
this.drawRequest();
return Promise.all(this.playoutPromises);
}
rewind() {
return this.stop().then(() => {
this.scrollLeft = 0;
this.ee.emit('select', 0, 0);
});
}
fastForward() {
return this.stop().then(() => {
if (this.viewDuration < this.duration) {
this.scrollLeft = this.duration - this.viewDuration;
} else {
this.scrollLeft = 0;
}
this.ee.emit('select', this.duration, this.duration);
});
}
clear() {
return this.stop().then(() => {
this.tracks = [];
this.soloedTracks = [];
this.mutedTracks = [];
this.playoutPromises = [];
this.cursor = 0;
this.playbackSeconds = 0;
this.duration = 0;
this.scrollLeft = 0;
this.seek(0, 0, undefined);
});
}
record() {
const playoutPromises = [];
this.mediaRecorder.start(300);
this.tracks.forEach((track) => {
track.setState('none');
playoutPromises.push(track.schedulePlay(this.ac.currentTime, 0, undefined, {
shouldPlay: this.shouldTrackPlay(track),
}));
});
this.playoutPromises = playoutPromises;
}
startAnimation(startTime) {
this.lastDraw = this.ac.currentTime;
this.animationRequest = window.requestAnimationFrame(() => {
this.updateEditor(startTime);
});
}
stopAnimation() {
window.cancelAnimationFrame(this.animationRequest);
this.lastDraw = undefined;
}
seek(start, end, track) {
if (this.isPlaying()) {
this.lastSeeked = start;
this.pausedAt = undefined;
this.restartPlayFrom(start);
} else {
// reset if it was paused.
this.setActiveTrack(track || this.tracks[0]);
this.pausedAt = start;
this.setTimeSelection(start, end);
if (this.getSeekStyle() === 'fill') {
this.playbackSeconds = start;
}
}
}
/*
* Animation function for the playlist.
* Keep under 16.7 milliseconds based on a typical screen refresh rate of 60fps.
*/
updateEditor(cursor) {
const currentTime = this.ac.currentTime;
const selection = this.getTimeSelection();
const cursorPos = cursor || this.cursor;
const elapsed = currentTime - this.lastDraw;
if (this.isPlaying()) {
const playbackSeconds = cursorPos + elapsed;
this.ee.emit('timeupdate', playbackSeconds);
this.animationRequest = window.requestAnimationFrame(() => {
this.updateEditor(playbackSeconds);
});
this.playbackSeconds = playbackSeconds;
this.draw(this.render());
this.lastDraw = currentTime;
} else {
if ((cursorPos + elapsed) >=
(this.isSegmentSelection()) ? selection.end : this.duration) {
this.ee.emit('finished');
}
this.stopAnimation();
this.resetDrawTimer = setTimeout(() => {
this.pausedAt = undefined;
this.lastSeeked = undefined;
this.setState(this.getState());
this.playbackSeconds = 0;
this.draw(this.render());
}, 0);
}
}
drawRequest() {
window.requestAnimationFrame(() => {
this.draw(this.render());
});
}
draw(newTree) {
const patches = diff(this.tree, newTree);
this.rootNode = patch(this.rootNode, patches);
this.tree = newTree;
// use for fast forwarding.
this.viewDuration = pixelsToSeconds(
this.rootNode.clientWidth - this.controls.width,
this.samplesPerPixel,
this.sampleRate,
);
}
getTrackRenderData(data = {}) {
const defaults = {
height: this.waveHeight,
resolution: this.samplesPerPixel,
sampleRate: this.sampleRate,
controls: this.controls,
isActive: false,
timeSelection: this.getTimeSelection(),
playlistLength: this.duration,
playbackSeconds: this.playbackSeconds,
colors: this.colors,
};
return _defaults(data, defaults);
}
isActiveTrack(track) {
const activeTrack = this.getActiveTrack();
if (this.isSegmentSelection()) {
return activeTrack === track;
}
return true;
}
renderAnnotations() {
return this.annotationList.render();
}
renderTimeScale() {
const controlWidth = this.controls.show ? this.controls.width : 0;
const timeScale = new TimeScale(this.duration, this.scrollLeft,
this.samplesPerPixel, this.sampleRate, controlWidth);
return timeScale.render();
}
renderTrackSection() {
const trackElements = this.tracks.map(track =>
track.render(this.getTrackRenderData({
isActive: this.isActiveTrack(track),
shouldPlay: this.shouldTrackPlay(track),
soloed: this.soloedTracks.indexOf(track) > -1,
muted: this.mutedTracks.indexOf(track) > -1,
})),
);
return h('div.playlist-tracks',
{
attributes: {
style: 'overflow: auto;',
},
onscroll: (e) => {
this.scrollLeft = pixelsToSeconds(
e.target.scrollLeft,
this.samplesPerPixel,
this.sampleRate,
);
this.ee.emit('scroll', this.scrollLeft);
},
hook: new ScrollHook(this),
},
trackElements,
);
}
render() {
const containerChildren = [];
if (this.showTimescale) {
containerChildren.push(this.renderTimeScale());
}
containerChildren.push(this.renderTrackSection());
if (this.annotationList.length) {
containerChildren.push(this.renderAnnotations());
}
return h('div.playlist',
{
attributes: {
style: 'overflow: hidden; position: relative;',
},
},
containerChildren,
);
}
getInfo() {
const info = [];
this.tracks.forEach((track) => {
info.push(track.getTrackDetails());
});
return info;
}
}
| mit |
KingYSoft/foretch | angular/src/app/home/home-test1.component.ts | 407 | import { Component, Injector, AfterViewInit, Inject } from '@angular/core';
import { Router } from '@angular/router';
import { Helpers } from 'shared/helpers/Helpers';
import { AppComponentBase } from 'shared/app-component-base';
@Component({
template: '<p>test1</p>'
})
export class HomeTest1Component extends AppComponentBase {
constructor(injector: Injector) {
super(injector);
}
}
| mit |
daviferreira/leticiastallone.com | leticiastallone/publications/views.py | 333 | # coding: utf-8
from django.views.generic.detail import DetailView
from .models import Article
class ArticleDetailView(DetailView):
model = Article
context_object_name = 'article'
def get_context_data(self, **kwargs):
context = super(ArticleDetailView, self).get_context_data(**kwargs)
return context
| mit |
dcarrasco/inv-fija | public/js/view_stock_datos.js | 1561 | var plot,
jq_grafico = function(div_id, datos, x_label, y_label, series_label, title) {
return $.jqplot(div_id, datos, {
title: title,
animate: true,
animateReplot: true,
stackSeries: true,
captureRightClick: true,
seriesDefaults:{
renderer:$.jqplot.BarRenderer,
rendererOptions: {
highlightMouseOver: true,
animation: {
speed: 300
}
},
pointLabels: {show: true}
},
series: series_label,
axes: {
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
ticks: x_label
},
yaxis: {
padMin: 0,
min: 0,
tickOptions: {formatString: "%'i"},
label: y_label,
labelRenderer: $.jqplot.CanvasAxisLabelRenderer
}
},
legend: {
show: true,
location: 's',
placement: 'outsideGrid'
}
});
},
render_grafico = function(data_grafico, tipo, datos) {
var data,
str_tipo = '',
str_dato = '',
str_ejey = '';
str_dato = (datos == 'monto') ? 'Valor (MM$)' : 'Cantidad';
if (tipo == 'simcard')
{
str_tipo = 'Simcard';
data = (datos == 'monto') ? data_grafico.v_simcard : data_grafico.q_simcard;
}
else if (tipo == 'otros')
{
str_tipo = 'Otros';
data = (datos == 'monto') ? data_grafico.v_otros : data_grafico.q_otros;
}
else
{
str_tipo = 'Equipos';
data = (datos == 'monto') ? data_grafico.v_equipos : data_grafico.q_equipos;
}
if (plot !== undefined) plot.destroy();
plot = jq_grafico('chart', data, data_grafico.x_label, str_dato, data_grafico.series_label, str_dato + ' ' + str_tipo);
};
| mit |
Creedzy/MotionLayer | src/main/java/org/cg/service/DAOS/NotificationDAO.java | 1966 | package org.cg.service.DAOS;
import java.util.List;
import org.cg.Model.Message;
import org.cg.Model.User;
import org.cg.service.Exception.DataAccessLayerException;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.springframework.stereotype.Service;
import org.cg.Model.*;
@Service
public class NotificationDAO extends ServiceDAO{
public NotificationDAO() {
super();
}
/**
* Insert a new message into the database.
* @param event
*/
public void create(Notification message) throws DataAccessLayerException {
super.saveOrUpdate(message);
}
/**
* Delete a detached message from the database.
* @param event
*/
public void delete(Notification message) throws DataAccessLayerException {
super.delete(message);
}
/**
* Find an message by its primary key.
* @param id
* @return
*/
public Notification find(Long id) throws DataAccessLayerException {
return (Notification) super.find(Notification.class, id);
}
/**
* Updates the state of a detached message.
*
* @param event
*/
public void update(Notification message) throws DataAccessLayerException {
super.saveOrUpdate(message);
}
/**
* Finds all users in the database.
* @return
*/
public List findAll() throws DataAccessLayerException{
return super.findAll(Notification.class);
}
public List findMessagesForUser(String userId) throws DataAccessLayerException{
List objects = null;
try {
session = getCurrentSession();
Query query = session.createQuery("from" + Notification.class.getName() + "where sender = :userId or receiver = :userId");
query.setParameter("userId", userId);
objects = query.list();
} catch (HibernateException e) {
logger.debug("Caught hibernate exception: {}" ,e);
}
return objects;
}
}
| mit |
Dan-field/Jazz | Urlinie.py | 5550 | from MIDIInput import *
from time import sleep
from random import *
from timer import *
class Urlinie:
def __init__(self, DS=1.0):
self.DS = DS
seed = range(120)
self.contour = []
for number in seed:
self.contour.append(0)
self.slope = 0
self.semi_multiplier = 32
self.no_of_undulations = 1
self.undulation_gradient = 0.0
self.arc_reference = [0, 6, 11, 17, 21, 26, 31, 35, 39, 43, 46, 50, 53, 57, 60, 63, 66, 69, 71, 74, 76, 79, 81, 83, 85, 88, 90, 91, 93, 95, 97, 98, 100, 101, 103, 104, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 115, 116, 117, 117, 118, 118, 119, 119, 119, 119, 120, 120, 120, 120, 120, 120, 120, 120, 119, 119, 119, 119, 118, 118, 117, 117, 116, 115, 115, 114, 113, 112, 111, 110, 109, 108, 107, 106, 104, 103, 101, 100, 98, 97, 95, 93, 91, 90, 88, 85, 83, 81, 79, 76, 74, 71, 69, 66, 63, 60, 57, 53, 50, 46, 43, 39, 35, 31, 26, 21, 17, 11, 6, 0]
#self.semicircle_reference = [0, 22, 31, 37, 43, 48, 52, 56, 60, 63, 66, 69, 72, 75, 77, 79, 82, 84, 86, 88, 89, 91, 93, 94, 96, 97, 99, 100, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 112, 113, 114, 114, 115, 116, 116, 117, 117, 118, 118, 118, 119, 119, 119, 119, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 119, 119, 119, 119, 118, 118, 118, 117, 117, 116, 116, 115, 114, 114, 113, 112, 112, 111, 110, 109, 108, 107, 106, 105, 104, 103, 102, 100, 99, 97, 96, 94, 93, 91, 89, 88, 86, 84, 82, 79, 77, 75, 72, 69, 66, 63, 60, 56, 52, 48, 43, 37, 31, 22, 0]
self.d = Display("Urlinie Contour", int(240*DS), int(240*DS), int(820*DS), int(10*DS))
self.display_line = []
for i, number in enumerate(self.contour):
self.display_line.append(Point(int(i*2*DS), int((120-number)*DS)))
for p in self.display_line:
self.d.add(p)
self.MI = None # placeholder for MIDI Input reference
self.drawingTimer = Timer(0, self.drawUL, [], False)
def newUrlinie_firstTry(self):
start = -self.slope
curve = self.semi_multiplier
newUrlinie = []
for i, no in enumerate(self.arc_reference):
newUrlinie.append(start*(120-i)/64 + no*curve/64)
self.contour = newUrlinie
self.display_line = []
for i, number in enumerate(newUrlinie):
self.display_line.append(Point(i*2, 120-number))
self.d.removeAll()
for point in self.display_line:
self.d.add(point)
def newUrlinie(self):
start = -self.slope
curve = self.semi_multiplier
newUrlinie = []
for i, no in enumerate(self.arc_reference):
newUrlinie.append(start*(120-i)/64 + no*curve/64) # this gives the underlying curve without undulations
# now add the undulations
if self.no_of_undulations > 1:
ref = []
undulatedUrlinie = []
divs = self.no_of_undulations
grad = self.undulation_gradient
for no in range(120):
ref.append((120/divs)*(1+(divs*no/120))) # create a vector pointing to the end of each segment, eg [15, 15, 15, ..., 30, 30, ..., 60..., 120]
for i in range(120):
undulatedUrlinie.append(newUrlinie[ref[i]-1]-int(grad*(ref[i]-i))) # create line segments that finish on the underlying curve
newUrlinie = undulatedUrlinie
self.contour = newUrlinie
self.drawingTimer.start()
return newUrlinie
def drawUL(self):
self.display_line = []
newUrlinie = self.contour
for i, number in enumerate(newUrlinie):
self.display_line.append(Point(int(i*2*self.DS), int((120-number)*self.DS)))
self.d.removeAll()
for point in self.display_line:
self.d.add(point)
def adjustOverallSlope(self, slider_value):
# assume slider_value is an integer 0-127
# Change: this now adjusts OVERALL SLOPE
self.slope = slider_value-63
def adjustArcMultiplier(self, value):
# Change: this now adjusts SEMICIRCLE MULTIPLIER
self.semi_multiplier = value-63
def adjustNumberOfUndulations(self, value):
# Change: this now adjusts NUMBER OF UNDULATIONS
self.no_of_undulations = (value/16)+1 # result from 1 to 8
def adjustUndulationGradient(self, value):
# Change: this now adjusts undulation gradient
self.undulation_gradient = (value-63.0)/(8.0*self.no_of_undulations)
def weighted_choice(self, weights):
# thanks to Eli Benderski's Website
totals = []
running_total = 0
for w in weights:
running_total += w
totals.append(running_total)
rnd = random() * running_total
for i, total in enumerate(totals):
if rnd < total:
return i
def allOctaves(self, MidiNo): # Takes a single MIDI number input and returns a list of that note in all octaves
octaves = [element*12 for element in range(11)] # produce list [0, 12, 24 ... 120]
pc = int(MidiNo)%12 # pitch class
result = []
for octave in octaves:
result.append(octave+pc) # this is the pitch class number plus the octave number
return result
def pickClosest(self, notepool, target): # returns the nearest note in the notepool to the target
# check how far the potential notes are from the target
differences = [abs(target - float(note)) for note in notepool]
# find the closest
closest = differences.index(min(differences))
return notepool[closest]
| mit |
kitaisreal/ToneApp | app/src/main/java/com/example/yetti/toneplayer/database/impl/DBArtistServiceImpl.java | 7405 | package com.example.yetti.toneplayer.database.impl;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.example.yetti.toneplayer.database.DBToneContract;
import com.example.yetti.toneplayer.database.DatabaseManager;
import com.example.yetti.toneplayer.database.IDBArtistService;
import com.example.yetti.toneplayer.model.Artist;
import java.util.ArrayList;
import java.util.List;
public class DBArtistServiceImpl implements IDBArtistService {
@Override
public boolean addArtists(List<Artist> pArtistList) {
try {
final SQLiteDatabase sqLiteDatabase = DatabaseManager.getInstance().openDatabase();
for (final Artist artist : pArtistList) {
final ContentValues values = new ContentValues();
values.put(DBToneContract.ArtistEntry.COLUMN_NAME_ARTIST_NAME, artist.getArtistName());
values.put(DBToneContract.ArtistEntry.COLUMN_NAME_ARTIST_SONG_COUNT, artist.getSongCount());
values.put(DBToneContract.ArtistEntry.COLUMN_NAME_ARTIST_GENRE, artist.getArtistGenre());
values.put(DBToneContract.ArtistEntry.COLUMN_NAME_ARTIST_ARTWORKURL, artist.getArtistArtUrl());
final String sqlToExecute = String.format(DBToneContract.SQLTemplates.SQL_SELECT_WHERE,
"*",
DBToneContract.ArtistEntry.TABLE_NAME,
DBToneContract.ArtistEntry.COLUMN_NAME_ARTIST_NAME,
artist.getArtistName());
final Cursor c = sqLiteDatabase.rawQuery(sqlToExecute, null);
if (c.moveToFirst()) {
c.close();
} else {
c.close();
sqLiteDatabase.insert(DBToneContract.ArtistEntry.TABLE_NAME, null, values);
}
}
sqLiteDatabase.close();
DatabaseManager.getInstance().closeDatabase();
return true;
} catch (final Exception ex) {
ex.printStackTrace();
}
return false;
}
@Override
public boolean deleteArtists(List<Artist> pArtistList) {
final SQLiteDatabase sqLiteDatabase = DatabaseManager.getInstance().openDatabase();
for (final Artist artist : pArtistList) {
final String artistName = artist.getArtistName();
final String sqlToExecute = String.format(DBToneContract.SQLTemplates.SQL_SELECT_WHERE,
"*",
DBToneContract.SongEntry.TABLE_NAME,
DBToneContract.SongEntry.COLUMN_NAME_ENTRY_ID,
artist.getArtistName());
final Cursor c = sqLiteDatabase.rawQuery(sqlToExecute, null);
if (c.moveToFirst()) {
sqLiteDatabase.delete(DBToneContract.SongEntry.TABLE_NAME, DBToneContract.ArtistEntry.COLUMN_NAME_ARTIST_NAME + " = ?",
new String[]{artistName});
c.close();
} else {
c.close();
}
}
sqLiteDatabase.close();
DatabaseManager.getInstance().closeDatabase();
return true;
}
@Override
public boolean updateArtist(Artist pArtist) {
final SQLiteDatabase sqLiteDatabase = DatabaseManager.getInstance().openDatabase();
try {
System.out.println("DATABASE " + pArtist.toString());
final ContentValues values = new ContentValues();
values.put(DBToneContract.ArtistEntry.COLUMN_NAME_ARTIST_NAME, pArtist.getArtistName());
values.put(DBToneContract.ArtistEntry.COLUMN_NAME_ARTIST_SONG_COUNT, pArtist.getSongCount());
values.put(DBToneContract.ArtistEntry.COLUMN_NAME_ARTIST_GENRE, pArtist.getArtistGenre());
values.put(DBToneContract.ArtistEntry.COLUMN_NAME_ARTIST_ARTWORKURL, pArtist.getArtistArtUrl());
sqLiteDatabase.update(DBToneContract.ArtistEntry.TABLE_NAME, values, DBToneContract.ArtistEntry.COLUMN_NAME_ARTIST_NAME + "=?",
new String[]{pArtist.getArtistName()});
sqLiteDatabase.close();
DatabaseManager.getInstance().closeDatabase();
return true;
} catch (final Exception ex) {
sqLiteDatabase.close();
DatabaseManager.getInstance().closeDatabase();
return false;
}
}
@Override
public Artist getArtistByName(String pArtistName) {
try {
final SQLiteDatabase sqLiteDatabase = DatabaseManager.getInstance().openDatabase();
final String sqlToExecute = String.format(DBToneContract.SQLTemplates.SQL_SELECT_WHERE,
"*",
DBToneContract.ArtistEntry.TABLE_NAME,
DBToneContract.ArtistEntry.COLUMN_NAME_ARTIST_NAME,
pArtistName);
final Cursor c = sqLiteDatabase.rawQuery(sqlToExecute, null);
if (c != null) {
c.moveToFirst();
final int artistNameIndex = c.getColumnIndex(DBToneContract.ArtistEntry.COLUMN_NAME_ARTIST_NAME);
final int artistSongCount = c.getColumnIndex(DBToneContract.ArtistEntry.COLUMN_NAME_ARTIST_SONG_COUNT);
final int artistGenre = c.getColumnIndex(DBToneContract.ArtistEntry.COLUMN_NAME_ARTIST_GENRE);
final int artistArtworkUrl = c.getColumnIndex(DBToneContract.ArtistEntry.COLUMN_NAME_ARTIST_ARTWORKURL);
sqLiteDatabase.close();
DatabaseManager.getInstance().closeDatabase();
final Artist artist = new Artist(c.getString(artistNameIndex), c.getInt(artistSongCount), c.getString(artistGenre), c.getString(artistArtworkUrl));
c.close();
return artist;
}
sqLiteDatabase.close();
} catch (final Exception ex) {
return null;
}
return null;
}
@Override
public List<Artist> getArtists() {
try {
final SQLiteDatabase sqLiteDatabase = DatabaseManager.getInstance().openDatabase();
final Cursor c = sqLiteDatabase.query(DBToneContract.ArtistEntry.TABLE_NAME, null, null, null, null, null, null);
final List<Artist> artistList = new ArrayList<>();
if (c.moveToFirst()) {
final int artistNameIndex = c.getColumnIndex(DBToneContract.ArtistEntry.COLUMN_NAME_ARTIST_NAME);
final int artistSongCount = c.getColumnIndex(DBToneContract.ArtistEntry.COLUMN_NAME_ARTIST_SONG_COUNT);
final int artistGenre = c.getColumnIndex(DBToneContract.ArtistEntry.COLUMN_NAME_ARTIST_GENRE);
final int artistArtworkUrl = c.getColumnIndex(DBToneContract.ArtistEntry.COLUMN_NAME_ARTIST_ARTWORKURL);
do {
artistList.add(new Artist(c.getString(artistNameIndex), c.getInt(artistSongCount), c.getString(artistArtworkUrl), c.getString(artistGenre)));
} while (c.moveToNext());
c.close();
sqLiteDatabase.close();
DatabaseManager.getInstance().closeDatabase();
return artistList;
}
c.close();
} catch (final Exception ex) {
ex.printStackTrace();
return null;
}
return null;
}
}
| mit |
ChrisL1200/post-office-project | app/scripts/services/user.js | 361 | 'use strict';
angular.module('postOfficeProjectApp')
.factory('User', function ($resource) {
return $resource('/api/users/:id/:action', {
id: '@id'
}, { //parameters default
update: {
method: 'PUT',
params: {}
},
get: {
method: 'GET',
params: {
id:'me'
}
}
});
});
| mit |