repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
gazzlab/LSL-gazzlab-branch | liblsl/external/lslboost/numeric/conversion/bounds.hpp | 721 | // (c) Copyright Fernando Luis Cacciola Carballal 2000-2004
// Use, modification, and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.lslboost.org/LICENSE_1_0.txt)
// See library home page at http://www.lslboost.org/libs/numeric/conversion
//
// Contact the author at: [email protected]
//
#ifndef BOOST_NUMERIC_CONVERSION_BOUNDS_12NOV2002_HPP
#define BOOST_NUMERIC_CONVERSION_BOUNDS_12NOV2002_HPP
#include "lslboost/numeric/conversion/detail/bounds.hpp"
namespace lslboost { namespace numeric
{
template<class N>
struct bounds : boundsdetail::get_impl<N>::type
{} ;
} } // namespace lslboost::numeric
#endif
| mit |
NCuculova/Roommates | src/main/java/mk/ukim/finki/mp/roommates/model/ListLook.java | 1025 | package mk.ukim.finki.mp.roommates.model;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import mk.ukim.finki.mp.roommates.util.CustomLocalDateSerializer;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
/**
* Class for the bookmarked listings with getters and setters for all properties
*/
@Entity
@Table(name = "listlook")
public class ListLook extends BaseEntity {
@ManyToOne
private Listing listing;
@ManyToOne
private Member member;
@JsonSerialize(using = CustomLocalDateSerializer.class)
private Date date;
public Listing getListing() {
return listing;
}
public void setListing(Listing listing) {
this.listing = listing;
}
public Member getMember() {
return member;
}
public void setMember(Member member) {
this.member = member;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
| mit |
llalov/Issue-Tracking-System | services/SoftUniIssueTracker.Models/Project.cs | 1609 | using SIT.Models.Interfaces;
namespace SIT.Models
{
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
public class Project : IDentificatable
{
private ICollection<ProjectPriority> projectPriorities;
private ICollection<ProjectLabel> projectLabels;
private ICollection<Issue> issues;
public Project()
{
this.projectPriorities = new HashSet<ProjectPriority>();
this.projectLabels = new HashSet<ProjectLabel>();
this.issues = new HashSet<Issue>();
}
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string ProjectKey { get; set; }
public string Description { get; set; }
[Required]
public string LeadId { get; set; }
public virtual User Lead { get; set; }
public int TransitionSchemeId { get; set; }
public virtual TransitionScheme TransitionScheme { get; set; }
public virtual ICollection<ProjectPriority> ProjectPriorities
{
get { return this.projectPriorities; }
set { this.projectPriorities = value; }
}
public virtual ICollection<ProjectLabel> ProjectLabels
{
get { return this.projectLabels; }
set { this.projectLabels = value; }
}
public virtual ICollection<Issue> Issues
{
get { return this.issues; }
set { this.issues = value; }
}
}
} | mit |
20steps/alexa | web/wp-content/plugins/cac-addon-acf/classes/Free/Setting/Field/Media.php | 1106 | <?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
class ACA_ACF_Free_Setting_Field_Media extends ACA_ACF_Free_Setting_Field {
public function get_grouped_field_options() {
add_filter( 'acf/location/rule_match/user_type', '__return_true', 16 );
add_filter( 'acf/location/rule_match/page_type', '__return_true', 16 );
add_filter( 'acf/location/rule_match/post_type', array( $this, 'is_location_attachment' ), 16, 2 );
add_filter( 'acf/location/rule_match/ef_media', '__return_true', 16 );
$group_ids = apply_filters( 'acf/location/match_field_groups', array(), array() );
remove_filter( 'acf/location/rule_match/user_type', '__return_true', 16 );
remove_filter( 'acf/location/rule_match/page_type', '__return_true', 16 );
remove_filter( 'acf/location/rule_match/post_type', array( $this, 'is_location_attachment' ), 16 );
remove_filter( 'acf/location/rule_match/ef_media', '__return_true', 16 );
return $this->get_option_groups( $group_ids );
}
public function is_location_attachment( $match, $rule ) {
return isset( $rule['value'] ) && 'attachment' === $rule['value'];
}
}
| mit |
it-projects-llc/website-addons | website_sale_clear_cart/controllers/website_sale_clear_cart.py | 346 | from odoo import http
from odoo.http import request
class PosWebsiteSale(http.Controller):
@http.route(["/shop/clear_cart"], type="json", auth="public", website=True)
def clear_cart(self):
order = request.website.sale_get_order()
if order:
for line in order.website_order_line:
line.unlink()
| mit |
zenkovnick/pfr | apps/frontend/modules/flight/templates/_plane_field.php | 533 | <?php
$options = array();
if(isset($class)){
$options['class'] = $class;
}
if(isset($placeholder))
$options['placeholder'] = $placeholder;
if(isset($disabled) && $disabled){
$options['disabled'] = 'disabled';
}
?>
<?php
if(!($field->getWidget() instanceof sfWidgetFormInputHidden)){
if(isset($label)){
if($label !== false) {
echo $field->renderLabel();
}
}
echo "<div class='list-select plane-select'>".$field->render($options)."</div>";
echo $field->renderError() ;
}
?>
| mit |
Filipkovarik/JS_projects | DCBw7M351.js | 8271 | const Discord = require("discord.js");
const client = new Discord.Client();
const http = require("http");
const auth = require("./auth.json");
const req = require("./req.json")
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const prefix = "§";
parseargs = (x, delimiter='"') =>
x.split(" ").reduce(
(arr, val) => {
let strEnd = val[val.length-1] === delimiter && val[val.length-2] !== "\\";
if (strEnd) val = val.substring(0, val.length - 1);
return ((arr[arr.length-1] || "")[0] !== delimiter) ? arr.concat([val]) : [arr.pop().substring(strEnd ? 1 : 0) + " " + val, ...(arr.reverse()) ].reverse() },
[] ).map(x => x.replace(new RegExp('\\\\' + delimiter, 'gm'), delimiter).replace(/\\\\/gm, "\\"));
splitarray = (array, callback) => {
let indices = [0], chunks = [];
array.forEach((elem, index, arr) => callback(elem, index, arr) && indices.push(index));
indices.push(array.length);
for (i = 1; i < indices.length; i++) chunks.push(array.slice( indices[i - 1] , indices[i] ))
return chunks
}
class Command {
constructor (name, func, desc="", syntax="", argdesc={}, argcheck=()=>true, perms=0b0) {
this.name = name;
Command._commands[name] = this;
this.func = func; this.permissions = perms; this.syntax = syntax;
this.description = desc; this.argcheck = argcheck; this.argdesc = argdesc;
}
run(member, args, message) {
if (args[0] === "/?") return this.help(message);
let validation = this.argcheck.apply(args);
if (validation === false) {message.channel.send("Nesprávná syntax"); this.help(message); return false;}
if (!auth_check(member)) return message.channel.send("Nedostatečné oprávnění")
func.call(message.channel, message, args)
}
auth_check(member){
return member.permissions.has(this.permissions);
}
help(message){
return message.channel.send(
this.name + ": " +
this.description + "\n" +
this.name + " " + this.syntax + "\n\n" +
Object.keys(this.argdesc)
.map(k => k.padEnd(10) + this.argdesc[k]).join("\n")
);
}
}
Command._commands = {};
class IRequest {
constructor(){
this.creq = http.get(req.url, {path: req.path, auth: req.user+":"+req.pass}, res => {
console.log("[IReq] Status " + res.statusCode);
if (res.statusCode !== 200) { res.resume(); return; }
res.setEncoding("windows-1250");
let rawData = '';
res.on('data', chunk => rawData += chunk );
res.on('end', _ => this.parse(rawData) );
}
this.timestamp = +(new Date());
}
parse(html) {
console.log("[IReq] Data received");
const dom = new JSDOM(html);
const win = dom.window;
//const win = document // for in-page testing
const focusSelector = "body > center:nth-child(3) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(1) > td:nth-child(1) > center:nth-child(1) > table:nth-child(2) > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(4) > center:nth-child(1) > table:nth-child(2) > tbody:nth-child(1) > tr:nth-child(1) > td:nth-child(1) > center:nth-child(1)";
const elems = splitarray(Array.prototype.filter.call(win.querySelector(focusSelector).children,
(elem, index, arr) =>
["font", "table", "center"].indexOf(elem.nodeName.toLowerCase()) > -1
&& ( index == arr.length-1 || (elem.nodeName + arr[index+1].nodeName).toLowerCase() !== "tabletable" ) ),
(elem) => elem.nodeName.toLowerCase() === "center"
)
return new IData(elems, this.timestamp);
}
}
class IData {
constructor(arr, timestamp){
if (arr.length === 0) throw new TypeError("No IData provided");
this.entries = arr.map(idata => (([_,d,m,y]) => Date.parse(m+"/"+d+"/"+y))(idata[0].match(/(\d+)\.(\d+)\.(\d+)/)))
.map((idata)=>[idata[0], new IData.Day(this, ...idata)])
this.timestamp = timestamp;
}
}
IData.Day = class Day {
constructor(head, date, table, extras=""){
this.head = head;
this.date = date;
this.table = table;
this.extrasstr = extras;
this.entries = [];
this.extras = [];
this.reloc = [];
this.parseTable();
}
parseTable(){
let table = Array.prototype.slice.call(this.table.querySelectorAll("tr"), 2)
.map(row => row.children.map(cell => cell.innerText))
for (i = 0; i < table.length; i++) table[i][0] == (table[i][0].length <= 2) ? table[i-1][0] : table[i][0];
}
}
(()=>{
function ping() { this.send("pong!") }
function idata() { this.send("Na hledači suplování se stále tvrdě pracuje.") }
function help(message, [cmdname])
{
if (cmdname === undefined) return this.send("Pro zadání parametrů příkazů obsahující mezery ohraničte parametr uvozovkami: `" + prefix + "role přidat \"Velký okoun\"`\nDostupné příkazy:\n\n" + Object.values(Command._commands).map(cmd => cmd.name.padEnd(10)+cmd.description).join("\n"));
if (Command._commands.hasOwnProperty(cmdname)) Command._commands[cmdname].help(message);
else this.send("Neznámý příkaz. Napište '" + prefix + "help' pro seznam všech příkazů.");
}
function selfrole(message, [action, rolequery]){
let role = Object.entries(this.guild.roles).filter( ([ID, rolename]) => rolename === rolequery );
if (role.length > 1) return this.send("Existuje více rolí s tímto jménem. Prosím obtěžujte administrátory, ať toto nedopatření napraví.");
if (role.length === 0) return this.send(`Role "${rolequery}" neexistuje.`);
[role] = role;
let member = message.member;
let availroles = Object.entries(arguments.callee._roles)
.filter( ([perms, roles]) => perms & member.permissions === perms )
.reduce( ([perms, roles], cur) => cur.concat(roles), [] );
if (availroles.indexOf(role) === -1) return this.send(`Role "${rolequery}" není dostupná.`);
if (action === "přidat") member.addRole(role, "Bot self-assignment");
else member.removeRole(role, "Bot self-unassignment");
return true;
}
selfrole._roles = {
0b0: []
}
new Command("ping", ping, "Pošle zpět odezvu");
new Command("supl", idata, "[WIP] Zobrazí personalizované suplování"
);
new Command("help", help, "Vypíše seznam všech dostupných příkazů, nebo vypíše nápovědu k zadanému příkazu.", "help *příkaz*",
{"*příkaz*": "Jméno příkazu, k němuž se má zobrazit nápověda."});
new Command("role", selfrole, "Umožní uživateli si přidat či odebrat dostupné role / označení.",
"role přidat/odebrat *role*", {"přidat": "Umožní přidání role", "odebrat": "Umožní odebrání role" , "*role*": "Role, která se má uživateli přidat/odebrat"},
(action) => action === "přidat" || action === "odebrat" );
})()
/*const commands = {
"echo": (message, args) => {
var a = [];
for (var i in args) if(i!=0) a.push(args[i]);;
message.channel.send(a.join(" "))
}
}*/
class Reaction{
constructor (check, react){}
}
const reactions = {
/*"zacina noc": "drž hubu!",
"začíná noc": "drž hubu!",
"la nuit commence": "tais toi!",
"the game": "I just lost.",
"klutzy": "Draconequus",
"supl": "Did somepone say supl?",
"knock, knock": "Who's there?"*/
}
client.on("message", message => {
console.log("Message detected: " + message.content);
let prefix = "§";
if(message.content.substring(0, prefix.length) === prefix) {
console.log("Detected command call");
var args = message.content.substring(prefix.length).split(" ");
var cmd = args.shift();
console.log(`Detected "${cmd}" command call`);
args = parseargs(args.join(" "))
console.log("Arguments: " + args.join("+"));
console.log("Command exists: " + Command._commands.hasOwnProperty(cmd));
if(Command._commands.hasOwnProperty(cmd))
Commands._commands[cmd].run(message.member, args, message);
else message.channel.send("Neznámý příkaz, pro seznam příkazů napiš '" + prefix + "help'.");
}
else {
for(var k in reactions) {
if(message.content.toLowerCase().includes(k) && !message.member.roles.some(x=>x.name==="Bot")){
message.reply(reactions[k]);
break;
}
}
}
});
console.log("Bot started");
client.login(auth.token);
| mit |
Breta01/MemoryKing | src/actions/actionCreators.js | 678 | // Load stats
export function loadStats(stats) {
return {
type: 'LOAD_STATS',
stats
}
}
// Add stats
export function addStats(stat) {
return {
type: 'ADD_STATS',
stat: stat
}
}
// Change account
export function changeAcconut(accountId) {
return {
type: 'CHANGE_ACCOUNT',
gameId,
score
}
}
// Change settings
export function changeSettings(settingsId, newSettings) {
return {
type: 'CHANGE_SETTINGS',
settingsId,
newSettings
}
}
// Reset settings
export function resetSettings(settingsId) {
return {
type: 'RESET_SETTINGS',
settignsId
}
}
| mit |
patrys/qcheck | qcheck/__init__.py | 3312 | from __future__ import print_function
import collections
import itertools
import random
import string
import sys
Spec = collections.namedtuple('Spec', 'instance model actions properties')
Action = collections.namedtuple('Action', 'callable args kwargs')
def signature(*args, **kwargs):
def decorator(func):
func._args = [generator() for generator in args]
func._kwargs = dict(
(name, generator()) for name, generator in kwargs.items())
return func
return decorator
def random_action(spec, instance, model):
action = random.choice(spec.actions)
args = [next(generator) for generator in action._args]
kwargs = dict(
(name, next(generator))
for name, generator in action._kwargs.items())
return Action(action, args, kwargs)
def test_step(spec, instance, model, action=None):
if action is None:
action = random_action(spec, instance, model)
try:
retval = action.callable(
instance, model, *action.args, **action.kwargs)
except Exception as exc:
return action, exc
if retval is NotImplemented:
return NotImplemented, None
for prop in spec.properties:
try:
prop(instance, model)
except Exception as exc:
return action, exc
return action, None
def reduce_test_case(spec, test_case):
print('Reducing the test case')
for seq_len in range(1, len(test_case) - 1):
print('Checking test cases of length %d...' % (seq_len,))
for sub_case in itertools.combinations(test_case, seq_len):
instance = spec.instance()
model = spec.model()
for action in sub_case:
retval, exc = test_step(spec, instance, model, action)
if exc:
return sub_case
return test_case
def generate_test_case(spec, max_length):
test_case = []
instance = spec.instance()
model = spec.model()
while len(test_case) < max_length:
action = NotImplemented
while action is NotImplemented:
action, exc = test_step(spec, instance, model)
test_case.append(action)
if exc:
print('ERROR:', repr(exc))
test_case = reduce_test_case(spec, test_case)
print('Failing case:')
for action in test_case:
print(
'%s %r %r' % (
action.callable.__code__.co_name,
action.args, action.kwargs))
return test_case
def test_spec(spec):
for test_len in range(30):
for test_no in range(200):
test_case = generate_test_case(spec, test_len)
if test_case:
return test_case
def rand_int(value_min=0, value_max=sys.maxint, edge_cases=[0, 1, 2]):
for value in edge_cases:
yield value
while True:
yield random.randint(value_min, value_max)
def rand_string(min_length=0, max_length=255, alphabet=None, edge_cases=['']):
for value in edge_cases:
yield value
if alphabet is None:
alphabet = string.ascii_letters + string.ascii_digits
while True:
yield ''.join(
random.choice(alphabet)
for i in range(random.randrange(min_length, max_length)))
| mit |
hayes/unpm | index.js | 1410 | var Router = require('unpm-router')
var auth = require('unpm-auth')
var http = require('http')
var controllers = require('./lib/controllers')
var Package = require('./lib/models/Package')
var add_defaults = require('./lib/config')
var logging = require('./lib/logging')
var handler = require('./lib/handler')
var cidr = require('./lib/cidr')
module.exports = unpm
function unpm(config, User, backend) {
if(!(this instanceof unpm)) {
return new unpm(config, User, backend)
}
config = add_defaults(config)
this.router = Router(config.basePathname)
this.handler = handler(this)
this.server = http.createServer(this.handler)
this.log = logging(config)
this.port = config.port || 8123
this.config = config
this.middleware = []
this.backend = Object.create(config.backend || {})
if(backend) {
config.backend = backend
}
if(User) {
config.User = User
}
this.Package = Package(this)
auth(this, config.User)
cidr(this)
this.router.add('PUT', '/:name', controllers.publish)
this.router.add('GET', '/:name/-/:name/:version.tgz', controllers.getTarball)
this.router.add('GET', '/:name/:version?', controllers.getPackage)
this.router.add('PUT', '/:name/-rev/:rev?', controllers.unpublish.some)
this.router.add('DELETE', '/:name/-rev/:rev?', controllers.unpublish.all)
this.router.add('DELETE', '/:name/-/:file/-rev/:rev', controllers.unpublish.tarball)
}
| mit |
epam/Constellation | app/scripts/router.js | 249 | App.Router.map(function () {
this.route("loginForm", {path: "/"});
this.resource("openflow", {path: "/openflow"}, function () {
this.route("topology", {path: "/topology"});
this.route("flows", {path: "/flows"});
});
}); | mit |
enilu/web-flash | flash-vue-h5/src/page/official_site/news.js | 848 | import {XHeader, Panel, Swiper, SwiperItem} from 'vux'
import footMenu from '../../components/footer/footMenu'
import api from '../../fetch/api'
import {getApiUrl} from '../../util/tool'
export default {
components: {
XHeader, footMenu, Panel, Swiper, SwiperItem
},
data () {
return {
banner: {},
newsList: [],
userName: 'enilu'
}
},
created () {
this.init()
},
methods: {
init () {
const imgBase = getApiUrl() + '/file/getImgStream?idFile='
api.getNewsList().then(res => {
this.banner = res.data.data.banner
for (const index in this.banner.list) {
this.banner.list[index].img = imgBase + this.banner.list[index].idFile
}
this.list = res.data.data.list
})
},
bannerChange (index) {
this.banner.index = index
}
}
}
| mit |
cliftonm/clifton | Clifton.Core/Clifton.Core.TemplateEngine/TemplateEngine.cs | 7427 | /* The MIT License (MIT)
*
* Copyright (c) 2015 Marc Clifton
*
* 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 System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using Clifton.Core.ExtensionMethods;
using Clifton.Core.Semantics;
namespace Clifton.Core.TemplateEngine
{
public class TemplateEngine
{
public List<string> Usings { get; protected set; }
public List<string> References { get; protected set; }
protected Dictionary<Guid, IRuntimeAssembly> cachedAssemblies;
protected bool useDynamic;
protected ISemanticProcessor proc;
public TemplateEngine(ISemanticProcessor proc = null)
{
Usings = new List<string>();
References = new List<string>();
cachedAssemblies = new Dictionary<Guid, IRuntimeAssembly>();
AddCoreUsings();
}
protected virtual void AddCoreUsings()
{
Usings.Add("using System;");
Usings.Add("using System.Text;");
Usings.Add("using Clifton.Core.TemplateEngine;");
}
public void UsesDynamic()
{
useDynamic = true;
References.Add("Microsoft.CSharp.dll");
References.Add(typeof(System.Runtime.CompilerServices.DynamicAttribute).Assembly.Location);
}
public string Parse(string template)
{
string ret;
IRuntimeAssembly t;
if (!IsCached(template, out t))
{
string code = new Parser().Parse(template);
StringBuilder sb = new StringBuilder(String.Join("\r\n", Usings));
sb.Append(GetClassBoilerplate());
sb.Append(code);
sb.Append(GetFinisherBoilerplate());
t = GetAssembly(sb.ToString());
cachedAssemblies[GetHash(template)] = t;
}
ret = t.GetTemplate();
return ret;
}
public string Parse(string template, List<ParamTypeInfo> parms)
{
string ret;
IRuntimeAssembly t;
if (!IsCached(template, out t))
{
string code = new Parser().Parse(template);
StringBuilder sb = new StringBuilder(String.Join("\r\n", Usings));
sb.Append(GetClassBoilerplate());
InitializeParameters(sb, parms);
sb.Append(code);
sb.Append(GetFinisherBoilerplate());
t = GetAssembly(sb.ToString());
cachedAssemblies[GetHash(template)] = t;
}
object[] objParms = parms.Select(p => p.ParamValue).ToArray();
ret = t.GetTemplate(objParms);
return ret;
}
public string Parse(string template, string[] names, params object[] parms)
{
string ret;
IRuntimeAssembly t;
if (!IsCached(template, out t))
{
string code = new Parser().Parse(template);
StringBuilder sb = new StringBuilder(String.Join("\r\n", Usings));
sb.Append(GetClassBoilerplate());
InitializeParameters(sb, names, parms);
sb.Append(code);
sb.Append(GetFinisherBoilerplate());
t = GetAssembly(sb.ToString());
cachedAssemblies[GetHash(template)] = t;
}
ret = t.GetTemplate(parms);
return ret;
}
public string Parse(string template, params object[] parms)
{
string ret;
IRuntimeAssembly t;
if (!IsCached(template, out t))
{
string code = new Parser().Parse(template);
StringBuilder sb = new StringBuilder(String.Join("\r\n", Usings));
sb.Append(GetClassBoilerplate());
InitializeParameters(sb, parms);
sb.Append(code);
sb.Append(GetFinisherBoilerplate());
t = GetAssembly(sb.ToString());
cachedAssemblies[GetHash(template)] = t;
}
ret = t.GetTemplate(parms);
return ret;
}
//public bool IsCached(string template)
//{
// return cachedAssemblies.ContainsKey(GetHash(template));
//}
public bool IsCached(string template, out IRuntimeAssembly t)
{
return cachedAssemblies.TryGetValue(GetHash(template), out t);
}
public virtual Guid GetHash(string template)
{
using (MD5 md5 = MD5.Create())
{
byte[] hash = md5.ComputeHash(Encoding.Default.GetBytes(template));
return new Guid(hash);
}
}
private string GetClassBoilerplate()
{
return @"
public class RuntimeCompiled : IRuntimeAssembly
{
public string GetTemplate(object[] paramList)
{
";
}
private string GetFinisherBoilerplate()
{
return @"
return sb.ToString();
}
}";
}
private IRuntimeAssembly GetAssembly(string assyCode)
{
IRuntimeAssembly t = null;
List<string> errors;
Assembly assy = Compiler.Compile(assyCode, out errors, References);
if (assy == null)
{
proc.IfNotNull((p) => errors.ForEach(errMsg => p.ProcessInstance<LoggerMembrane, ST_CompilerError>(err => err.Error = errMsg)));
throw new TemplateEngineException(errors);
}
else
{
t = (IRuntimeAssembly)assy.CreateInstance("RuntimeCompiled");
}
return t;
}
/// <summary>
/// Using a fully specified parameter list: value, name, and type.
/// </summary>
private void InitializeParameters(StringBuilder sb, List<ParamTypeInfo> parms)
{
parms.ForEachWithIndex((pti, idx) =>
{
sb.Append(pti.ParamType + " " + pti.ParamName + " = (" + pti.ParamType+")paramList[" + idx + "];\r\n");
});
}
/// <summary>
/// Making assumptions about class types and native types, still requiring variable names.
/// </summary>
private void InitializeParameters(StringBuilder sb, string[] names, object[] parms)
{
parms.ForEachWithIndex((parm, idx) =>
{
if (useDynamic)
{
sb.Append("dynamic " + names[idx] + " = paramList[" + idx + "];\r\n");
}
else
{
Type t = parm.GetType();
string typeName = t.IsClass ? "I" + t.Name : t.Name;
sb.Append(typeName + " " + names[idx] + " = (" + typeName + ")paramList[" + idx + "];\r\n");
}
});
}
/// <summary>
/// Only dynamic is supported. Non-class types are not supported because we can't determine their names.
/// Class types must be distinct.
/// </summary>
private void InitializeParameters(StringBuilder sb, object[] parms)
{
List<string> typeNames = new List<string>();
parms.ForEachWithIndex((parm, idx) =>
{
Type t = parm.GetType();
string typeName = t.Name.CamelCase();
if (!t.IsClass)
{
throw new TemplateEngineException("Automatic parameter passing does not support native types. Wrap the type in a class.");
}
if (typeNames.Contains(typeName))
{
throw new TemplateEngineException("Type names must be distinct.");
}
typeNames.Add(typeName);
sb.Append("dynamic " + typeName + " = paramList[" + idx + "];\r\n");
});
}
}
}
| mit |
QuinntyneBrown/SecurityApi | SecurityApi/Auth/JwtOptions.cs | 500 | using Microsoft.Owin.Security.Jwt;
using SecurityApi.Config;
namespace SecurityApi.Auth
{
public class JwtOptions : JwtBearerAuthenticationOptions
{
public JwtOptions()
{
var config = AppConfiguration.Config;
AllowedAudiences = new[] { config.JwtAudience };
IssuerSecurityTokenProviders = new[]
{
new SymmetricKeyIssuerSecurityTokenProvider(config.JwtIssuer, config.JwtKey)
};
}
}
} | mit |
mimmi20/browscap-js | test/issue-1442.js | 14981 | 'use strict';
const assert = require('assert');
const Browscap = require('../src/index.js');
suite('checking for issue 1442. (2 tests)', function () {
test('issue-1442-A ["Mozilla/4.0 (compatible; Linux 2.6.22) NetFront/3.4 Kindle/2.0 (screen 600x800)"]', function () {
const browscap = new Browscap();
const browser = browscap.getBrowser('Mozilla/4.0 (compatible; Linux 2.6.22) NetFront/3.4 Kindle/2.0 (screen 600x800)');
assert.strictEqual(browser['Comment'], 'Access NetFront 3.4', 'Expected actual "Comment" to be \'Access NetFront 3.4\' (was \'' + browser['Comment'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Browser'], 'NetFront', 'Expected actual "Browser" to be \'NetFront\' (was \'' + browser['Browser'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Browser_Type'], 'Browser', 'Expected actual "Browser_Type" to be \'Browser\' (was \'' + browser['Browser_Type'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Browser_Bits'], '0', 'Expected actual "Browser_Bits" to be \'0\' (was \'' + browser['Browser_Bits'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Browser_Maker'], 'Access', 'Expected actual "Browser_Maker" to be \'Access\' (was \'' + browser['Browser_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Browser_Modus'], 'unknown', 'Expected actual "Browser_Modus" to be \'unknown\' (was \'' + browser['Browser_Modus'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Version'], '3.4', 'Expected actual "Version" to be \'3.4\' (was \'' + browser['Version'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Platform'], 'unknown', 'Expected actual "Platform" to be \'unknown\' (was \'' + browser['Platform'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Platform_Version'], 'unknown', 'Expected actual "Platform_Version" to be \'unknown\' (was \'' + browser['Platform_Version'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Platform_Description'], 'unknown', 'Expected actual "Platform_Description" to be \'unknown\' (was \'' + browser['Platform_Description'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Platform_Bits'], '0', 'Expected actual "Platform_Bits" to be \'0\' (was \'' + browser['Platform_Bits'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Platform_Maker'], 'unknown', 'Expected actual "Platform_Maker" to be \'unknown\' (was \'' + browser['Platform_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Alpha'], false, 'Expected actual "Alpha" to be false (was \'' + browser['Alpha'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Beta'], false, 'Expected actual "Beta" to be false (was \'' + browser['Beta'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Frames'], true, 'Expected actual "Frames" to be true (was \'' + browser['Frames'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['IFrames'], true, 'Expected actual "IFrames" to be true (was \'' + browser['IFrames'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Tables'], true, 'Expected actual "Tables" to be true (was \'' + browser['Tables'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Cookies'], true, 'Expected actual "Cookies" to be true (was \'' + browser['Cookies'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['JavaScript'], true, 'Expected actual "JavaScript" to be true (was \'' + browser['JavaScript'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['VBScript'], false, 'Expected actual "VBScript" to be false (was \'' + browser['VBScript'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['JavaApplets'], false, 'Expected actual "JavaApplets" to be false (was \'' + browser['JavaApplets'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['isSyndicationReader'], false, 'Expected actual "isSyndicationReader" to be false (was \'' + browser['isSyndicationReader'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['isFake'], false, 'Expected actual "isFake" to be false (was \'' + browser['isFake'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['isAnonymized'], false, 'Expected actual "isAnonymized" to be false (was \'' + browser['isAnonymized'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['isModified'], false, 'Expected actual "isModified" to be false (was \'' + browser['isModified'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['CssVersion'], '2', 'Expected actual "CssVersion" to be \'2\' (was \'' + browser['CssVersion'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Device_Name'], 'Kindle', 'Expected actual "Device_Name" to be \'Kindle\' (was \'' + browser['Device_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Device_Maker'], 'Amazon.com, Inc.', 'Expected actual "Device_Maker" to be \'Amazon.com, Inc.\' (was \'' + browser['Device_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Device_Type'], 'Ebook Reader', 'Expected actual "Device_Type" to be \'Ebook Reader\' (was \'' + browser['Device_Type'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Device_Pointing_Method'], 'touchscreen', 'Expected actual "Device_Pointing_Method" to be \'touchscreen\' (was \'' + browser['Device_Pointing_Method'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Device_Code_Name'], 'Kindle', 'Expected actual "Device_Code_Name" to be \'Kindle\' (was \'' + browser['Device_Code_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Device_Brand_Name'], 'Amazon', 'Expected actual "Device_Brand_Name" to be \'Amazon\' (was \'' + browser['Device_Brand_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['RenderingEngine_Name'], 'NetFront', 'Expected actual "RenderingEngine_Name" to be \'NetFront\' (was \'' + browser['RenderingEngine_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['RenderingEngine_Version'], 'unknown', 'Expected actual "RenderingEngine_Version" to be \'unknown\' (was \'' + browser['RenderingEngine_Version'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['RenderingEngine_Maker'], 'Access', 'Expected actual "RenderingEngine_Maker" to be \'Access\' (was \'' + browser['RenderingEngine_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
});
test('issue-1442-B ["SonyEricssonJ10i2/R7CA Browser/NetFront/3.5 Profile/MIDP-2.1 Configuration/CLDC-1.1 JavaPlatform/JP-8.5.2"]', function () {
const browscap = new Browscap();
const browser = browscap.getBrowser('SonyEricssonJ10i2/R7CA Browser/NetFront/3.5 Profile/MIDP-2.1 Configuration/CLDC-1.1 JavaPlatform/JP-8.5.2');
assert.strictEqual(browser['Comment'], 'Access NetFront 3.5', 'Expected actual "Comment" to be \'Access NetFront 3.5\' (was \'' + browser['Comment'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Browser'], 'NetFront', 'Expected actual "Browser" to be \'NetFront\' (was \'' + browser['Browser'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Browser_Type'], 'Browser', 'Expected actual "Browser_Type" to be \'Browser\' (was \'' + browser['Browser_Type'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Browser_Bits'], '0', 'Expected actual "Browser_Bits" to be \'0\' (was \'' + browser['Browser_Bits'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Browser_Maker'], 'Access', 'Expected actual "Browser_Maker" to be \'Access\' (was \'' + browser['Browser_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Browser_Modus'], 'unknown', 'Expected actual "Browser_Modus" to be \'unknown\' (was \'' + browser['Browser_Modus'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Version'], '3.5', 'Expected actual "Version" to be \'3.5\' (was \'' + browser['Version'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Platform'], 'unknown', 'Expected actual "Platform" to be \'unknown\' (was \'' + browser['Platform'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Platform_Version'], 'unknown', 'Expected actual "Platform_Version" to be \'unknown\' (was \'' + browser['Platform_Version'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Platform_Description'], 'unknown', 'Expected actual "Platform_Description" to be \'unknown\' (was \'' + browser['Platform_Description'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Platform_Bits'], '0', 'Expected actual "Platform_Bits" to be \'0\' (was \'' + browser['Platform_Bits'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Platform_Maker'], 'unknown', 'Expected actual "Platform_Maker" to be \'unknown\' (was \'' + browser['Platform_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Alpha'], false, 'Expected actual "Alpha" to be false (was \'' + browser['Alpha'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Beta'], false, 'Expected actual "Beta" to be false (was \'' + browser['Beta'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Frames'], true, 'Expected actual "Frames" to be true (was \'' + browser['Frames'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['IFrames'], true, 'Expected actual "IFrames" to be true (was \'' + browser['IFrames'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Tables'], true, 'Expected actual "Tables" to be true (was \'' + browser['Tables'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Cookies'], true, 'Expected actual "Cookies" to be true (was \'' + browser['Cookies'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['JavaScript'], true, 'Expected actual "JavaScript" to be true (was \'' + browser['JavaScript'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['VBScript'], false, 'Expected actual "VBScript" to be false (was \'' + browser['VBScript'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['JavaApplets'], false, 'Expected actual "JavaApplets" to be false (was \'' + browser['JavaApplets'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['isSyndicationReader'], false, 'Expected actual "isSyndicationReader" to be false (was \'' + browser['isSyndicationReader'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['isFake'], false, 'Expected actual "isFake" to be false (was \'' + browser['isFake'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['isAnonymized'], false, 'Expected actual "isAnonymized" to be false (was \'' + browser['isAnonymized'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['isModified'], false, 'Expected actual "isModified" to be false (was \'' + browser['isModified'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['CssVersion'], '2', 'Expected actual "CssVersion" to be \'2\' (was \'' + browser['CssVersion'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Device_Name'], 'Elm', 'Expected actual "Device_Name" to be \'Elm\' (was \'' + browser['Device_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Device_Maker'], 'SonyEricsson', 'Expected actual "Device_Maker" to be \'SonyEricsson\' (was \'' + browser['Device_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Device_Type'], 'Mobile Phone', 'Expected actual "Device_Type" to be \'Mobile Phone\' (was \'' + browser['Device_Type'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Device_Pointing_Method'], 'unknown', 'Expected actual "Device_Pointing_Method" to be \'unknown\' (was \'' + browser['Device_Pointing_Method'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Device_Code_Name'], 'J10i2', 'Expected actual "Device_Code_Name" to be \'J10i2\' (was \'' + browser['Device_Code_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['Device_Brand_Name'], 'SonyEricsson', 'Expected actual "Device_Brand_Name" to be \'SonyEricsson\' (was \'' + browser['Device_Brand_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['RenderingEngine_Name'], 'NetFront', 'Expected actual "RenderingEngine_Name" to be \'NetFront\' (was \'' + browser['RenderingEngine_Name'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['RenderingEngine_Version'], 'unknown', 'Expected actual "RenderingEngine_Version" to be \'unknown\' (was \'' + browser['RenderingEngine_Version'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
assert.strictEqual(browser['RenderingEngine_Maker'], 'Access', 'Expected actual "RenderingEngine_Maker" to be \'Access\' (was \'' + browser['RenderingEngine_Maker'] + '\'; used pattern: ' + browser['browser_name_regex'] + ')');
});
});
| mit |
C2FO/comb | test/base/regexp.test.js | 1301 | "use strict";
var it = require('it'),
assert = require('assert'),
comb = require("../../index");
it.describe("comb/base/regexp.js", function (it) {
//Super of other classes
it.should("escape it properly", function () {
var chars = [".", "$", "?", "*", "|", "{", "}", "(", ")", "[", "]", "\\", "/", "+", "^"];
chars.forEach(function (c) {
assert.equal(comb.regexp.escapeString(c), "\\" + c);
assert.equal(comb(c).escape(), "\\" + c);
});
chars.forEach(function (c) {
assert.equal(comb(c).escape([c]), c);
});
});
it.should("determine if something is a RegExp", function () {
assert.isTrue(comb.isRexExp(/a/));
assert.isTrue(comb.isRexExp(new RegExp("a")));
assert.isFalse(comb.isRexExp());
assert.isFalse(comb.isRexExp(""));
assert.isFalse(comb.isRexExp(1));
assert.isFalse(comb.isRexExp(false));
assert.isFalse(comb.isRexExp(true));
assert.isTrue(comb(/a/).isRegExp());
assert.isTrue(comb(new RegExp("a")).isRegExp());
assert.isFalse(comb("").isRegExp());
assert.isFalse(comb(1).isRegExp());
assert.isFalse(comb(false).isRegExp());
assert.isFalse(comb(true).isRegExp());
});
}).as(module); | mit |
Repugnus/halftest | guns.lua | 6253 | bullet = {
{"halftest:bullet","halftest:smg1_bullet", "halftest:9mm_bullet_entity", "halftest:smg1_bullet_entity", "halftest:9mm_clip", "halftest:smg1_clip", "halftest:spas12_bullet_entity", "halftest:spas12_shell"},
}
local halftest_shoot_bullet = function(itemstack, player)
for _,bullet in ipairs(bullet) do
if player:get_inventory():get_stack("main", player:get_wield_index()+1):get_name() == bullet[5] then
if not minetest.setting_getbool("creative_mode") then
player:get_inventory():remove_item("main", bullet[5])
end
local playerpos = player:getpos()
local obj = minetest.add_entity({x=playerpos.x,y=playerpos.y+1.5,z=playerpos.z}, bullet[3])
local dir = player:get_look_dir()
obj:setvelocity({x=dir.x*19, y=dir.y*19, z=dir.z*19})
obj:setacceleration({x=dir.x, y=dir.y, z=dir.z})
obj:setyaw(player:get_look_yaw()+math.pi)
minetest.sound_play("halftest_9mm_shoot", {pos=playerpos})
if obj:get_luaentity().player == "" then
obj:get_luaentity().player = player
end
obj:get_luaentity().node = player:get_inventory():get_stack("main", 1):get_name()
return true
end
end
return false
end
local halftest_shoot_bullets = function(itemstack, player)
for _,bullet in ipairs(bullet) do
if player:get_inventory():get_stack("main", player:get_wield_index()+1):get_name() == bullet[6] then
if not minetest.setting_getbool("creative_mode") then
player:get_inventory():remove_item("main", bullet[6])
end
local playerpos = player:getpos()
local obj = minetest.add_entity({x=playerpos.x,y=playerpos.y+1.5,z=playerpos.z}, bullet[4])
local obj1 = minetest.add_entity({x=playerpos.x,y=playerpos.y+1.5,z=playerpos.z}, bullet[4])
local obj2 = minetest.add_entity({x=playerpos.x,y=playerpos.y+1.5,z=playerpos.z}, bullet[4])
local dir = player:get_look_dir()
minetest.sound_play("halftest_smg1_shoot", {pos=playerpos})
obj:setvelocity({x=dir.x*20, y=dir.y*20, z=dir.z*20})
obj:setacceleration({x=dir.x, y=dir.y, z=dir.z})
obj:setyaw(player:get_look_yaw()+math.pi)
minetest.after(.001, function()
obj1:setvelocity({x=dir.x*20, y=dir.y*20, z=dir.z*20})
obj1:setacceleration({x=dir.x, y=dir.y, z=dir.z})
obj1:setyaw(player:get_look_yaw()+math.pi)
minetest.after(.001, function()
obj2:setvelocity({x=dir.x*20, y=dir.y*20, z=dir.z*20})
obj2:setacceleration({x=dir.x, y=dir.y, z=dir.z})
obj2:setyaw(player:get_look_yaw()+math.pi)
end)
end)
if obj:get_luaentity().player == "" then
obj:get_luaentity().player = player
end
if obj1:get_luaentity().player == "" then
obj1:get_luaentity().player = player
end
if obj2:get_luaentity().player == "" then
obj2:get_luaentity().player = player
end
obj:get_luaentity().node = player:get_inventory():get_stack("main", 1):get_name()
obj1:get_luaentity().node = player:get_inventory():get_stack("main", 1):get_name()
obj2:get_luaentity().node = player:get_inventory():get_stack("main", 1):get_name()
return true
end
end
return false
end
local halftest_shoot_bullets1 = function(itemstack, player)
for _,bullet in ipairs(bullet) do
if player:get_inventory():get_stack("main", player:get_wield_index()+1):get_name() == bullet[8] then
if not minetest.setting_getbool("creative_mode") then
player:get_inventory():remove_item("main", bullet[8])
end
local playerpos = player:getpos()
local obj = minetest.add_entity({x=playerpos.x,y=playerpos.y+1.5,z=playerpos.z}, bullet[7])
local obj1 = minetest.add_entity({x=playerpos.x,y=playerpos.y+1.5,z=playerpos.z}, bullet[7])
local obj2 = minetest.add_entity({x=playerpos.x,y=playerpos.y+1.5,z=playerpos.z}, bullet[7])
local dir = player:get_look_dir()
minetest.sound_play("halftest_spas12_shoot", {pos=playerpos})
obj:setvelocity({x=dir.x*20, y=dir.y*20, z=dir.z*20})
obj:setacceleration({x=dir.x, y=dir.y+1, z=dir.z})
obj:setyaw(player:get_look_yaw()+math.pi)
obj1:setvelocity({x=dir.x*20, y=dir.y*20, z=dir.z*20})
obj1:setacceleration({x=dir.x+10, y=dir.y, z=dir.z})
obj1:setyaw(player:get_look_yaw()+math.pi)
obj2:setvelocity({x=dir.x*20, y=dir.y*20, z=dir.z*20})
obj2:setacceleration({x=dir.x, y=dir.y, z=dir.z-10})
obj2:setyaw(player:get_look_yaw()+math.pi)
if obj:get_luaentity().player == "" then
obj:get_luaentity().player = player
end
if obj1:get_luaentity().player == "" then
obj1:get_luaentity().player = player
end
if obj2:get_luaentity().player == "" then
obj2:get_luaentity().player = player
end
obj:get_luaentity().node = player:get_inventory():get_stack("main", 1):get_name()
obj1:get_luaentity().node = player:get_inventory():get_stack("main", 1):get_name()
obj2:get_luaentity().node = player:get_inventory():get_stack("main", 1):get_name()
return true
end
end
return false
end
minetest.register_node("halftest:9mm", {
description = "9mm",
drawtype = "mesh",
mesh = "gun.obj",
tiles = {name="default_steel_block.png"},
inventory_image = "halftest_9mm.png",
on_place = function(itemstack, placer, pointed_thing)
if minetest.get_node(pointed_thing.under).name == "default:chest_locked" then
minetest.item_place(itemstack, placer, pointed_thing, param2)
end
end,
on_use = function(itemstack, user, pointed_thing)
if halftest_shoot_bullet(item, user, pointed_thing) then
if not minetest.setting_getbool("creative_mode") then
itemstack:add_wear(65535/200)
end
end
return itemstack
end,
node_placement_prediction = "",
})
minetest.register_craftitem("halftest:smg1", {
description = "SMG1",
inventory_image = "halftest_smg1.png",
stack_max = 1,
on_use = function(itemstack, user, pointed_thing)
if halftest_shoot_bullets(item, user, pointed_thing) then
if not minetest.setting_getbool("creative_mode") then
itemstack:add_wear(65535/200)
end
end
return itemstack
end,
})
minetest.register_craftitem("halftest:spas12", {
description = "SPAS12",
inventory_image = "halftest_spas12.png",
stack_max = 1,
on_use = function(itemstack, user, pointed_thing)
if halftest_shoot_bullets1(item, user, pointed_thing) then
if not minetest.setting_getbool("creative_mode") then
itemstack:add_wear(65535/200)
end
end
return itemstack
end,
})
| mit |
devcycle/devcycle.github.io | vendor/bundle/gems/tzinfo-data-1.2019.3/lib/tzinfo/data/definitions/Europe/Madrid.rb | 13551 | # encoding: UTF-8
# This file contains data derived from the IANA Time Zone Database
# (http://www.iana.org/time-zones).
module TZInfo
module Data
module Definitions
module Europe
module Madrid
include TimezoneDefinition
timezone 'Europe/Madrid' do |tz|
tz.offset :o0, -884, 0, :LMT
tz.offset :o1, 0, 0, :WET
tz.offset :o2, 0, 3600, :WEST
tz.offset :o3, 0, 7200, :WEMT
tz.offset :o4, 3600, 0, :CET
tz.offset :o5, 3600, 3600, :CEST
tz.transition 1901, 1, :o1, -2177452800, 4830771, 2
tz.transition 1918, 4, :o2, -1631926800, 58120787, 24
tz.transition 1918, 10, :o1, -1616889600, 4843747, 2
tz.transition 1919, 4, :o2, -1601168400, 58129331, 24
tz.transition 1919, 10, :o1, -1585353600, 4844477, 2
tz.transition 1924, 4, :o2, -1442451600, 58173419, 24
tz.transition 1924, 10, :o1, -1427673600, 4848127, 2
tz.transition 1926, 4, :o2, -1379293200, 58190963, 24
tz.transition 1926, 10, :o1, -1364774400, 4849583, 2
tz.transition 1927, 4, :o2, -1348448400, 58199531, 24
tz.transition 1927, 10, :o1, -1333324800, 4850311, 2
tz.transition 1928, 4, :o2, -1316390400, 4850703, 2
tz.transition 1928, 10, :o1, -1301270400, 4851053, 2
tz.transition 1929, 4, :o2, -1284339600, 58217339, 24
tz.transition 1929, 10, :o1, -1269820800, 4851781, 2
tz.transition 1937, 6, :o2, -1026954000, 58288835, 24
tz.transition 1937, 10, :o1, -1017619200, 4857619, 2
tz.transition 1938, 4, :o2, -1001898000, 58295795, 24
tz.transition 1938, 4, :o3, -999482400, 29148233, 12
tz.transition 1938, 10, :o2, -986090400, 29150093, 12
tz.transition 1939, 10, :o1, -954115200, 4859089, 2
tz.transition 1940, 3, :o4, -940208400, 58312931, 24
tz.transition 1942, 5, :o5, -873079200, 29165789, 12
tz.transition 1942, 8, :o4, -862621200, 58334483, 24
tz.transition 1943, 4, :o5, -842839200, 29169989, 12
tz.transition 1943, 10, :o4, -828320400, 58344011, 24
tz.transition 1944, 4, :o5, -811389600, 29174357, 12
tz.transition 1944, 9, :o4, -796870800, 58352747, 24
tz.transition 1945, 4, :o5, -779940000, 29178725, 12
tz.transition 1945, 9, :o4, -765421200, 58361483, 24
tz.transition 1946, 4, :o5, -748490400, 29183093, 12
tz.transition 1946, 9, :o4, -733971600, 58370219, 24
tz.transition 1949, 4, :o5, -652327200, 29196449, 12
tz.transition 1949, 10, :o4, -639018000, 58396595, 24
tz.transition 1974, 4, :o5, 135122400
tz.transition 1974, 10, :o4, 150246000
tz.transition 1975, 4, :o5, 166572000
tz.transition 1975, 10, :o4, 181695600
tz.transition 1976, 3, :o5, 196812000
tz.transition 1976, 9, :o4, 212540400
tz.transition 1977, 4, :o5, 228866400
tz.transition 1977, 9, :o4, 243990000
tz.transition 1978, 4, :o5, 260326800
tz.transition 1978, 10, :o4, 276051600
tz.transition 1979, 4, :o5, 291776400
tz.transition 1979, 9, :o4, 307501200
tz.transition 1980, 4, :o5, 323830800
tz.transition 1980, 9, :o4, 338950800
tz.transition 1981, 3, :o5, 354675600
tz.transition 1981, 9, :o4, 370400400
tz.transition 1982, 3, :o5, 386125200
tz.transition 1982, 9, :o4, 401850000
tz.transition 1983, 3, :o5, 417574800
tz.transition 1983, 9, :o4, 433299600
tz.transition 1984, 3, :o5, 449024400
tz.transition 1984, 9, :o4, 465354000
tz.transition 1985, 3, :o5, 481078800
tz.transition 1985, 9, :o4, 496803600
tz.transition 1986, 3, :o5, 512528400
tz.transition 1986, 9, :o4, 528253200
tz.transition 1987, 3, :o5, 543978000
tz.transition 1987, 9, :o4, 559702800
tz.transition 1988, 3, :o5, 575427600
tz.transition 1988, 9, :o4, 591152400
tz.transition 1989, 3, :o5, 606877200
tz.transition 1989, 9, :o4, 622602000
tz.transition 1990, 3, :o5, 638326800
tz.transition 1990, 9, :o4, 654656400
tz.transition 1991, 3, :o5, 670381200
tz.transition 1991, 9, :o4, 686106000
tz.transition 1992, 3, :o5, 701830800
tz.transition 1992, 9, :o4, 717555600
tz.transition 1993, 3, :o5, 733280400
tz.transition 1993, 9, :o4, 749005200
tz.transition 1994, 3, :o5, 764730000
tz.transition 1994, 9, :o4, 780454800
tz.transition 1995, 3, :o5, 796179600
tz.transition 1995, 9, :o4, 811904400
tz.transition 1996, 3, :o5, 828234000
tz.transition 1996, 10, :o4, 846378000
tz.transition 1997, 3, :o5, 859683600
tz.transition 1997, 10, :o4, 877827600
tz.transition 1998, 3, :o5, 891133200
tz.transition 1998, 10, :o4, 909277200
tz.transition 1999, 3, :o5, 922582800
tz.transition 1999, 10, :o4, 941331600
tz.transition 2000, 3, :o5, 954032400
tz.transition 2000, 10, :o4, 972781200
tz.transition 2001, 3, :o5, 985482000
tz.transition 2001, 10, :o4, 1004230800
tz.transition 2002, 3, :o5, 1017536400
tz.transition 2002, 10, :o4, 1035680400
tz.transition 2003, 3, :o5, 1048986000
tz.transition 2003, 10, :o4, 1067130000
tz.transition 2004, 3, :o5, 1080435600
tz.transition 2004, 10, :o4, 1099184400
tz.transition 2005, 3, :o5, 1111885200
tz.transition 2005, 10, :o4, 1130634000
tz.transition 2006, 3, :o5, 1143334800
tz.transition 2006, 10, :o4, 1162083600
tz.transition 2007, 3, :o5, 1174784400
tz.transition 2007, 10, :o4, 1193533200
tz.transition 2008, 3, :o5, 1206838800
tz.transition 2008, 10, :o4, 1224982800
tz.transition 2009, 3, :o5, 1238288400
tz.transition 2009, 10, :o4, 1256432400
tz.transition 2010, 3, :o5, 1269738000
tz.transition 2010, 10, :o4, 1288486800
tz.transition 2011, 3, :o5, 1301187600
tz.transition 2011, 10, :o4, 1319936400
tz.transition 2012, 3, :o5, 1332637200
tz.transition 2012, 10, :o4, 1351386000
tz.transition 2013, 3, :o5, 1364691600
tz.transition 2013, 10, :o4, 1382835600
tz.transition 2014, 3, :o5, 1396141200
tz.transition 2014, 10, :o4, 1414285200
tz.transition 2015, 3, :o5, 1427590800
tz.transition 2015, 10, :o4, 1445734800
tz.transition 2016, 3, :o5, 1459040400
tz.transition 2016, 10, :o4, 1477789200
tz.transition 2017, 3, :o5, 1490490000
tz.transition 2017, 10, :o4, 1509238800
tz.transition 2018, 3, :o5, 1521939600
tz.transition 2018, 10, :o4, 1540688400
tz.transition 2019, 3, :o5, 1553994000
tz.transition 2019, 10, :o4, 1572138000
tz.transition 2020, 3, :o5, 1585443600
tz.transition 2020, 10, :o4, 1603587600
tz.transition 2021, 3, :o5, 1616893200
tz.transition 2021, 10, :o4, 1635642000
tz.transition 2022, 3, :o5, 1648342800
tz.transition 2022, 10, :o4, 1667091600
tz.transition 2023, 3, :o5, 1679792400
tz.transition 2023, 10, :o4, 1698541200
tz.transition 2024, 3, :o5, 1711846800
tz.transition 2024, 10, :o4, 1729990800
tz.transition 2025, 3, :o5, 1743296400
tz.transition 2025, 10, :o4, 1761440400
tz.transition 2026, 3, :o5, 1774746000
tz.transition 2026, 10, :o4, 1792890000
tz.transition 2027, 3, :o5, 1806195600
tz.transition 2027, 10, :o4, 1824944400
tz.transition 2028, 3, :o5, 1837645200
tz.transition 2028, 10, :o4, 1856394000
tz.transition 2029, 3, :o5, 1869094800
tz.transition 2029, 10, :o4, 1887843600
tz.transition 2030, 3, :o5, 1901149200
tz.transition 2030, 10, :o4, 1919293200
tz.transition 2031, 3, :o5, 1932598800
tz.transition 2031, 10, :o4, 1950742800
tz.transition 2032, 3, :o5, 1964048400
tz.transition 2032, 10, :o4, 1982797200
tz.transition 2033, 3, :o5, 1995498000
tz.transition 2033, 10, :o4, 2014246800
tz.transition 2034, 3, :o5, 2026947600
tz.transition 2034, 10, :o4, 2045696400
tz.transition 2035, 3, :o5, 2058397200
tz.transition 2035, 10, :o4, 2077146000
tz.transition 2036, 3, :o5, 2090451600
tz.transition 2036, 10, :o4, 2108595600
tz.transition 2037, 3, :o5, 2121901200
tz.transition 2037, 10, :o4, 2140045200
tz.transition 2038, 3, :o5, 2153350800, 59172253, 24
tz.transition 2038, 10, :o4, 2172099600, 59177461, 24
tz.transition 2039, 3, :o5, 2184800400, 59180989, 24
tz.transition 2039, 10, :o4, 2203549200, 59186197, 24
tz.transition 2040, 3, :o5, 2216250000, 59189725, 24
tz.transition 2040, 10, :o4, 2234998800, 59194933, 24
tz.transition 2041, 3, :o5, 2248304400, 59198629, 24
tz.transition 2041, 10, :o4, 2266448400, 59203669, 24
tz.transition 2042, 3, :o5, 2279754000, 59207365, 24
tz.transition 2042, 10, :o4, 2297898000, 59212405, 24
tz.transition 2043, 3, :o5, 2311203600, 59216101, 24
tz.transition 2043, 10, :o4, 2329347600, 59221141, 24
tz.transition 2044, 3, :o5, 2342653200, 59224837, 24
tz.transition 2044, 10, :o4, 2361402000, 59230045, 24
tz.transition 2045, 3, :o5, 2374102800, 59233573, 24
tz.transition 2045, 10, :o4, 2392851600, 59238781, 24
tz.transition 2046, 3, :o5, 2405552400, 59242309, 24
tz.transition 2046, 10, :o4, 2424301200, 59247517, 24
tz.transition 2047, 3, :o5, 2437606800, 59251213, 24
tz.transition 2047, 10, :o4, 2455750800, 59256253, 24
tz.transition 2048, 3, :o5, 2469056400, 59259949, 24
tz.transition 2048, 10, :o4, 2487200400, 59264989, 24
tz.transition 2049, 3, :o5, 2500506000, 59268685, 24
tz.transition 2049, 10, :o4, 2519254800, 59273893, 24
tz.transition 2050, 3, :o5, 2531955600, 59277421, 24
tz.transition 2050, 10, :o4, 2550704400, 59282629, 24
tz.transition 2051, 3, :o5, 2563405200, 59286157, 24
tz.transition 2051, 10, :o4, 2582154000, 59291365, 24
tz.transition 2052, 3, :o5, 2595459600, 59295061, 24
tz.transition 2052, 10, :o4, 2613603600, 59300101, 24
tz.transition 2053, 3, :o5, 2626909200, 59303797, 24
tz.transition 2053, 10, :o4, 2645053200, 59308837, 24
tz.transition 2054, 3, :o5, 2658358800, 59312533, 24
tz.transition 2054, 10, :o4, 2676502800, 59317573, 24
tz.transition 2055, 3, :o5, 2689808400, 59321269, 24
tz.transition 2055, 10, :o4, 2708557200, 59326477, 24
tz.transition 2056, 3, :o5, 2721258000, 59330005, 24
tz.transition 2056, 10, :o4, 2740006800, 59335213, 24
tz.transition 2057, 3, :o5, 2752707600, 59338741, 24
tz.transition 2057, 10, :o4, 2771456400, 59343949, 24
tz.transition 2058, 3, :o5, 2784762000, 59347645, 24
tz.transition 2058, 10, :o4, 2802906000, 59352685, 24
tz.transition 2059, 3, :o5, 2816211600, 59356381, 24
tz.transition 2059, 10, :o4, 2834355600, 59361421, 24
tz.transition 2060, 3, :o5, 2847661200, 59365117, 24
tz.transition 2060, 10, :o4, 2866410000, 59370325, 24
tz.transition 2061, 3, :o5, 2879110800, 59373853, 24
tz.transition 2061, 10, :o4, 2897859600, 59379061, 24
tz.transition 2062, 3, :o5, 2910560400, 59382589, 24
tz.transition 2062, 10, :o4, 2929309200, 59387797, 24
tz.transition 2063, 3, :o5, 2942010000, 59391325, 24
tz.transition 2063, 10, :o4, 2960758800, 59396533, 24
tz.transition 2064, 3, :o5, 2974064400, 59400229, 24
tz.transition 2064, 10, :o4, 2992208400, 59405269, 24
tz.transition 2065, 3, :o5, 3005514000, 59408965, 24
tz.transition 2065, 10, :o4, 3023658000, 59414005, 24
tz.transition 2066, 3, :o5, 3036963600, 59417701, 24
tz.transition 2066, 10, :o4, 3055712400, 59422909, 24
tz.transition 2067, 3, :o5, 3068413200, 59426437, 24
tz.transition 2067, 10, :o4, 3087162000, 59431645, 24
tz.transition 2068, 3, :o5, 3099862800, 59435173, 24
tz.transition 2068, 10, :o4, 3118611600, 59440381, 24
tz.transition 2069, 3, :o5, 3131917200, 59444077, 24
tz.transition 2069, 10, :o4, 3150061200, 59449117, 24
end
end
end
end
end
end
| mit |
ZhaoJianQiu/TurScript | src/vm/CmdType.java | 697 | package vm;
public enum CmdType {
NOP, // 空指令
HALT, // 关闭虚拟机
POP, // 弹出栈顶元素
POPN, // 弹出栈顶N个元素
OPTR, // 执行计算
LOAD_CONST, // 加载常量
LOAD_NULL, // 加载NULL
NEW_VAR, // 创建变量
SET_VAR, // 赋值变量
LOAD_VAR, // 加载变量
CALL, // 调用函数
TEST, // 真值跳转
JMP, // 无条件跳转
JMP_BACK, // 向后无条件跳转
LOAD_TRUE, // 加载TRUE
LOAD_FALSE, // 加载FALSE
SET_RET_VAL, // 设置返回值
RET, // 函数返回
LOAD_LOCAL, // 加载局部变量
NEW_LOCAL, // 在栈上新建局部变量,函数结束后栈内有关该函数的元素全部会被弹出
SET_LOCAL, // 赋值局部变量
}
| mit |
Kononnable/typeorm-model-generator | test/integration/entityTypes/mssql/entity/Post.ts | 1655 | import { Entity, PrimaryColumn, Column } from "typeorm";
@Entity("Post")
export class Post {
@PrimaryColumn()
id: number;
@Column()
name: string;
@Column("bigint")
bigint: string;
@Column("bit")
bit: boolean;
@Column("decimal")
decimal: number;
@Column("int")
int: number;
@Column("money")
money: number;
@Column("numeric")
numeric: number;
@Column("smallint")
smallint: number;
@Column("smallmoney")
smallmoney: number;
@Column("tinyint")
tinyint: number;
@Column("float")
float: number;
@Column("real")
real: number;
@Column("date")
dateObj: Date;
@Column("datetime2")
datetime2: Date;
@Column("datetime")
datetime: Date;
@Column("datetimeoffset")
datetimeoffset: Date;
@Column("smalldatetime")
smalldatetime: Date;
@Column("time")
timeObj: Date;
@Column("char")
char: string;
@Column("text")
text: string;
@Column("varchar")
varchar: string;
@Column("nchar")
nchar: string;
@Column("ntext")
ntext: string;
@Column("nvarchar")
nvarchar: string;
@Column("binary")
binary: Buffer;
@Column("image")
image: Buffer;
@Column("varbinary")
varbinary: Buffer;
@Column("hierarchyid")
hierarchyid: string;
@Column("sql_variant")
sqlVariant: string;
@Column("timestamp")
timestamp: Date;
@Column("uniqueidentifier")
uniqueidentifier: string;
@Column("xml")
xml: string;
@Column("geometry")
geometry: string;
@Column("geography")
geography: string;
}
| mit |
cliffano/swaggy-jenkins | clients/cpp-tizen/generated/src/PipelineRunNode.cpp | 7694 | #include <map>
#include <cstdlib>
#include <glib-object.h>
#include <json-glib/json-glib.h>
#include "Helpers.h"
#include "PipelineRunNode.h"
using namespace std;
using namespace Tizen::ArtikCloud;
PipelineRunNode::PipelineRunNode()
{
//__init();
}
PipelineRunNode::~PipelineRunNode()
{
//__cleanup();
}
void
PipelineRunNode::__init()
{
//_class = std::string();
//displayName = std::string();
//durationInMillis = int(0);
//new std::list()std::list> edges;
//id = std::string();
//result = std::string();
//startTime = std::string();
//state = std::string();
}
void
PipelineRunNode::__cleanup()
{
//if(_class != NULL) {
//
//delete _class;
//_class = NULL;
//}
//if(displayName != NULL) {
//
//delete displayName;
//displayName = NULL;
//}
//if(durationInMillis != NULL) {
//
//delete durationInMillis;
//durationInMillis = NULL;
//}
//if(edges != NULL) {
//edges.RemoveAll(true);
//delete edges;
//edges = NULL;
//}
//if(id != NULL) {
//
//delete id;
//id = NULL;
//}
//if(result != NULL) {
//
//delete result;
//result = NULL;
//}
//if(startTime != NULL) {
//
//delete startTime;
//startTime = NULL;
//}
//if(state != NULL) {
//
//delete state;
//state = NULL;
//}
//
}
void
PipelineRunNode::fromJson(char* jsonStr)
{
JsonObject *pJsonObject = json_node_get_object(json_from_string(jsonStr,NULL));
JsonNode *node;
const gchar *_classKey = "_class";
node = json_object_get_member(pJsonObject, _classKey);
if (node !=NULL) {
if (isprimitive("std::string")) {
jsonToValue(&_class, node, "std::string", "");
} else {
}
}
const gchar *displayNameKey = "displayName";
node = json_object_get_member(pJsonObject, displayNameKey);
if (node !=NULL) {
if (isprimitive("std::string")) {
jsonToValue(&displayName, node, "std::string", "");
} else {
}
}
const gchar *durationInMillisKey = "durationInMillis";
node = json_object_get_member(pJsonObject, durationInMillisKey);
if (node !=NULL) {
if (isprimitive("int")) {
jsonToValue(&durationInMillis, node, "int", "");
} else {
}
}
const gchar *edgesKey = "edges";
node = json_object_get_member(pJsonObject, edgesKey);
if (node !=NULL) {
{
JsonArray* arr = json_node_get_array(node);
JsonNode* temp_json;
list<PipelineRunNodeedges> new_list;
PipelineRunNodeedges inst;
for (guint i=0;i<json_array_get_length(arr);i++) {
temp_json = json_array_get_element(arr,i);
if (isprimitive("PipelineRunNodeedges")) {
jsonToValue(&inst, temp_json, "PipelineRunNodeedges", "");
} else {
inst.fromJson(json_to_string(temp_json, false));
}
new_list.push_back(inst);
}
edges = new_list;
}
}
const gchar *idKey = "id";
node = json_object_get_member(pJsonObject, idKey);
if (node !=NULL) {
if (isprimitive("std::string")) {
jsonToValue(&id, node, "std::string", "");
} else {
}
}
const gchar *resultKey = "result";
node = json_object_get_member(pJsonObject, resultKey);
if (node !=NULL) {
if (isprimitive("std::string")) {
jsonToValue(&result, node, "std::string", "");
} else {
}
}
const gchar *startTimeKey = "startTime";
node = json_object_get_member(pJsonObject, startTimeKey);
if (node !=NULL) {
if (isprimitive("std::string")) {
jsonToValue(&startTime, node, "std::string", "");
} else {
}
}
const gchar *stateKey = "state";
node = json_object_get_member(pJsonObject, stateKey);
if (node !=NULL) {
if (isprimitive("std::string")) {
jsonToValue(&state, node, "std::string", "");
} else {
}
}
}
PipelineRunNode::PipelineRunNode(char* json)
{
this->fromJson(json);
}
char*
PipelineRunNode::toJson()
{
JsonObject *pJsonObject = json_object_new();
JsonNode *node;
if (isprimitive("std::string")) {
std::string obj = getClass();
node = converttoJson(&obj, "std::string", "");
}
else {
}
const gchar *_classKey = "_class";
json_object_set_member(pJsonObject, _classKey, node);
if (isprimitive("std::string")) {
std::string obj = getDisplayName();
node = converttoJson(&obj, "std::string", "");
}
else {
}
const gchar *displayNameKey = "displayName";
json_object_set_member(pJsonObject, displayNameKey, node);
if (isprimitive("int")) {
int obj = getDurationInMillis();
node = converttoJson(&obj, "int", "");
}
else {
}
const gchar *durationInMillisKey = "durationInMillis";
json_object_set_member(pJsonObject, durationInMillisKey, node);
if (isprimitive("PipelineRunNodeedges")) {
list<PipelineRunNodeedges> new_list = static_cast<list <PipelineRunNodeedges> > (getEdges());
node = converttoJson(&new_list, "PipelineRunNodeedges", "array");
} else {
node = json_node_alloc();
list<PipelineRunNodeedges> new_list = static_cast<list <PipelineRunNodeedges> > (getEdges());
JsonArray* json_array = json_array_new();
GError *mygerror;
for (list<PipelineRunNodeedges>::iterator it = new_list.begin(); it != new_list.end(); it++) {
mygerror = NULL;
PipelineRunNodeedges obj = *it;
JsonNode *node_temp = json_from_string(obj.toJson(), &mygerror);
json_array_add_element(json_array, node_temp);
g_clear_error(&mygerror);
}
json_node_init_array(node, json_array);
json_array_unref(json_array);
}
const gchar *edgesKey = "edges";
json_object_set_member(pJsonObject, edgesKey, node);
if (isprimitive("std::string")) {
std::string obj = getId();
node = converttoJson(&obj, "std::string", "");
}
else {
}
const gchar *idKey = "id";
json_object_set_member(pJsonObject, idKey, node);
if (isprimitive("std::string")) {
std::string obj = getResult();
node = converttoJson(&obj, "std::string", "");
}
else {
}
const gchar *resultKey = "result";
json_object_set_member(pJsonObject, resultKey, node);
if (isprimitive("std::string")) {
std::string obj = getStartTime();
node = converttoJson(&obj, "std::string", "");
}
else {
}
const gchar *startTimeKey = "startTime";
json_object_set_member(pJsonObject, startTimeKey, node);
if (isprimitive("std::string")) {
std::string obj = getState();
node = converttoJson(&obj, "std::string", "");
}
else {
}
const gchar *stateKey = "state";
json_object_set_member(pJsonObject, stateKey, node);
node = json_node_alloc();
json_node_init(node, JSON_NODE_OBJECT);
json_node_take_object(node, pJsonObject);
char * ret = json_to_string(node, false);
json_node_free(node);
return ret;
}
std::string
PipelineRunNode::getClass()
{
return _class;
}
void
PipelineRunNode::setClass(std::string _class)
{
this->_class = _class;
}
std::string
PipelineRunNode::getDisplayName()
{
return displayName;
}
void
PipelineRunNode::setDisplayName(std::string displayName)
{
this->displayName = displayName;
}
int
PipelineRunNode::getDurationInMillis()
{
return durationInMillis;
}
void
PipelineRunNode::setDurationInMillis(int durationInMillis)
{
this->durationInMillis = durationInMillis;
}
std::list<PipelineRunNodeedges>
PipelineRunNode::getEdges()
{
return edges;
}
void
PipelineRunNode::setEdges(std::list <PipelineRunNodeedges> edges)
{
this->edges = edges;
}
std::string
PipelineRunNode::getId()
{
return id;
}
void
PipelineRunNode::setId(std::string id)
{
this->id = id;
}
std::string
PipelineRunNode::getResult()
{
return result;
}
void
PipelineRunNode::setResult(std::string result)
{
this->result = result;
}
std::string
PipelineRunNode::getStartTime()
{
return startTime;
}
void
PipelineRunNode::setStartTime(std::string startTime)
{
this->startTime = startTime;
}
std::string
PipelineRunNode::getState()
{
return state;
}
void
PipelineRunNode::setState(std::string state)
{
this->state = state;
}
| mit |
coldspire/OrgByDate | Program.cs | 427 | using System;
using System.Windows.Forms;
namespace OrgByDate
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
| mit |
chinemelu/BC_28-more_recipes_v2 | server/models/review.js | 636 | module.exports = (sequelize, DataTypes) => {
const Review = sequelize.define('Review', {
title: {
type: DataTypes.STRING,
allowNull: false
},
message: {
type: DataTypes.TEXT,
allowNull: false
},
userId: {
type: DataTypes.INTEGER,
allowNull: false
},
recipeId: {
type: DataTypes.INTEGER,
allowNull: false
}
});
Review.associate = (models) => {
Review.belongsTo(models.User, {
foreignKey: 'userId'
});
Review.belongsTo(models.Recipe, {
foreignKey: 'recipeId',
onDelete: 'CASCADE'
});
};
return Review;
};
| mit |
ssqsignon/ssqsignon-proxy | dotnet/nancyfx/SSQSignonProxyNancyFx/AuthProxyModule.cs | 7884 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Nancy.ModelBinding;
using RestSharp;
namespace SSQSignon
{
public abstract class AuthProxyModule : Nancy.NancyModule
{
public AuthProxyModule(string path, string moduleName, string clientId, string clientSecret, bool detectGrantType = true)
{
if (string.IsNullOrEmpty(path))
{
throw new ArgumentNullException("path");
}
if (string.IsNullOrEmpty(moduleName))
{
throw new ArgumentNullException("moduleName");
}
if (string.IsNullOrEmpty(clientId))
{
throw new ArgumentNullException("clientId");
}
var restClient = new RestClient(string.Format("https://ssqsignon.com/{0}", moduleName));
if (!string.IsNullOrEmpty(clientSecret))
{
restClient.Authenticator = new RestSharp.Authenticators.HttpBasicAuthenticator(clientId, clientSecret);
}
Post[string.Format("{0}/auth", path)] = _ =>
{
try
{
var request = this.Bind<AuthRequest>();
return Auth(restClient, request, clientId, detectGrantType);
}
catch (Nancy.ModelBinding.ModelBindingException)
{
return Send(Nancy.HttpStatusCode.BadRequest, new { error = "request_body_invalid" });
}
};
Get[string.Format("{0}/whoami", path)] = _ =>
{
return WhoAmI(restClient);
};
Get[string.Format("{0}/saferedirect", path)] = _ =>
{
return SafeRedirect(restClient, Request.Query.response_type, Request.Query.redirect_uri, Request.Query.client_id, Request.Query.state, Request.Query.scope, Request.Query.deny_access);
};
Delete[string.Format("{0}/{{userid}}/tokens", path)] = _ =>
{
return NullifyTokens(restClient, _.userid);
};
}
protected class AuthRequest
{
public string grant_type { get; set; }
public string client_id { get; set; }
public string code { get; set; }
public string redirect_uri { get; set; }
public string username { get; set; }
public string password { get; set; }
public string refresh_token { get; set; }
public string scope { get; set; }
public string client_secret { get; set; }
}
protected virtual dynamic WhoAmI(RestClient restClient)
{
var request = new RestRequest("whoami", Method.GET);
CopyAuthorizationHeader(request);
return Proxy(restClient, request);
}
protected virtual dynamic SafeRedirect(RestClient restClient, string response_type, string redirectUri, string clientId, string state, string scope, bool denyAccess)
{
var request = new RestRequest("saferedirect", Method.GET);
CopyAuthorizationHeader(request);
request.Parameters.Add(new Parameter { Type = ParameterType.QueryString, Name = "response_type", Value = string.IsNullOrEmpty(response_type) ? "code" : response_type });
request.Parameters.Add(new Parameter { Type = ParameterType.QueryString, Name = "deny_access", Value = denyAccess });
if (!string.IsNullOrEmpty(redirectUri))
{
request.Parameters.Add(new Parameter { Type = ParameterType.QueryString, Name = "redirect_uri", Value = redirectUri });
}
if (!string.IsNullOrEmpty(clientId))
{
request.Parameters.Add(new Parameter { Type = ParameterType.QueryString, Name = "client_id", Value = clientId });
}
if (!string.IsNullOrEmpty(state))
{
request.Parameters.Add(new Parameter { Type = ParameterType.QueryString, Name = "state", Value = state });
}
if (!string.IsNullOrEmpty(scope))
{
request.Parameters.Add(new Parameter { Type = ParameterType.QueryString, Name = "scope", Value = scope });
}
return Proxy(restClient, request);
}
protected virtual dynamic Auth(RestClient restClient, AuthRequest model, string clientId, bool detectGrantType)
{
var request = new RestRequest("auth", Method.POST);
if (string.IsNullOrEmpty(model.client_id))
{
model.client_id = clientId;
}
if (string.IsNullOrEmpty(model.grant_type) && detectGrantType)
{
model.grant_type = DetectGrantType(model);
}
request.AddJsonBody(model);
return Proxy(restClient, request);
}
protected virtual dynamic NullifyTokens(RestClient restClient, string userid)
{
var request = new RestRequest(string.Format("{0}/tokens", userid), Method.DELETE);
CopyAuthorizationHeader(request);
return Proxy(restClient, request);
}
protected virtual dynamic Proxy(RestClient restClient, RestRequest request)
{
var response = restClient.Execute(request);
if (response.ErrorException == null && !string.IsNullOrEmpty(response.Content))
{
return Send((Nancy.HttpStatusCode)response.StatusCode, new System.Net.Mime.ContentType(response.ContentType).MediaType, response.Content);
}
else if (response.ErrorException == null)
{
return (Nancy.HttpStatusCode)response.StatusCode;
}
else
{
return Send(Nancy.HttpStatusCode.InternalServerError, new { reason = response.ErrorException.Message });
}
}
protected virtual Nancy.Response Send(Nancy.HttpStatusCode status, string contentType, string content)
{
return new Nancy.Response
{
StatusCode = status,
ContentType = new System.Net.Mime.ContentType(contentType).MediaType,
Contents = res =>
{
using (var writer = new System.IO.StreamWriter(res))
{
writer.Write(content);
}
}
};
}
protected virtual Nancy.Response Send(Nancy.HttpStatusCode status, dynamic content)
{
return Send(status, "application/json", Newtonsoft.Json.JsonConvert.SerializeObject(content));
}
protected virtual Nancy.Response Send(Nancy.HttpStatusCode status, string content)
{
return Send(status, "text/plain; charset=utf-8", content);
}
protected virtual void CopyAuthorizationHeader(RestRequest request)
{
Request.Headers
.Where(h => h.Key.Equals("authorization", StringComparison.InvariantCultureIgnoreCase))
.ToList()
.ForEach(h => h.Value.ToList().ForEach(v => request.AddHeader("Authorization", v)));
}
protected virtual string DetectGrantType(AuthRequest model)
{
if (!string.IsNullOrEmpty(model.username) || !string.IsNullOrEmpty(model.password))
{
return "password";
}
if (!string.IsNullOrEmpty(model.code))
{
return "authorization_code";
}
if (!string.IsNullOrEmpty(model.refresh_token))
{
return "refresh_token";
}
return null;
}
}
} | mit |
glav/CognitiveServicesFluentApi | Glav.CognitiveServices.FluentApi.Face/Domain/LargePersonGroupPerson/LargePersonGroupPersonDeleteAnalysisContext.cs | 1298 | using Glav.CognitiveServices.FluentApi.Core.Contracts;
using Glav.CognitiveServices.FluentApi.Core.Configuration;
using Glav.CognitiveServices.FluentApi.Core.ScoreEvaluation;
using System.Collections.Generic;
using Glav.CognitiveServices.FluentApi.Core.Communication;
using System.Linq;
namespace Glav.CognitiveServices.FluentApi.Face.Domain.LargePersonGroupPerson
{
public class LargePersonGroupPersonDeleteAnalysisContext : BaseApiAnalysisContext<LargePersonGroupPersonDeleteResult, BaseApiErrorResponse, double>
{
public LargePersonGroupPersonDeleteAnalysisContext(ApiActionDataCollection actionData, LargePersonGroupPersonDeleteResult analysisResult)
: base(actionData, analysisResult, new NumericScoreEvaluationEngine(new DefaultScoreLevels()))
{
}
public LargePersonGroupPersonDeleteAnalysisContext(ApiActionDataCollection actionData, IScoreEvaluationEngine<double> scoringEngine)
: base(actionData, scoringEngine)
{
}
public override ApiActionDefinition AnalysisType => FaceApiOperations.LargePersonGroupPersonDelete;
public override IEnumerable<BaseApiErrorResponse> GetAllErrors()
{
return AnalysisResults.Select(e => e.ResponseData.error);
}
}
}
| mit |
thebravoman/software_engineering_2016 | c04/B_11_Daniel_Tuechki.rb | 333 | require 'csv'
path_to_file = ARGV[0].to_s
user = []
video = []
count = []
CSV.foreach(File.path(path_to_file)) do |row|
user << row[0].to_i
video << row[1].to_i
count << row[2].to_f
end
task_1 = Hash.new
i = 0
sum = 0
video.each do |every_video|
sum = sum + count[i]
task_1[every_video] = sum
end
puts task_1
| mit |
vlsi1217/leetlint | src/nineChap6_LL/MergeKsortList.java | 2067 | package nineChap6_LL;
import misc.ListNode;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;
public class MergeKsortList {
public ListNode mergeKLists(List<ListNode> lists) {
// write your code here
int[] arr1 = new int[] {1, 4, 10, 12, 100};
int[] arr2 = new int[] {0, 2, 3, 5, 88};
int[] arr3 = new int[] {6, 7, 8, 9};
ListNode l1 = ListNode.buildList(arr1);
ListNode l2 = ListNode.buildList(arr2);
ListNode l3 = ListNode.buildList(arr3);
List<ListNode> heads = new ArrayList<>();
heads.add(l1);
heads.add(l2);
heads.add(l3);
ListNode ans = merge(heads);
return ans;
}
public static ListNode merge(List<ListNode> lists) {
Comparator<ListNode> listCmptr = new Comparator<ListNode>() {
public int compare(ListNode lhs, ListNode rhs) {
if (lhs == null) {
return -1;
}
else if (rhs == null) {
return 1;
}
return lhs.val - rhs.val;
}
};
// this is how to instantiate a priority queue: PriorityQueue(int initialCapacity, Comparator<? super E> comparator)
Queue<ListNode> minPQ = new PriorityQueue<ListNode>(listCmptr);
for (int i = 0; i < lists.size(); ++i ){ // simple traverse lists
if (lists.get(i) != null) {
minPQ.add(lists.get(i));
}
}
ListNode dummy = new ListNode(0);
// while (!minPQ.isEmpty()) {
// ListNode min = minPQ.poll();
//
// minPQ.add(min.next);
// dummy.next = min;
// }
ListNode tail = dummy;
while (!minPQ.isEmpty()) {
ListNode min = minPQ.poll();
tail.next = min;
tail = tail.next;
if (tail.next != null) {
minPQ.add(tail.next);
}
}
return dummy.next;
}
public MergeKsortList() {
ListNode test = mergeKLists(null);
ListNode.printList(test);
}
public static void main(String[] args) {
MergeKsortList mksl = new MergeKsortList();
}
}
| mit |
milkokochev/Telerik | C#1/HomeWorks/05. Conditional Statements/Digit as Word/DigitWords.cs | 1045 | //Write a program that asks for a digit (0-9), and depending on the input, shows the digit as a word (in English).
//Print “not a digit” in case of invalid input.
//Use a switch statement.
using System;
class DigitWords
{
static void Main()
{
Console.Write("Enter digit 0-9:");
string digit = Console.ReadLine();
switch (digit)
{
case "0": Console.WriteLine("zero"); break;
case "1": Console.WriteLine("one"); break;
case "2": Console.WriteLine("two"); break;
case "3": Console.WriteLine("three"); break;
case "4": Console.WriteLine("four"); break;
case "5": Console.WriteLine("five"); break;
case "6": Console.WriteLine("six"); break;
case "7": Console.WriteLine("seven"); break;
case "8": Console.WriteLine("eight"); break;
case "9": Console.WriteLine("nine"); break;
default: Console.WriteLine("not a digit");
break;
}
}
} | mit |
subramaniashiva/searchReact | public/src/js/app.js | 6319 | /*
Helper function to load data from server
*/
function loadProductsFromServer(url, dataType, reference, params) {
$.ajax({
url: url,
dataType: dataType,
cache: false,
success: function(data) {
this.setState({data: data});
}.bind(reference),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(reference)
});
}
/*
Product container
Contains product list and pagination components
*/
var ProductContainer = React.createClass({
getInitialState: function() {
return {
data: {
products: [],
total: 0
}};
},
componentDidMount: function() {
loadProductsFromServer(this.props.url, "json", this);
},
render: function() {
return ( <div className = "product-container">
<PageBar data={this.state.data} />
<ProductList data={this.state.data}/>
</div>
);
}
});
/*
Pagination component. Part of Product container component
Contains details about total products and current page
This logic is not complete
*/
var PageBar = React.createClass({
render: function() {
return (
<div className="page-bar">
Showing {this.props.data.products.length} of {this.props.data.total}
Results
</div>
);
}
});
/*
List of products as a component
Contains individual product components
*/
var ProductList = React.createClass({
render: function() {
var productNodes = this.props.data.products.map(function (product) {
return (
<Product name={product.name} img={product.images_o.l}
url={product.url} price={product.min_price_str}
rating={product.avg_rating} deals={product.deal_count}
ratingCount={product.rating_count}
keyFeatures={product.key_features.splice(0,6)}>
{product.brand}
</Product>
);
});
return (
<div className="productList">
{productNodes}
</div>
);
}
});
/*
Individual product as a component
Contains product details such as price, rating..etc
*/
var Product = React.createClass({
render: function() {
return (
<div className="product col-md-3">
<a href={this.props.url}><img className="thumb-img"
src={this.props.img} /></a>
<h5 className="product-name">
<a href={this.props.url}>{this.props.name}</a>
</h5>
<div className="price-block pull-left">
<div className="price">
BEST PRICE <span className="value">Rs. {this.props.price}</span>
</div>
<div className="deals">
{this.props.deals} deals
</div>
</div>
<div className="pull-right">
<div className="rating">
{this.props.rating}
</div>
<div className="total-rating">
{this.props.ratingCount} votes
</div>
</div>
<div className="clearfix"></div>
<ProductFeatures keyFeatures={this.props.keyFeatures}>
</ProductFeatures>
</div>
);
}
});
/*
Product features as component
This will be a part of product component
*/
var ProductFeatures = React.createClass({
render: function() {
var featureNodes = this.props.keyFeatures.map(function (features) {
return (
<li>
{(features[1].split(','))[0]}
</li>
);
});
return (
<div className="features-list">
{featureNodes}
</div>
);
}
});
/*
Search component.
Continas the search box and filters out the results as user types
*/
var SearchContainer = React.createClass({
getInitialState: function(){
return { searchString: '',
data: {products: []}};
},
handleChange: function(e){
loadProductsFromServer(this.props.url, "json", this);
this.setState({searchString:e.target.value});
},
render: function() {
var searchResult = this.state.data.products,
searchString = this.state.searchString.trim().toLowerCase();
if(searchString.length > 0){
// We are searching. Filter the results.
searchResult = searchResult.filter(function(l){
return l.name.toLowerCase().match( searchString );
});
}
return (<div>
<input id="search-box" type="text"
value={this.state.searchString}
onChange={this.handleChange}
className="form-control search-input ui-autocomplete-input"
placeholder="Find the best mobile at today's best price."
autocomplete="off" />
<span
className="glyphicon glyphicon-search form-control-feedback"
></span>
<ul id="search-list" className="search-list">
{ searchResult.map(function(l){
return <li>
<a href={l.url}>
<div className="pull-left search-list-img">
<img src={l.images_o.s} />
</div>
<div className="pull-left">
<span className="search-list-name">
{l.name}
</span><br/>from
<span className="search-list-desc">
{l.min_price_str}
</span> in
<span className="search-list-desc">
{l.store_count}
</span> stores</div>
</a>
</li>
}) }
</ul>
</div>);
}
});
// Render the Product container
React.render(<ProductContainer url="products.json" />,
document.getElementById('content'));
// Render the Search container
React.render(<SearchContainer url="products.json" />,
document.getElementById('search-bar'))
| mit |
xiongziliang/ZLMediaKit | src/Player/PlayerProxy.cpp | 11914 | /*
* Copyright (c) 2016 The ZLMediaKit project authors. All Rights Reserved.
*
* This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit).
*
* Use of this source code is governed by MIT license that can be found in the
* LICENSE file in the root of the source tree. All contributing project authors
* may be found in the AUTHORS file in the root of the source tree.
*/
#include "Common/config.h"
#include "PlayerProxy.h"
#include "Util/mini.h"
#include "Util/MD5.h"
#include "Util/logger.h"
#include "Extension/AAC.h"
using namespace toolkit;
namespace mediakit {
static uint8_t s_mute_adts[] = {0xff, 0xf1, 0x6c, 0x40, 0x2d, 0x3f, 0xfc, 0x00, 0xe0, 0x34, 0x20, 0xad, 0xf2, 0x3f, 0xb5, 0xdd,
0x73, 0xac, 0xbd, 0xca, 0xd7, 0x7d, 0x4a, 0x13, 0x2d, 0x2e, 0xa2, 0x62, 0x02, 0x70, 0x3c, 0x1c,
0xc5, 0x63, 0x55, 0x69, 0x94, 0xb5, 0x8d, 0x70, 0xd7, 0x24, 0x6a, 0x9e, 0x2e, 0x86, 0x24, 0xea,
0x4f, 0xd4, 0xf8, 0x10, 0x53, 0xa5, 0x4a, 0xb2, 0x9a, 0xf0, 0xa1, 0x4f, 0x2f, 0x66, 0xf9, 0xd3,
0x8c, 0xa6, 0x97, 0xd5, 0x84, 0xac, 0x09, 0x25, 0x98, 0x0b, 0x1d, 0x77, 0x04, 0xb8, 0x55, 0x49,
0x85, 0x27, 0x06, 0x23, 0x58, 0xcb, 0x22, 0xc3, 0x20, 0x3a, 0x12, 0x09, 0x48, 0x24, 0x86, 0x76,
0x95, 0xe3, 0x45, 0x61, 0x43, 0x06, 0x6b, 0x4a, 0x61, 0x14, 0x24, 0xa9, 0x16, 0xe0, 0x97, 0x34,
0xb6, 0x58, 0xa4, 0x38, 0x34, 0x90, 0x19, 0x5d, 0x00, 0x19, 0x4a, 0xc2, 0x80, 0x4b, 0xdc, 0xb7,
0x00, 0x18, 0x12, 0x3d, 0xd9, 0x93, 0xee, 0x74, 0x13, 0x95, 0xad, 0x0b, 0x59, 0x51, 0x0e, 0x99,
0xdf, 0x49, 0x98, 0xde, 0xa9, 0x48, 0x4b, 0xa5, 0xfb, 0xe8, 0x79, 0xc9, 0xe2, 0xd9, 0x60, 0xa5,
0xbe, 0x74, 0xa6, 0x6b, 0x72, 0x0e, 0xe3, 0x7b, 0x28, 0xb3, 0x0e, 0x52, 0xcc, 0xf6, 0x3d, 0x39,
0xb7, 0x7e, 0xbb, 0xf0, 0xc8, 0xce, 0x5c, 0x72, 0xb2, 0x89, 0x60, 0x33, 0x7b, 0xc5, 0xda, 0x49,
0x1a, 0xda, 0x33, 0xba, 0x97, 0x9e, 0xa8, 0x1b, 0x6d, 0x5a, 0x77, 0xb6, 0xf1, 0x69, 0x5a, 0xd1,
0xbd, 0x84, 0xd5, 0x4e, 0x58, 0xa8, 0x5e, 0x8a, 0xa0, 0xc2, 0xc9, 0x22, 0xd9, 0xa5, 0x53, 0x11,
0x18, 0xc8, 0x3a, 0x39, 0xcf, 0x3f, 0x57, 0xb6, 0x45, 0x19, 0x1e, 0x8a, 0x71, 0xa4, 0x46, 0x27,
0x9e, 0xe9, 0xa4, 0x86, 0xdd, 0x14, 0xd9, 0x4d, 0xe3, 0x71, 0xe3, 0x26, 0xda, 0xaa, 0x17, 0xb4,
0xac, 0xe1, 0x09, 0xc1, 0x0d, 0x75, 0xba, 0x53, 0x0a, 0x37, 0x8b, 0xac, 0x37, 0x39, 0x41, 0x27,
0x6a, 0xf0, 0xe9, 0xb4, 0xc2, 0xac, 0xb0, 0x39, 0x73, 0x17, 0x64, 0x95, 0xf4, 0xdc, 0x33, 0xbb,
0x84, 0x94, 0x3e, 0xf8, 0x65, 0x71, 0x60, 0x7b, 0xd4, 0x5f, 0x27, 0x79, 0x95, 0x6a, 0xba, 0x76,
0xa6, 0xa5, 0x9a, 0xec, 0xae, 0x55, 0x3a, 0x27, 0x48, 0x23, 0xcf, 0x5c, 0x4d, 0xbc, 0x0b, 0x35,
0x5c, 0xa7, 0x17, 0xcf, 0x34, 0x57, 0xc9, 0x58, 0xc5, 0x20, 0x09, 0xee, 0xa5, 0xf2, 0x9c, 0x6c,
0x39, 0x1a, 0x77, 0x92, 0x9b, 0xff, 0xc6, 0xae, 0xf8, 0x36, 0xba, 0xa8, 0xaa, 0x6b, 0x1e, 0x8c,
0xc5, 0x97, 0x39, 0x6a, 0xb8, 0xa2, 0x55, 0xa8, 0xf8};
#define MUTE_ADTS_DATA s_mute_adts
#define MUTE_ADTS_DATA_LEN sizeof(s_mute_adts)
#define MUTE_ADTS_DATA_MS 130
PlayerProxy::PlayerProxy(const string &vhost, const string &app, const string &stream_id,
bool enable_hls, bool enable_mp4, int retry_count, const EventPoller::Ptr &poller)
: MediaPlayer(poller) {
_vhost = vhost;
_app = app;
_stream_id = stream_id;
_enable_hls = enable_hls;
_enable_mp4 = enable_mp4;
_retry_count = retry_count;
}
void PlayerProxy::setPlayCallbackOnce(const function<void(const SockException &ex)> &cb){
_on_play = cb;
}
void PlayerProxy::setOnClose(const function<void()> &cb){
_on_close = cb;
}
void PlayerProxy::play(const string &strUrlTmp) {
weak_ptr<PlayerProxy> weakSelf = shared_from_this();
std::shared_ptr<int> piFailedCnt(new int(0)); //连续播放失败次数
setOnPlayResult([weakSelf,strUrlTmp,piFailedCnt](const SockException &err) {
auto strongSelf = weakSelf.lock();
if(!strongSelf) {
return;
}
if(strongSelf->_on_play) {
strongSelf->_on_play(err);
strongSelf->_on_play = nullptr;
}
if(!err) {
// 播放成功
*piFailedCnt = 0;//连续播放失败次数清0
strongSelf->onPlaySuccess();
}else if(*piFailedCnt < strongSelf->_retry_count || strongSelf->_retry_count < 0) {
// 播放失败,延时重试播放
strongSelf->rePlay(strUrlTmp,(*piFailedCnt)++);
}
});
setOnShutdown([weakSelf,strUrlTmp,piFailedCnt](const SockException &err) {
auto strongSelf = weakSelf.lock();
if(!strongSelf) {
return;
}
//注销直接拉流代理产生的流:#532
strongSelf->setMediaSource(nullptr);
if(strongSelf->_muxer) {
auto tracks = strongSelf->MediaPlayer::getTracks(false);
for (auto & track : tracks){
track->delDelegate(strongSelf->_muxer.get());
}
GET_CONFIG(bool,resetWhenRePlay,General::kResetWhenRePlay);
if (resetWhenRePlay) {
strongSelf->_muxer.reset();
} else {
strongSelf->_muxer->resetTracks();
}
}
//播放异常中断,延时重试播放
if(*piFailedCnt < strongSelf->_retry_count || strongSelf->_retry_count < 0) {
strongSelf->rePlay(strUrlTmp,(*piFailedCnt)++);
}
});
MediaPlayer::play(strUrlTmp);
_pull_url = strUrlTmp;
MediaSource::Ptr mediaSource;
if(dynamic_pointer_cast<RtspPlayer>(_delegate)){
//rtsp拉流
GET_CONFIG(bool,directProxy,Rtsp::kDirectProxy);
if(directProxy){
mediaSource = std::make_shared<RtspMediaSource>(_vhost, _app, _stream_id);
}
} else if(dynamic_pointer_cast<RtmpPlayer>(_delegate)){
//rtmp拉流,rtmp强制直接代理
mediaSource = std::make_shared<RtmpMediaSource>(_vhost, _app, _stream_id);
}
if(mediaSource){
setMediaSource(mediaSource);
mediaSource->setListener(shared_from_this());
}
}
PlayerProxy::~PlayerProxy() {
_timer.reset();
}
void PlayerProxy::rePlay(const string &strUrl,int iFailedCnt){
auto iDelay = MAX(2 * 1000, MIN(iFailedCnt * 3000, 60*1000));
weak_ptr<PlayerProxy> weakSelf = shared_from_this();
_timer = std::make_shared<Timer>(iDelay / 1000.0f,[weakSelf,strUrl,iFailedCnt]() {
//播放失败次数越多,则延时越长
auto strongPlayer = weakSelf.lock();
if(!strongPlayer) {
return false;
}
WarnL << "重试播放[" << iFailedCnt << "]:" << strUrl;
strongPlayer->MediaPlayer::play(strUrl);
return false;
}, getPoller());
}
bool PlayerProxy::close(MediaSource &sender,bool force) {
if(!force && totalReaderCount()){
return false;
}
//通知其停止推流
weak_ptr<PlayerProxy> weakSelf = dynamic_pointer_cast<PlayerProxy>(shared_from_this());
getPoller()->async_first([weakSelf]() {
auto strongSelf = weakSelf.lock();
if (!strongSelf) {
return;
}
strongSelf->_muxer.reset();
strongSelf->setMediaSource(nullptr);
strongSelf->teardown();
if (strongSelf->_on_close) {
strongSelf->_on_close();
}
});
WarnL << sender.getSchema() << "/" << sender.getVhost() << "/" << sender.getApp() << "/" << sender.getId() << " " << force;
return true;
}
int PlayerProxy::totalReaderCount(){
return (_muxer ? _muxer->totalReaderCount() : 0) + (_pMediaSrc ? _pMediaSrc->readerCount() : 0);
}
int PlayerProxy::totalReaderCount(MediaSource &sender) {
return totalReaderCount();
}
MediaOriginType PlayerProxy::getOriginType(MediaSource &sender) const{
return MediaOriginType::pull;
}
string PlayerProxy::getOriginUrl(MediaSource &sender) const{
return _pull_url;
}
std::shared_ptr<SockInfo> PlayerProxy::getOriginSock(MediaSource &sender) const{
return getSockInfo();
}
class MuteAudioMaker : public FrameDispatcher{
public:
typedef std::shared_ptr<MuteAudioMaker> Ptr;
MuteAudioMaker(){};
~MuteAudioMaker() override {}
void inputFrame(const Frame::Ptr &frame) override {
if(frame->getTrackType() == TrackVideo){
auto audio_idx = frame->dts() / MUTE_ADTS_DATA_MS;
if(_audio_idx != audio_idx){
_audio_idx = audio_idx;
auto aacFrame = std::make_shared<FrameFromStaticPtr>(CodecAAC, (char *)MUTE_ADTS_DATA, MUTE_ADTS_DATA_LEN, _audio_idx * MUTE_ADTS_DATA_MS, 0 ,ADTS_HEADER_LEN);
FrameDispatcher::inputFrame(aacFrame);
}
}
}
private:
class FrameFromStaticPtr : public FrameFromPtr{
public:
template <typename ... ARGS>
FrameFromStaticPtr(ARGS && ...args) : FrameFromPtr(std::forward<ARGS>(args)...) {};
~FrameFromStaticPtr() override = default;
bool cacheAble() const override {
return true;
}
};
private:
int _audio_idx = 0;
};
void PlayerProxy::onPlaySuccess() {
GET_CONFIG(bool,resetWhenRePlay,General::kResetWhenRePlay);
if (dynamic_pointer_cast<RtspMediaSource>(_pMediaSrc)) {
//rtsp拉流代理
if (resetWhenRePlay || !_muxer) {
_muxer.reset(new MultiMediaSourceMuxer(_vhost, _app, _stream_id, getDuration(), false, true, _enable_hls, _enable_mp4));
}
} else if (dynamic_pointer_cast<RtmpMediaSource>(_pMediaSrc)) {
//rtmp拉流代理
if (resetWhenRePlay || !_muxer) {
_muxer.reset(new MultiMediaSourceMuxer(_vhost, _app, _stream_id, getDuration(), true, false, _enable_hls, _enable_mp4));
}
} else {
//其他拉流代理
if (resetWhenRePlay || !_muxer) {
_muxer.reset(new MultiMediaSourceMuxer(_vhost, _app, _stream_id, getDuration(), true, true, _enable_hls, _enable_mp4));
}
}
_muxer->setMediaListener(shared_from_this());
auto videoTrack = getTrack(TrackVideo, false);
if (videoTrack) {
//添加视频
_muxer->addTrack(videoTrack);
//视频数据写入_mediaMuxer
videoTrack->addDelegate(_muxer);
}
//是否添加静音音频
GET_CONFIG(bool, addMuteAudio, General::kAddMuteAudio);
auto audioTrack = getTrack(TrackAudio, false);
if (audioTrack) {
//添加音频
_muxer->addTrack(audioTrack);
//音频数据写入_mediaMuxer
audioTrack->addDelegate(_muxer);
} else if (addMuteAudio && videoTrack) {
//没有音频信息,产生一个静音音频
MuteAudioMaker::Ptr audioMaker = std::make_shared<MuteAudioMaker>();
//videoTrack把数据写入MuteAudioMaker
videoTrack->addDelegate(audioMaker);
//添加一个静音Track至_mediaMuxer
_muxer->addTrack(std::make_shared<AACTrack>());
//MuteAudioMaker生成静音音频然后写入_mediaMuxer;
audioMaker->addDelegate(_muxer);
}
//添加完毕所有track,防止单track情况下最大等待3秒
_muxer->addTrackCompleted();
if (_pMediaSrc) {
//让_muxer对象拦截一部分事件(比如说录像相关事件)
_pMediaSrc->setListener(_muxer);
}
}
} /* namespace mediakit */
| mit |
stve/analytics-proxy-helpers | test/test_view_helpers.rb | 1176 | require File.dirname(__FILE__) + '/helper.rb'
include GoogleAnalytics::Proxy::ViewHelpers
class ViewHelpersTest < Test::Unit::TestCase
context "GoogleAnalyticsProxy" do
should "embed the analytics proxy js" do
assert_equal google_analytics_proxy, '<script type="text/javascript" src="/javascripts/google_analytics_proxy.js"></script>'
end
context "with a default variable name" do
setup do
# set to nil so it uses the default variable name
GoogleAnalytics::Proxy.variable_name = nil
end
should "generate embed code properly" do
assert_equal google_analytics_proxy_setup, '<script type="text/javascript">
var _gap = new GoogleAnalyticsProxy();
</script>
'
end
end
context "with a custom variable name" do
setup do
GoogleAnalytics::Proxy.variable_name = 'pageTracker'
end
should "generate embed code properly" do
assert_equal google_analytics_proxy_setup, '<script type="text/javascript">
var pageTracker = new GoogleAnalyticsProxy();
</script>
'
end
end
end
end | mit |
samkariu/nairobi-routes | boilerplate/config.py | 4180 | """
This is the boilerplate default configuration file.
Changes and additions to settings should be done in the config module
located in the application root rather than this config.
"""
config = {
# webapp2 sessions
'webapp2_extras.sessions' : {'secret_key': '_PUT_KEY_HERE_YOUR_SECRET_KEY_'},
# webapp2 authentication
'webapp2_extras.auth' : {'user_model': 'boilerplate.models.User',
'cookie_name': 'session_name'},
# jinja2 templates
'webapp2_extras.jinja2' : {'template_path': ['templates','boilerplate/templates', 'admin/templates'],
'environment_args': {'extensions': ['jinja2.ext.i18n']}},
# application name
'app_name' : "Nairobi Routes Visualizer",
# the default language code for the application.
# should match whatever language the site uses when i18n is disabled
'app_lang' : 'en',
# Locale code = <language>_<territory> (ie 'en_US')
# to pick locale codes see http://cldr.unicode.org/index/cldr-spec/picking-the-right-language-code
# also see http://www.sil.org/iso639-3/codes.asp
# Language codes defined under iso 639-1 http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes
# Territory codes defined under iso 3166-1 alpha-2 http://en.wikipedia.org/wiki/ISO_3166-1
# disable i18n if locales array is empty or None
'locales' : ['en_US', 'es_ES', 'it_IT', 'zh_CN', 'id_ID', 'fr_FR', 'de_DE', 'ru_RU', 'pt_BR', 'cs_CZ'],
# contact page email settings
'contact_sender' : "PUT_SENDER_EMAIL_HERE",
'contact_recipient' : "PUT_RECIPIENT_EMAIL_HERE",
# Password AES Encryption Parameters
'aes_key' : "12_24_32_BYTES_KEY_FOR_PASSWORDS",
'salt' : "_PUT_SALT_HERE_TO_SHA512_PASSWORDS_",
# get your own consumer key and consumer secret by registering at https://dev.twitter.com/apps
# callback url must be: http://[YOUR DOMAIN]/login/twitter/complete
'twitter_consumer_key' : 'PUT_YOUR_TWITTER_CONSUMER_KEY_HERE',
'twitter_consumer_secret' : 'PUT_YOUR_TWITTER_CONSUMER_SECRET_HERE',
#Facebook Login
# get your own consumer key and consumer secret by registering at https://developers.facebook.com/apps
#Very Important: set the site_url= your domain in the application settings in the facebook app settings page
# callback url must be: http://[YOUR DOMAIN]/login/facebook/complete
'fb_api_key' : 'PUT_YOUR_FACEBOOK_PUBLIC_KEY_HERE',
'fb_secret' : 'PUT_YOUR_FACEBOOK_PUBLIC_KEY_HERE',
#Linkedin Login
#Get you own api key and secret from https://www.linkedin.com/secure/developer
'linkedin_api' : 'PUT_YOUR_LINKEDIN_PUBLIC_KEY_HERE',
'linkedin_secret' : 'PUT_YOUR_LINKEDIN_PUBLIC_KEY_HERE',
# Github login
# Register apps here: https://github.com/settings/applications/new
'github_server' : 'github.com',
'github_redirect_uri' : 'http://www.example.com/social_login/github/complete',
'github_client_id' : 'PUT_YOUR_GITHUB_CLIENT_ID_HERE',
'github_client_secret' : 'PUT_YOUR_GITHUB_CLIENT_SECRET_HERE',
# get your own recaptcha keys by registering at http://www.google.com/recaptcha/
'captcha_public_key' : "PUT_YOUR_RECAPCHA_PUBLIC_KEY_HERE",
'captcha_private_key' : "PUT_YOUR_RECAPCHA_PRIVATE_KEY_HERE",
# Leave blank "google_analytics_domain" if you only want Analytics code
'google_analytics_domain' : "YOUR_PRIMARY_DOMAIN (e.g. google.com)",
'google_analytics_code' : "UA-XXXXX-X",
# add status codes and templates used to catch and display errors
# if a status code is not listed here it will use the default app engine
# stacktrace error page or browser error page
'error_templates' : {
403: 'errors/default_error.html',
404: 'errors/default_error.html',
500: 'errors/default_error.html',
},
# Enable Federated login (OpenID and OAuth)
# Google App Engine Settings must be set to Authentication Options: Federated Login
'enable_federated_login' : True,
# jinja2 base layout template
'base_layout' : 'base.html',
# send error emails to developers
'send_mail_developer' : True,
# fellas' list
'developers' : (
('Santa Klauss', '[email protected]'),
),
# If true, it will write in datastore a log of every email sent
'log_email' : True,
# If true, it will write in datastore a log of every visit
'log_visit' : True,
# ----> ADD MORE CONFIGURATION OPTIONS HERE <----
} # end config
| mit |
bigfont/2013-128CG-Vendord | HelpfulStuff/MVVMDemoApp/DemoApp/ViewModel/MainWindowViewModel.cs | 4740 | using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Windows.Data;
using DemoApp.DataAccess;
using DemoApp.Model;
using DemoApp.Properties;
namespace DemoApp.ViewModel
{
/// <summary>
/// The ViewModel for the application's main window.
/// </summary>
public class MainWindowViewModel : WorkspaceViewModel
{
#region Fields
ReadOnlyCollection<CommandViewModel> _commands;
readonly CustomerRepository _customerRepository;
ObservableCollection<WorkspaceViewModel> _workspaces;
#endregion // Fields
#region Constructor
public MainWindowViewModel(string customerDataFile)
{
base.DisplayName = Strings.MainWindowViewModel_DisplayName;
_customerRepository = new CustomerRepository(customerDataFile);
}
#endregion // Constructor
#region Commands
/// <summary>
/// Returns a read-only list of commands
/// that the UI can display and execute.
/// </summary>
public ReadOnlyCollection<CommandViewModel> Commands
{
get
{
if (_commands == null)
{
List<CommandViewModel> cmds = this.CreateCommands();
_commands = new ReadOnlyCollection<CommandViewModel>(cmds);
}
return _commands;
}
}
List<CommandViewModel> CreateCommands()
{
return new List<CommandViewModel>
{
new CommandViewModel(
Strings.MainWindowViewModel_Command_ViewAllCustomers,
new RelayCommand(param => this.ShowAllCustomers())),
new CommandViewModel(
Strings.MainWindowViewModel_Command_CreateNewCustomer,
new RelayCommand(param => this.CreateNewCustomer()))
};
}
#endregion // Commands
#region Workspaces
/// <summary>
/// Returns the collection of available workspaces to display.
/// A 'workspace' is a ViewModel that can request to be closed.
/// </summary>
public ObservableCollection<WorkspaceViewModel> Workspaces
{
get
{
if (_workspaces == null)
{
_workspaces = new ObservableCollection<WorkspaceViewModel>();
_workspaces.CollectionChanged += this.OnWorkspacesChanged;
}
return _workspaces;
}
}
void OnWorkspacesChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null && e.NewItems.Count != 0)
foreach (WorkspaceViewModel workspace in e.NewItems)
workspace.RequestClose += this.OnWorkspaceRequestClose;
if (e.OldItems != null && e.OldItems.Count != 0)
foreach (WorkspaceViewModel workspace in e.OldItems)
workspace.RequestClose -= this.OnWorkspaceRequestClose;
}
void OnWorkspaceRequestClose(object sender, EventArgs e)
{
WorkspaceViewModel workspace = sender as WorkspaceViewModel;
workspace.Dispose();
this.Workspaces.Remove(workspace);
}
#endregion // Workspaces
#region Private Helpers
void CreateNewCustomer()
{
Customer newCustomer = Customer.CreateNewCustomer();
CustomerViewModel workspace = new CustomerViewModel(newCustomer, _customerRepository);
this.Workspaces.Add(workspace);
this.SetActiveWorkspace(workspace);
}
void ShowAllCustomers()
{
AllCustomersViewModel workspace =
this.Workspaces.FirstOrDefault(vm => vm is AllCustomersViewModel)
as AllCustomersViewModel;
if (workspace == null)
{
workspace = new AllCustomersViewModel(_customerRepository);
this.Workspaces.Add(workspace);
}
this.SetActiveWorkspace(workspace);
}
void SetActiveWorkspace(WorkspaceViewModel workspace)
{
Debug.Assert(this.Workspaces.Contains(workspace));
ICollectionView collectionView = CollectionViewSource.GetDefaultView(this.Workspaces);
if (collectionView != null)
collectionView.MoveCurrentTo(workspace);
}
#endregion // Private Helpers
}
} | mit |
dodolangus/rep_bnv_app | application/views/pendaftaran/view_pendaftaran.php | 7964 | <!-- Map -->
<section id="contact" class="map">
<div class="container">
<div class="row text-left">
<div class="col-lg-12 ">
<hr/>
<div class="row">
<div class="col-lg-12">
<form method="post" action = "<?php echo site_url('pendaftaran/input_peserta'); ?>" enctype="multipart/form-data" accept-charset="utf-8">
<div class="alert alert-success alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4>Nama Kelas <strong>: <?php echo $nama_kelas; ?><h4>
<h5>PIC <strong>: <?php echo $pic; ?><h5>
<h5>Start Date <strong>: <input type="text" class="form-control" name='start_date' id='tgl_1' value="<?php echo $start_date; ?>"><h5>
<h5>End Date <strong>: <input type="text" class="form-control" name='end_date' id='tgl_2' value="<?php echo $end_date; ?>"><h5>
<label for="recipient-name" class="control-label">PIC TSG:</label>
<select name="pic_tsg" id="pic_tsg" class="form-control">
<option value='' >- Pilih -</option>
<?php foreach($pic_tsg as $tsg){ ?>
<option value='<?php echo $tsg->nama; ?>' <?php if($row->pic_tsg == $tsg->nama){ echo'selected';}?>>- <?php echo $tsg->nama; ?> -</option>
<?php } ?>
</select>
<div class="form-group">
<label for="recipient-name" class="control-label">Estimasi Biaya:</label>
<input type="number" class="form-control" name='estimasi_biaya' required>
</div>
<label for="recipient-name" class="control-label">Hari Pelatihan:</label>
<input type="number" class="form-control" name='hari_pelatihan' required>
</div>
<div class="panel panel-warning">
<div class="panel-heading">
<h3><i class="fa fa-list"></i> Data Peserta</h3>
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<div class="table-responsive">
<table class="table table-striped table-hover" id="-example">
<thead>
<tr class="warning">
<th width="5%">No</th>
<th >Warning</th>
<th >Npp</th>
<th width="30%">Nama</th>
<th >Div</th>
<th >Unit</th>
<th width="8%" >Jenjang</th>
<th >Jabatan</th>
<th width="15%">Lokasi</th>
</tr>
</thead>
<tbody>
<?php
$no = 1;
for($i=0;$i<count($npp);$i++){
$dapeg = $this->model_dop->get_table_where_array('m_biodata','npp',$npp[$i]);
$kemungkinan = $this->model_pendaftaran->getKemungkinanPelatihan($npp[$i],$start_date,$end_date,$id);
$jumlah = count($kemungkinan);
if ($jumlah >= 1 || empty($dapeg)){
$color = "class='danger'";
$cek = '';
}else{
$color = "class='success'";
$cek = 'checked';
}
?>
<tr <?php echo $color; ?>>
<td style="center">
<?php echo $no; ?>
<input type="checkbox" name="cek_<?php echo $no; ?>" value="1" <?php echo $cek; ?> >
<input class="form-control" type ="hidden" name="npp_<?php echo $no; $no++; ?>" value="<?php echo $npp[$i]; ?>" >
</td>
<td>
<?php if ($jumlah > 0) { ?>
<button type="button" class="btn btn-danger btn-xs" data-toggle="modal" data-target="#myModal_<?php echo $npp[$i]; ?>">
<?php echo $jumlah;?>
</button>
<div class="modal fade" id="myModal_<?php echo $npp[$i]; ?>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Pelatihan Konflik Untuk <?php echo $dapeg[0]['NAMA'];?></h4>
</div>
<div class="modal-body">
<table class="table table-striped table-hover">
<thead >
<tr class='warning'>
<th>Nama Pelatihan</th>
<th>Start Date</th>
<th>End Date</th>
<th>PIC</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php
foreach ($kemungkinan as $row){
$date1 = strtotime($row->start_date);
$date2 = strtotime(date('Y-m-d'));
if ($date1 < $date2){
$hps = 1;
}else{
$hps = 0;
}
?>
<tr>
<td><?php echo $row->nama_kelas; ?></td>
<td><?php echo $row->start_date; ?></td>
<td><?php echo $row->end_date; ?></td>
<td><?php echo $row->pic; ?></td>
<td>
<?php
if ($hps == 0){
?>
<a href="<?php echo site_url('pendaftaran/delete_pendaftaran').'/'.$row->pendaftaran_peserta_id.'/'.$id; ?>" type="button" class="btn btn-danger btn-xs" onclick="return confirm('Apakah anda yakin akan menghapus Npp. <?php echo $row->npp; ?> dari kelas <?php echo $row->nama_kelas; ?>?')">
<i class="fa fa-bitbucket"></i>
</a>
<?php
}
?>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
<?php } ?>
</td>
<td><?php echo $npp[$i];?></td>
<td><?php if($dapeg){ echo $dapeg[0]['NAMA'];}else{ echo 'Non Aktif'; } ?></td>
<td><?php if($dapeg){ echo $dapeg[0]['singkatan'];}else{ echo'Non Aktif'; } ?></td>
<td><?php if($dapeg){ echo $dapeg[0]['UNIT'];}else{ echo'Non Aktif'; } ?></td>
<td><?php if($dapeg){ echo $dapeg[0]['JENJANG'];}else{echo 'Non Aktif'; } ?></td>
<td><?php if($dapeg){ echo $dapeg[0]['JABATAN'];}else{echo 'Non Aktif'; } ?></td>
<td><?php if($dapeg){ echo $dapeg[0]['LOKASI'];}else{echo 'Non Aktif'; } ?></td>
</tr>
<?php
}
?>
<input class="form-control" type ="hidden" name="id" value="<?php echo $id; ?>" >
<input class="form-control" type ="hidden" name="jml_row" value="<?php echo $no; ?>" >
</tbody>
<tr>
<th colspan ='9'>
<button type="submit" class="btn btn-primary">Submit</button>
<a href="<?php echo site_url('slider/global_delete/t_pendaftaran_pelatihan/t_pendaftaran_id').'/'.$id.'/pendaftaran'; ?>" type="button" class="btn btn-danger" onclick="return confirm('Proses pendaftaran kelas <?php echo $nama_kelas; ?> dibatalkan ?')">
Cancel
</a>
</th>
</tr>
</form>
</table>
</div>
</div>
</div>
</div><br/>
</div>
</div>
</div> | mit |
willnewton10/node-algs | test/permutations.js | 555 | var assert = require('assert');
var permutations = require('../lib/permutations');
describe("permutations", function () {
it('should return similar array when 0 or 1 elements', function () {
assert.deepEqual([ ], permutations([ ]) );
assert.deepEqual([[1]], permutations([1]) );
});
it('should return all permutations of arrays with more than 1 elements', function () {
assert.deepEqual([[2,1],[1,2]], permutations([1,2]));
assert.deepEqual([[2,3,1],[3,2,1],[3,1,2],[1,3,2], [2,1,3], [1,2,3]],
permutations([1,2,3]));
});
});
| mit |
cerad/cerad | src/Cerad/Bundle/ArbiterBundle/Schedule/Tourn/Game.php | 3414 | <?php
namespace Zayso\ArbiterBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Entity(repositoryClass="Arbiter\GameRepo")
* Table(name="arbiter.games")
*/
class Game
{
/**
* @Id
* @Column(type="integer",name="id")
*/
//@GeneratedValue
private $id;
/** @Column(type="integer",name="game_num") */
private $gameNum;
/** @Column(type="string",name="datex") */
private $date;
/** @Column(type="string",name="dow") */
private $dow;
/** @Column(type="string",name="timex") */
private $time;
/** @Column(type="string",name="sport") */
private $sport; // MSSL
/** @Column(type="string",name="levelx") */
private $level; // MS-B
/** @Column(type="string",name="bill") */
private $bill;
/** @Column(type="string",name="site") */
private $site;
/** @Column(type="string",name="home_team") */
private $homeTeam;
/** @Column(type="string",name="away_team") */
private $awayTeam;
/** @Column(type="string",name="cr") */
private $cr;
/** @Column(type="string",name="ar1") */
private $ar1;
/** @Column(type="string",name="ar2") */
private $ar2;
/** @Column(type="integer",name="home_score") */
private $homeScore;
/** @Column(type="integer",name="away_score") */
private $awayScore;
public function getId() { return $this->id; }
public function setId($value) { $this->id = $value; }
public function setGameNum($value) { $this->gameNum = $value; }
public function setDate($value) { $this->date = $value; }
public function setDow($value) { $this->dow = $value; }
public function setTime($value) { $this->time = $value; }
public function setSport($value) { $this->sport = $value; }
public function setLevel($value) { $this->level = $value; }
public function setBill($value) { $this->bill = $value; }
public function setSite($value) { $this->site = $value; }
public function setHomeTeam($value) { $this->homeTeam = $value; }
public function setAwayTeam($value) { $this->awayTeam = $value; }
public function setHomeScore($value) { $this->homeScore = $value; }
public function setAwayScore($value) { $this->awayScore = $value; }
public function setCR($value) { $this->cr = $value; }
public function setAR1($value) { $this->ar1 = $value; }
public function setAR2($value) { $this->ar2 = $value; }
public function getGameNum() { return $this->gameNum; }
public function getDate() { return $this->date; }
public function getDow() { return $this->dow; }
public function getTime() { return $this->time; }
public function getSport() { return $this->sport; }
public function getLevel() { return $this->level; }
public function getBill() { return $this->bill; }
public function getSite() { return $this->site; }
public function getHomeTeam() { return $this->homeTeam; }
public function getAwayTeam() { return $this->awayTeam; }
public function getHomeScore() { return $this->homeScore; }
public function getAwayScore() { return $this->awayScore; }
public function getCR() { return $this->cr; }
public function getAR1() { return $this->ar1; }
public function getAR2() { return $this->ar2; }
}
?>
| mit |
arxopia/uirusu | test/functional/vtfile_test.rb | 3014 | # Copyright (c) 2010-2017 Jacob Hammack.
#
# 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 NON INFRINGEMENT. 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.
require 'test_helper'
class VTFileTest < Minitest::Test
# Runs before each test, silences STDOUT/STDERR during the test
def setup
@original_stderr = $stderr
@original_stdout = $stdout
$stderr = File.open(File::NULL, "w")
$stdout = File.open(File::NULL, "w")
@app_test = Uirusu::CLI::Application.new
@app_test.load_config if File.exist?(Uirusu::CONFIG_FILE)
end
# Restore STDOUT/STDERR after each test
def teardown
$stderr = @original_stderr
$stdout = @original_stdout
end
def test_return_XX_results_for_hash_FD287794107630FA3116800E617466A9
# Skip the test if we dont have a API key
if @app_test.config.empty? || @app_test.config['virustotal']['api-key'] == nil
skip
end
hash = "FD287794107630FA3116800E617466A9" #Hash for a version of Poison Ivy
results = Uirusu::VTFile.query_report(@app_test.config['virustotal']['api-key'], hash)
result = Uirusu::VTResult.new(hash, results)
assert_equal 55, result.results.size
end
# private-api
def test_return_scan_upload_url
if @app_test.config.empty? || @app_test.config['virustotal']['api-key'] == nil || !@app_test.config['virustotal']['private']
skip "scan_upload_url private-api"
end
#return a JSON response containing an upload URL
result = Uirusu::VTFile.scan_upload_url @app_test.config['virustotal']['api-key']
assert_includes result.keys, "upload_url"
end
def test_return_additional_info_for_hash_FD287794107630FA3116800E617466A9
# Skip the test if we dont have a API key
if @app_test.config.empty? || @app_test.config['virustotal']['api-key'] == nil || !@app_test.config['virustotal']['private']
skip 'hash additional_info private-api'
end
hash = "FD287794107630FA3116800E617466A9" #Hash for a version of Poison Ivy
results = Uirusu::VTFile.query_report(@app_test.config['virustotal']['api-key'], hash, allinfo: 1)
assert_includes results.keys, "additional_info"
end
end
| mit |
UpBeet/dungeon-generator | Assets/Scripts/BoardGenerator.cs | 2052 | using UnityEngine;
using UnityEditor;
/// <summary>
/// This component is effectively used to mimic the server-side
/// generation of boards that will be sent to the client.
/// </summary>
public class BoardGenerator : MonoBehaviour {
/// <summary>
/// Reference to the tile prefab for loading boards.
/// </summary>
[SerializeField] private TileController tilePrefab;
/// <summary>
/// Reference to the current board, or null if there isn't one.
/// </summary>
private BoardController board;
/// <summary>
/// Generates a new board.
/// </summary>
public void GenerateBoard () {
// Base case: no tile prefab.
if (tilePrefab == null) {
Debug.LogError ("Missing reference to tile prefab.");
return;
}
// Delete the old board object.
if (board != null) {
GameObject.DestroyImmediate (board.gameObject);
}
// Construct a board definition.
BoardDefinition generatedBoardDefinition = new BoardDefinition (20, 20);
// Construct the board GameObject.
GameObject boardObject = new GameObject ("Generated Board");
boardObject.transform.SetParent (transform);
board = boardObject.AddComponent<BoardController> ();
// Load the tiles onto the board.
board.LoadBoard (generatedBoardDefinition, tilePrefab);
}
}
/// <summary>
/// Inspector controls for the board generator.
/// </summary>
[CustomEditor (typeof (BoardGenerator))]
public class BoardGeneratorControls : Editor {
/// <summary>
/// The BoardGenerator this component inspector details.
/// </summary>
private BoardGenerator generator;
/// <summary>
/// Initialize this component inspector.
/// </summary>
void OnEnable () {
// Cache a reference to the BoardGenerator.
generator = target as BoardGenerator;
}
/// <summary>
/// Render the GUI for this component inspector.
/// </summary>
public override void OnInspectorGUI () {
// Draw the default inspect.
DrawDefaultInspector ();
// Draw the button to generate a new board.
if (GUILayout.Button ("Generate Board")) {
generator.GenerateBoard ();
}
}
}
| mit |
codelegant/TypeScript | declaration-merging/merging-moduel-with-function.js | 270 | function buildLabel(name) {
return buildLabel.prefix + name + buildLabel.suffix;
}
var buildLabel;
(function (buildLabel) {
buildLabel.suffix = "";
buildLabel.prefix = "Hello, ";
})(buildLabel || (buildLabel = {}));
console.log(buildLabel("lai chuanfeng"));
| mit |
aaronroyer/styles | test/test_helper.rb | 131 | require 'rubygems'
require 'minitest/autorun'
require "mocha/setup"
require File.join(File.dirname(__FILE__), *%w[.. lib styles])
| mit |
techdude101/C-Sharp | Course Documents/Section 1 - Projects/Projects/GradeCheck/GradeCheck/Form1.Designer.cs | 2998 | namespace GradeCheck
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.txtInput = new System.Windows.Forms.TextBox();
this.lblOutput = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(13, 121);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = "Calc Grade";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// txtInput
//
this.txtInput.Location = new System.Drawing.Point(150, 123);
this.txtInput.Name = "txtInput";
this.txtInput.Size = new System.Drawing.Size(100, 20);
this.txtInput.TabIndex = 1;
//
// lblOutput
//
this.lblOutput.AutoSize = true;
this.lblOutput.Location = new System.Drawing.Point(314, 130);
this.lblOutput.Name = "lblOutput";
this.lblOutput.Size = new System.Drawing.Size(35, 13);
this.lblOutput.TabIndex = 2;
this.lblOutput.Text = "label1";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(492, 458);
this.Controls.Add(this.lblOutput);
this.Controls.Add(this.txtInput);
this.Controls.Add(this.button1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button button1;
private System.Windows.Forms.TextBox txtInput;
private System.Windows.Forms.Label lblOutput;
}
}
| mit |
bradmontgomery/django-blargg | blargg/tests/test_admin.py | 2475 | from django.conf import settings
from django.contrib.admin.sites import AdminSite
from django.contrib.auth import get_user_model
from django.contrib.sites.models import Site
from django.test import TestCase, override_settings
from ..models import Entry
from ..admin import TagAdmin, EntryAdmin
@override_settings(SITE_ID=1)
class TestTagAdmin(TestCase):
"""Verify expected fields on ``TagAdmin`` class"""
def test_list_display(self):
self.assertEqual(TagAdmin.list_display, ('name', 'slug'))
def test_search_fields(self):
self.assertEqual(TagAdmin.search_fields, ('name', ))
@override_settings(SITE_ID=1)
class TestEntryAdmin(TestCase):
"""Verify fields and methods on ``EntryAdmin`` class."""
def test_list_display(self):
expected = sorted([
'title',
'content_format',
'author',
'published',
'published_on',
'updated_on'
])
self.assertEqual(sorted(EntryAdmin.list_display), expected)
def test_date_hierarchy(self):
self.assertEqual(EntryAdmin.date_hierarchy, 'created_on')
def test_list_filter(self):
self.assertEqual(EntryAdmin.list_filter, ('published', 'content_format'))
def test_search_fields(self):
expected = ('title', 'raw_content', 'tag_string')
self.assertEqual(EntryAdmin.search_fields, expected)
def test_prepopulated_fields(self):
self.assertEqual(EntryAdmin.prepopulated_fields, {"slug": ("title", )})
def test_actions(self):
self.assertEqual(EntryAdmin.actions, ['publish_entries'])
def test_publish_entries(self):
# Some setup (need a User and an Entry)
User = get_user_model()
username = 'entryadmin_publish_entries'
user = User.objects.create(
username=username,
password='{0}@example.com'.format(username)
)
entry = Entry(
site=Site.objects.get(pk=settings.SITE_ID),
author=user,
title="Test Entry",
raw_content="Test Content",
)
entry.save()
self.assertFalse(entry.published)
# Create an EntryAdmin and call the `publish_entries` method
admin = EntryAdmin(Entry, AdminSite())
admin.publish_entries(None, Entry.objects.all())
# Fetch the Entry, and see if it's published.
entry = Entry.objects.get(pk=entry.id)
self.assertTrue(entry.published)
| mit |
kolide/osquery-go | gen/osquery/osquery-consts.go | 429 | // Autogenerated by Thrift Compiler (1.0.0-dev)
// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
package osquery
import (
"bytes"
"context"
"reflect"
"fmt"
"github.com/apache/thrift/lib/go/thrift"
)
// (needed to ensure safety because of naive import list construction.)
var _ = thrift.ZERO
var _ = fmt.Printf
var _ = context.Background
var _ = reflect.DeepEqual
var _ = bytes.Equal
func init() {
}
| mit |
jpartogi/dosboxgo | command/cmd_cd.go | 680 | package command
import (
"errors"
)
type CmdCd struct {
Command
}
func (c CmdCd) CheckParams(Params []string) error {
var err error
if err := c.CheckNumberOfParams(Params); err != nil {
return err
}
if err := c.CheckParamValues(Params); err != nil {
return err
}
return err
}
func (c CmdCd) GetName() string {
return c.Name
}
func (c CmdCd) Execute(Params []string) {
c.Outputter.Println("Executing " + c.Name)
}
func (c CmdCd) CheckNumberOfParams(Params []string) error {
var err error
if len(Params) < 1 {
err = errors.New("Incorrect syntax.")
}
return err
}
func (c CmdCd) CheckParamValues(Params []string) error {
var err error
return err
}
| mit |
DanielFryyEPN/FinalJSProject | FrontEnd/src/app/components/books/manage-books/manage-books.component.ts | 1560 | import { Component, OnInit } from '@angular/core';
import { BookClass } from '../../../classes/BookClass';
import { BookService } from '../../../services/book.service';
import { AuthService } from '../../../services/auth.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-manage-books',
templateUrl: './manage-books.component.html',
styleUrls: ['./manage-books.component.css']
})
export class ManageBooksComponent implements OnInit {
isLogged: boolean;
books: BookClass[];
genres: number[];
constructor(private _bookService: BookService,
private _authService: AuthService,
private _router: Router) { }
ngOnInit() {
this.isLogged = this._authService.isLogged;
this._bookService.getBooks()
.subscribe(
(books: BookClass[]) => {
this.books = books.map((book: BookClass) => {
this.genres = book.genres.map((genre: number) => {
return genre;
});
return book;
});
},
(error) => {
console.log('Error: ', error);
}
);
}
editBook(book: BookClass) {
this._router.navigateByUrl('editBook');
return false;
}
deleteBook(book: BookClass) {
const index = this.books.indexOf(book);
this._bookService.deleteBook(book)
.subscribe(
res => {
this.books.splice(index, 1);
console.log('Response:', res);
},
err => {
console.log('Error', err);
}
);
return false;
}
}
| mit |
shawnspears/phase-0 | week-7/group-project/group_project_solution.js | 7678 |
// Release 1: Tests to User Stories (Shawn Spears)
// ------ User Stories ------
// As a user, I want to be able to be able to take two ordered lists of integers, and find the
// sum, mean, and median of each (Three different stories).
// The first list contains 7 integers: 1, 2, 3, 4, 5, 5, and 7. Therefore the length of this list is 7,
// which is odd. If I had to name it, I would call it the odd length list.
// The second list contains 8 integers: 4, 4, 5, 5, 6, 6, 6, and 7. Therefore the length of this list
// is 8, which is even. If I had to name it, I would call it the even length list.
// I want to find the sum, mean, and median of each of these lists separately, so separate functions
// would probably be the best way for me to get the results I want:
// ------ Story 1 ------
// In the sum function, if I inputted either the odd length or even length list of integers, it should
// return the sum of those integers.
// ------ Story 2 ------
// In the mean function, if I inputted either the odd length or even length list of integers, it should
// return the average of those integers as a decimal point number.
// ------ Story 3 ------
// In the median function, if I inputted either the odd length or even length list of integers, it should
// return the median of those integers as a decimal point number.
// (If you've forgotten what the median is, it is simply the middle value in a list of values. For an odd
// numbered list of values, there is an obvious middle as the two other halves apart from the middle value
// can be separated equally. In an even list, there will be two middle values -- the median will be the
// average of these values.)
// Release 2: User Stories to Pseudocode (Malia Lehrer)
// Input: An ordered list of integers
// The tests include two lists:
// An "odd list" of 7 values [1, 2, 3, 4, 5, 5, 7]
// And an "even list" of 8 values [4, 4, 5, 5, 6, 6, 6, 7]
// Three fucntions are needed.
// Output function 1: The sum of the list
// Output function 2: The mean of the list
// Output function 3: The median of the list
// Sum function
// Input: An ordered list of integers
// Output: The sum of the list
// Set up a For loop
// Set a variable equal to the length of the list
// Set a counter equal to 0
// Set a sum variable = 0
// While the counter is less than the length of the list,
// add one to the counter each loop
// add the value at the counter (array[counter]) to the sum variable
// Return the value of the sum variable
// Mean function -- Decimals are ok!
// Input: An ordered list of integers
// Output: The mean of the list
// Set a variable equal to the length of the list
// Sum all the numbers in the array together, perhaps using the above pseudocode, or a better way if you think of one
// Divide the sum of the array by the length variable
// Return the result of this operation
// Median function
// Input: An ordered list of integers
// Output: The median of the list, which will be the middle number in the odd list and the average of the two middle numbers in the even list
// Set a variable equal to the length of the list
// Set a variable equal to the index divided by 2, rounded down (half)
//If the length is not divisible by 2 (odd)
// Return the value at the index of (half + 1)
//Else
// Set a variable equal to the value at the index of half and index
// of (half + 1), divided by 2
// Return the resulting variable
// Release 3: Psuedocode to Code (Jon Clayton)
// inputs will be:
var oddList = [1, 2, 3, 4, 5, 5, 7]
var evenList = [4, 4, 5, 5, 6, 6, 6, 7]
//Our functions are:
function Sum(list) {
for (var length = list.length, counter = 0, total = 0; counter < length; counter++) {
total += list[counter];
}
return total
}
function Mean(list) {
var length = list.length;
return Sum(list)/length;
}
function Median(list) {
var length = list.length;
var half = Math.floor(length/2);
if (length % 2 != 0) {
return list[half+1];
}
else {
var result = (list[half]+list[half+1])/2;
return result;
}
}
// Tests
console.log(Sum(oddList));
console.log(Sum(evenList));
console.log(Mean(oddList));
console.log(Mean(evenList));
console.log(Median(oddList));
console.log(Median(evenList));
// I know these medians aren't coming out right.
// But we aren't allowed to fix it because we have to accept what comes to us.
// That's half the fun of the telephone game!!!!
// Release 4: Refeactor and Translate to User Stories (Trevor Newcomb)
// inputs will be:
var oddList = [1, 2, 3, 4, 5, 5, 7]
var evenList = [4, 4, 5, 5, 6, 6, 6, 7]
//Our functions are:
function sum(list) {
for (var length = list.length, counter = 0, total = 0; counter < length; counter++) {
total += list[counter];
}
return total
}
function mean(list) {
var length = list.length;
return sum(list)/length;
}
function median(list) {
var length = list.length;
var half = Math.floor(length/2);
if (length % 2 != 0) {
return list[half+1];
}
else {
var result = (list[half]+list[half+1])/2;
return result;
}
}
// Refactor was not really possible since the code was already really clean and concise. Great job on that guys!
// User Stories
// As a user, I want to give you two lists of numbers and I want you to run some tests on them. First, I will want
// to know the sum of each list. Second, I need to know the mean of these same lists. Lastly, I will need the median
// of the two lists. I think that's how we were supposed to do the user stories, it seems pretty simplistic. If
// there's anything more you all should think I should add to this feel free to let me know and I'll fiddle with it!
// Release 5: Putting it all together (Shawn Spears)
// Nice work team! Overall, I believe we did a pretty good job considering the game of telephone is designed to make
// things incredibly unorganized and messy. Looks like we did a pretty good job with avoiding that for the most part!
// I'll outline a list of the tests that our code had to pass, and then explain if our code passed each of them!
// ** Note: Initally our code didn't pass tests 1, 4, and 7, however, Jon did note that he realized that he should have
// named the functions using camelCase syntax, and thus I have added this to Release 4 -- the following tests reflect
// this change **
// Tests:
// 1. sum instanceof Function -- PASS, as the object named "sum" is a function
// 2. sum(oddLengthArray) === 27 -- PASS, as passing the oddLengthArray through sum returned 27
// 3. sum(evenLengthArray) === 43 -- PASS, as passing the evenLengthArray through sum returned 43
// 4. mean instanceof Function -- PASS, as the object named "mean" is a function
// 5. mean(oddLengthArray) === 3.857142857142857 -- PASS, as passing the oddLengthArray through mean returned 3.857142857142857
// 6. mean(evenLengthArray) === 5.375 -- PASS, as passing the evenLengthArray through mean returned 5.375
// 7. median instanceof Function -- PASS, as the object named "median" is a function
// 8. median(oddLengthArray) === 4 -- FAIL, as passing the oddLengthArray through sum returned 5 instead of 4
// 9. median(evenLengthArray) === 5.5 -- FAIL, as passing the evenLengthArray through sum returned 6 instead of 5.5
// Essentially the only tests our code didn't pass were tests 8 and 9 which indicate that the median function did
// not return the correct medians for either array. Other than that, I feel like we did a fantastic job working
// together as a team, and staying true to the rules of telephone! It's supposed to trip you up a bit, as of course
// normally we would have been able to avoid some miscommunications if the rules allowed for this. Go team!
| mit |
meln1k/reactive-telegrambot | src/main/scala/com/github/meln1k/reactive/telegrambot/models/ResponseEntity.scala | 703 | package com.github.meln1k.reactive.telegrambot.models
trait ResponseEntity
/**
* This object represents an incoming update.
* @param update_id The update‘s unique identifier.
* Update identifiers start from a certain positive number and increase sequentially.
* This ID becomes especially handy if you’re using Webhooks,
* since it allows you to ignore repeated updates or to restore the correct update sequence,
* should they get out of order.
* @param message New incoming message of any kind — text, photo, sticker, etc.
*/
case class Update(update_id: Long, message: Option[Message]) extends ResponseEntity
| mit |
grecosoft/NetFusion | netfusion/src/Integration/NetFusion.RabbitMq/Settings/BusHost.cs | 618 | using System.ComponentModel.DataAnnotations;
namespace NetFusion.RabbitMQ.Settings
{
/// <summary>
/// Settings for a host associated with a specific bus connection.
/// </summary>
public class BusHost
{
/// <summary>
/// The name of the host computer running RabbitMQ.
/// </summary>
[Required(AllowEmptyStrings = false, ErrorMessage = "HostName Required")]
public string HostName { get; set; }
/// <summary>
/// The connection port to use. Defaults to 5672.
/// </summary>
public ushort Port { get; set; } = 5672;
}
} | mit |
ppc-web/ppcweb | web/donation/users/classes/Redirect.php | 2115 | <?php
/*
UserSpice 4
An Open Source PHP User Management System
by the UserSpice Team at http://UserSpice.com
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class Redirect {
public static function to($location = null, $args=''){
global $us_url_root;
#die("Redirecting to $location<br />\n");
if ($location) {
if (is_numeric($location)) {
switch ($location) {
case '404':
header('HTTP/1.0 404 Not found');
include 'includes/errors/404.php';
break;
}
}
if (!preg_match('/^https?:\/\//', $location) && !file_exists($location)) {
foreach (array($us_url_root, '../', 'users/', substr($us_url_root, 1), '../../', '/', '/users/') as $prefix) {
if (file_exists($prefix.$location)) {
$location = $prefix.$location;
break;
}
}
}
if ($args) $location .= $args; // allows 'login.php?err=Error+Message' or the like
if (!headers_sent()){
header('Location: '.$location);
exit();
} else {
echo '<script type="text/javascript">';
echo 'window.location.href="'.$location.'";';
echo '</script>';
echo '<noscript>';
echo '<meta http-equiv="refresh" content="0;url='.$location.'" />';
echo '</noscript>'; exit;
}
}
}
}
| mit |
erikzhouxin/CSharpSolution | NetSiteUtilities/AopApi/Domain/AlipayMarketingCashlessvoucherTemplateCreateModel.cs | 5918 | using System;
using System.Xml.Serialization;
namespace EZOper.NetSiteUtilities.AopApi
{
/// <summary>
/// AlipayMarketingCashlessvoucherTemplateCreateModel Data Structure.
/// </summary>
[Serializable]
public class AlipayMarketingCashlessvoucherTemplateCreateModel : AopObject
{
/// <summary>
/// 面额。每张代金券可以抵扣的金额。币种为人民币,单位为元。该数值不能小于0,小数点以后最多保留两位。代金券必填,兑换券不能填
/// </summary>
[XmlElement("amount")]
public string Amount { get; set; }
/// <summary>
/// 品牌名。用于拼接券名称,长度不能超过12个字符,voucher_type值为代金券时:券名称=券面额+’元代金券’,voucher_type值为兑换券时:券名称=品牌名+“兑换券”组成 ,券名称最终用于卡包展示
/// </summary>
[XmlElement("brand_name")]
public string BrandName { get; set; }
/// <summary>
/// 扩展信息,暂为启用
/// </summary>
[XmlElement("extension_info")]
public string ExtensionInfo { get; set; }
/// <summary>
/// 最低额度。设置券使用门槛,只有订单金额大于等于最低额度时券才能使用。币种为人民币,单位为元。该数值不能小于0,小数点以后最多保留两位。 代金券必填,兑换券不能填
/// </summary>
[XmlElement("floor_amount")]
public string FloorAmount { get; set; }
/// <summary>
/// 券变动异步通知地址
/// </summary>
[XmlElement("notify_uri")]
public string NotifyUri { get; set; }
/// <summary>
/// 外部业务单号。用作幂等控制。同一个pid下相同的外部业务单号作唯一键
/// </summary>
[XmlElement("out_biz_no")]
public string OutBizNo { get; set; }
/// <summary>
/// 发放结束时间,晚于该时间不能发券。券的发放结束时间和发放开始时间跨度不能大于90天。发放结束时间必须晚于发放开始时间。格式为:yyyy-MM-dd HH:mm:ss
/// </summary>
[XmlElement("publish_end_time")]
public string PublishEndTime { get; set; }
/// <summary>
/// 发放开始时间,早于该时间不能发券。发放开始时间不能大于当前时间15天。格式为:yyyy-MM-dd HH:mm:ss
/// </summary>
[XmlElement("publish_start_time")]
public string PublishStartTime { get; set; }
/// <summary>
/// 规则配置,JSON字符串,{"PID": "2088512417841101,2088512417841102", "STORE": "123456,678901"},其中PID表示可以核销该券的pid列表,多个值用英文逗号隔开,PID为必传且需与接口调用PID同属一个商家,STORE表示可以核销该券的内部门店ID,多个值用英文逗号隔开 , 兑换券不能指定规则配置
/// </summary>
[XmlElement("rule_conf")]
public string RuleConf { get; set; }
/// <summary>
/// 券可用时段,JSON数组字符串,空数组即[],表示不限制,指定每周时间段示例:[{"day_rule": "1,2,3,4,5", "time_begin": "09:00:00", "time_end": "22:00:00"}, {"day_rule": "6,7", "time_begin": "08:00:00", "time_end": "23:00:00"}],数组中每个元素都包含三个key:day_rule, time_begin, time_end,其中day_rule表示周几,取值范围[1, 2, 3, 4, 5, 6, 7](周7表示星期日),多个值使用英文逗号隔开;time_begin和time_end分别表示生效起始时间和结束时间,格式为HH:mm:ss。另外,数组中各个时间规则是或关系。例如,[{"day_rule": "1,2,3,4,5", "time_begin": "09:00:00", "time_end": "22:00:00"}, {"day_rule": "6,7", "time_begin": "08:00:00", "time_end": "23:00:00"}]表示在每周的一,二,三,四,五的早上9点到晚上10点券可用或者每周的星期六和星期日的早上8点到晚上11点券可用。 仅支持代金券
/// </summary>
[XmlElement("voucher_available_time")]
public string VoucherAvailableTime { get; set; }
/// <summary>
/// 券使用说明。JSON数组字符串,最多可以有10条,每条最多50字。如果没有券使用说明则传入空数组即[]
/// </summary>
[XmlElement("voucher_description")]
public string VoucherDescription { get; set; }
/// <summary>
/// 拟发行券的数量。单位为张。该数值必须是大于0的整数。
/// </summary>
[XmlElement("voucher_quantity")]
public long VoucherQuantity { get; set; }
/// <summary>
/// 券类型,取值范围 代金券:CASHLESS_FIX_VOUCHER;兑换券(暂不支持):EXCHANGE_VOUCHER;
/// </summary>
[XmlElement("voucher_type")]
public string VoucherType { get; set; }
/// <summary>
/// 券有效期。有两种类型:绝对时间和相对时间。使用JSON字符串表示。绝对时间有3个key:type、start、end,type取值固定为"ABSOLUTE",start和end分别表示券生效时间和失效时间,格式为yyyy-MM-dd HH:mm:ss。绝对时间示例:{"type": "ABSOLUTE", "start": "2017-01-10 00:00:00", "end": "2017-01-13 23:59:59"}。相对时间有3个key:type、duration、unit,type取值固定为"RELATIVE",duration表示从发券时间开始到往后推duration个单位时间为止作为券的使用有效期,unit表示有效时间单位,有效时间单位可枚举:MINUTE, HOUR, DAY。示例:{"type": "RELATIVE", "duration": 1 , "unit": "DAY" },如果此刻发券,那么该券从现在开始生效1(duration)天(unit)后失效。
/// </summary>
[XmlElement("voucher_valid_period")]
public string VoucherValidPeriod { get; set; }
}
}
| mit |
zewa666/cli | lib/resources/src/main-webpack.ts | 1247 | /// <reference types="aurelia-loader-webpack/src/webpack-hot-interface"/>
// we want font-awesome to load as soon as possible to show the fa-spinner
import {Aurelia} from 'aurelia-framework'
import environment from './environment';
import {PLATFORM} from 'aurelia-pal';
import * as Bluebird from 'bluebird';
// remove out if you don't want a Promise polyfill (remove also from webpack.config.js)
Bluebird.config({ warnings: { wForgottenReturn: false } });
export function configure(aurelia: Aurelia) {
aurelia.use
.standardConfiguration()
.feature(PLATFORM.moduleName('resources/index'));
// Uncomment the line below to enable animation.
// aurelia.use.plugin(PLATFORM.moduleName('aurelia-animator-css'));
// if the css animator is enabled, add swap-order="after" to all router-view elements
// Anyone wanting to use HTMLImports to load views, will need to install the following plugin.
// aurelia.use.plugin(PLATFORM.moduleName('aurelia-html-import-template-loader'));
if (environment.debug) {
aurelia.use.developmentLogging();
}
if (environment.testing) {
aurelia.use.plugin(PLATFORM.moduleName('aurelia-testing'));
}
return aurelia.start().then(() => aurelia.setRoot(PLATFORM.moduleName('app')));
}
| mit |
nfelix/mvmt | spec/views/brands/index.html.haml_spec.rb | 600 | require 'rails_helper'
RSpec.describe "brands/index", :type => :view do
before(:each) do
assign(:brands, [
Brand.create!(
:title => "Title",
:desc => "MyText",
:website => "Website"
),
Brand.create!(
:title => "Title",
:desc => "MyText",
:website => "Website"
)
])
end
it "renders a list of brands" do
render
assert_select "tr>td", :text => "Title".to_s, :count => 2
assert_select "tr>td", :text => "MyText".to_s, :count => 2
assert_select "tr>td", :text => "Website".to_s, :count => 2
end
end
| mit |
shadeslayor/DestinyAPI.NET | DestinyAPI/PlayerSearch.cs | 1676 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
namespace DestinyAPI
{
public sealed class PlayerSearch
{
//Const Variables
private readonly String _html_method = "GET";
private readonly String _API_ACTION = "/SearchDestinyPlayer/{membershipType}/{displayName}/";
//Variables
private WebAPI api;
/// <summary>
/// Init PlayerSearch Object
/// </summary>
/// <param name="api_key">The API Key supplied by Bungie</param>
public PlayerSearch(String api_key)
{
api = new WebAPI(api_key);
}
public List<DestinyPlayer> FindPlayers(PLATFORM platform, String name)
{
//Variables
String url = CreateAPIURL(platform, name);
String json = String.Empty;
JsonPlayerSearchObj jsonObj = null;
//Get JSON
json = api.ExecuteMethod(url, _html_method);
//Deserialize
jsonObj = new JavaScriptSerializer().Deserialize<JsonPlayerSearchObj>(json);
return jsonObj.Response.ToList();
}
private String CreateAPIURL(PLATFORM platform, String name)
{
//variables
String url = _API_ACTION;
url = url.Replace("{membershipType}", platform.ToString());
url = url.Replace("{displayName}", name);
return url;
}
private class JsonPlayerSearchObj : JsonObject
{
public DestinyPlayer[] Response { get; set; }
}
}
}
| mit |
szaretsky/test_cars | exe/etaserver.rb | 357 | $LOAD_PATH.unshift('lib/')
require 'testcars'
##################################
#
# ETA service.
# Gets and responds by means of msgpacked hash
# Req: { "cmd" => "eta", "lat" => ..., "lon" => ... }
# Resp: { "eta" => ... }
#
##################################
# port for eta service
Testcars.etaserver( dbname: 'cars', user: 'devel', port: 2202 )
| mit |
apcurium/resxible | src/Resxible.Tests/Localization/Platforms/iOSResourceFileHandlerFixture.cs | 1769 | using System.IO;
using Com.Apcurium.Resxible.Localization.iOS;
using NUnit.Framework;
namespace Com.Apcurium.Resxible.Tests.Localization.Platforms
{
[TestFixture]
public class iOSResourceFileHandlerFixture
{
private const string iOSFileName = "Localizable.Copy.strings";
[SetUp]
public void Setup()
{
File.Delete(iOSFileName);
File.Copy("Localizable.strings", iOSFileName);
}
[Test]
public void Ctor_WithFile_CorrectlyInitialized()
{
var sut = new iOSResourceFileHandler(iOSFileName, false);
Assert.That(sut.Keys.Count, Is.EqualTo(2));
}
[Test]
public void AddValue_Save_FileUpdated()
{
var sut = new iOSResourceFileHandler(iOSFileName, false);
sut["anotherkey"] = "test";
sut.Save(false);
sut = new iOSResourceFileHandler(iOSFileName, false);
Assert.That(sut.Keys.Count, Is.EqualTo(3));
}
[Test]
public void AddValue_WithClearOption_Save_FileUpdated()
{
var sut = new iOSResourceFileHandler(iOSFileName, true);
sut["anotherkey"] = "test";
sut.Save(false);
sut = new iOSResourceFileHandler(iOSFileName, false);
Assert.That(sut.Keys.Count, Is.EqualTo(1));
}
[Test]
public void AddValue_Save_FileUpdated_Escaped()
{
var sut = new iOSResourceFileHandler(iOSFileName, false);
sut["anotherkey"] = "< > & ¢ £ ¥ € © ®";
sut.Save(false);
sut = new iOSResourceFileHandler(iOSFileName, false);
Assert.That(sut.Keys.Count, Is.EqualTo(3));
}
}
}
| mit |
triggertoo/whatsup | src/vendor/zend/tests/Zend/Stdlib/SplPriorityQueueTest.php | 2365 | <?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Stdlib
* @subpackage UnitTests
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id:$
*/
namespace ZendTest\Stdlib;
use Zend\Stdlib\SplPriorityQueue;
/**
* @category Zend
* @package Zend_Stdlib
* @subpackage UnitTests
* @group Zend_Stdlib
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class SplPriorityQueueTest extends \PHPUnit_Framework_TestCase
{
public function setUp()
{
$this->queue = new SplPriorityQueue();
$this->queue->insert('foo', 3);
$this->queue->insert('bar', 4);
$this->queue->insert('baz', 2);
$this->queue->insert('bat', 1);
}
public function testSerializationAndDeserializationShouldMaintainState()
{
$s = serialize($this->queue);
$unserialized = unserialize($s);
$count = count($this->queue);
$this->assertSame($count, count($unserialized), 'Expected count ' . $count . '; received ' . count($unserialized));
$expected = array();
foreach ($this->queue as $item) {
$expected[] = $item;
}
$test = array();
foreach ($unserialized as $item) {
$test[] = $item;
}
$this->assertSame($expected, $test, 'Expected: ' . var_export($expected, 1) . "\nReceived:" . var_export($test, 1));
}
public function testCanRetrieveQueueAsArray()
{
$expected = array(
4 => 'bar',
3 => 'foo',
2 => 'baz',
1 => 'bat',
);
$test = $this->queue->toArray();
$this->assertSame($expected, $test, var_export($test, 1));
}
}
| mit |
crubier/lil | projects/com.crubier.lil/src-gen/com/crubier/lil/lil/DataTypeQueue.java | 1443 | /**
*/
package com.crubier.lil.lil;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Data Type Queue</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link com.crubier.lil.lil.DataTypeQueue#getElementType <em>Element Type</em>}</li>
* </ul>
* </p>
*
* @see com.crubier.lil.lil.LilPackage#getDataTypeQueue()
* @model
* @generated
*/
public interface DataTypeQueue extends DataType
{
/**
* Returns the value of the '<em><b>Element Type</b></em>' containment reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Element Type</em>' containment reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Element Type</em>' containment reference.
* @see #setElementType(DataType)
* @see com.crubier.lil.lil.LilPackage#getDataTypeQueue_ElementType()
* @model containment="true"
* @generated
*/
DataType getElementType();
/**
* Sets the value of the '{@link com.crubier.lil.lil.DataTypeQueue#getElementType <em>Element Type</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Element Type</em>' containment reference.
* @see #getElementType()
* @generated
*/
void setElementType(DataType value);
} // DataTypeQueue
| mit |
tomgrohl/jCountdown | test/unit/jcountdown.js | 13711 | module("jCountdown - jQuery Countdown Plugin");
$.fn.countdown.locale['de'] = {
yearText: 'Jahre',
monthText: 'Monate',
weekText: 'Wochen',
dayText: 'Tage',
hourText: 'Stunden',
minText: 'Minuten',
secText: 'Sekunden',
timeSeparator: ':',
isRTL: false
};
$.fn.countdown.locale['fr'] = {
yearText: 'Années',
monthText: 'Mois',
weekText: 'Semaines',
dayText: 'Jours',
hourText: 'Heures',
minText: 'Minutes',
secText: 'Secondes',
timeSeparator: ':',
isRTL: false
};
asyncTest("Events Fire", 6, function() {
var $test = $("#test"),
date = new Date(),
pastDate;
date.setMilliseconds(0);
pastDate = new Date( date.getTime() - ( 3600 * 24 * 1000 ) ); //1 day in the past
$test.countdown({
date: pastDate,
onStart: function( event, timer ) {
ok( true, "Start Event Fired" );
},
onChange: function( event, timer ) {
ok( true, "Change Event Fired" );
},
onPause: function( event ) {
ok( true, "Paused Event Fired" );
},
onResume: function( event ) {
ok( true, "Resumed Event Fired" );
},
onComplete: function() {
ok( true, "Complete Event Fired" );
},
onLocaleChange: function() {
ok( true, "Locale Event Fired" );
start();
},
leadingZero: true
}).countdown('pause').countdown('resume').countdown('changeLocale', 'fr');
});
asyncTest("$('elem').on Events Fire", 6, function() {
var $test = $("#test"),
date = new Date(),
pastDate;
date.setMilliseconds(0);
pastDate = new Date( date.getTime() - ( 3600 * 24 * 1000 ) ); //1 day in the past
$test.on("countStart", function() {
ok( true, "countStart Event Fired" );
}).on("countChange", function() {
ok( true, "countChange Event Fired" );
}).on("countResume", function() {
ok( true, "countResume Event Fired" );
}).on("countResume", function() {
ok( true, "countResume Event Fired" );
}).on("localeChange", function() {
ok( true, "localeChange Event Fired" );
}).on("countComplete", function() {
ok( true, "countComplete Event Fired" );
start();
});
$test.countdown({
date: pastDate,
leadingZero: true
}).countdown('pause').countdown('resume').countdown('changeLocale', 'fr');
});
asyncTest("Triggering Events Fire", 2, function() {
var $test = $("#test");
$test.off("countComplete").countdown("destroy");
date = new Date();
date.setMilliseconds(0);
pastDate = new Date( date.getTime() - ( 3600 * 24 * 1000 ) ); //1 day in the past
futureDate = new Date( date.getTime() + ( 3600 * 24 * 1000 ) ); //1 day in the future
$test.on("countComplete", function() {
ok( true, "countComplete Event Fired" );
});
$test.countdown({
date: futureDate,
leadingZero: true,
onComplete: function() {
ok( true, "Complete Event Fired" );
start();
}
});
$test.trigger('complete');
$test.trigger('countComplete');
});
asyncTest("Change Settings", 3, function() {
var $test = $("#test"),
date = new Date(),
futureDate;
$test.countdown('destroy');
date.setMilliseconds(0);
futureDate = new Date( date.getTime() + ( 1000 ) );
$test.countdown({
date: futureDate
});
$test.countdown('changeSettings',{
date : futureDate,
onComplete: function( event ) {
$(this).html("Completed");
ok( true, "Completed Event Fired after changeSettings method ran" );
equal( $test.html(), "Completed", "returns proper value after change" );
start();
}
});
newSettings = $test.countdown('getSettings');
equal( newSettings.date, futureDate, "Settings changed successfully" );
});
test("Destroy Instance", 3, function() {
var $test = $("#test"),
date = new Date(),
futureDate;
date.setMilliseconds(0);
futureDate = new Date( date.getTime() + ( 1000 ) );
$test.countdown({
date: futureDate
}).countdown('destroy');
settings = $test.countdown('getSettings');
equal( settings, undefined, "Settings were removed" );
events = $test.data('events.jcdData');
equal( events, undefined, "Events were removed" );
equal( $test.html(), "Original Content", "Original content is put back after instance has been destroyed" );
});
asyncTest("Advanced Options - secOnly", 1, function() {
var $test = $("#test"),
date = new Date(),
future60Date;
date.setMilliseconds(0);
future60Date = new Date( date.getTime() + ( 60000 ) );
$test.countdown({
date: future60Date,
secsOnly: true,
onChange: function( e,settings ) {
equal( settings.secLeft, 60, "Returns correct number of seconds when secsOnly option is used" );
$test.countdown('destroy');
start();
}
});
});
asyncTest("Advanced Options - minsOnly", 1, function() {
var $test = $("#test"),
date = new Date(),
future60Date;
date.setMilliseconds(0);
future60Date = new Date( date.getTime() + ( 60000 * 2.1 ) ); //60 secs * 2 minutes
$test.countdown({
date: future60Date,
minsOnly: true,
onChange: function( e,settings ) {
equal( settings.minsLeft, 2, "Returns correct number of minutes when minsOnly option is used" );
$test.countdown('destroy');
start();
}
});
});
asyncTest("Advanced Options - hoursOnly", 1, function() {
var $test = $("#test"),
date = new Date(),
future60Date;
date.setMilliseconds(0);
future60Date = new Date( date.getTime() + ( 3600 * 24 * 2000 ) ); //1 hour * 24 hours * 2 days
$test.countdown({
date: future60Date,
hoursOnly: true,
onChange: function( e,settings ) {
equal( settings.hrsLeft, 48, "Returns correct number of hours when hoursOnly option is used" );
$test.countdown('destroy');
start();
}
});
});
asyncTest("Advanced Options - secOnly: Far Future Date", 1, function() {
var $test = $("#test"),
date = new Date(),
future60Date;
date.setMilliseconds(0);
future60Date = new Date( date.getTime() + ( 2629800 * 9000 ) ); //9 months in future
$test.countdown({
date: future60Date,
secsOnly: true,
onChange: function( e,settings ) {
equal( settings.secLeft, 23668200, "Returns correct number of seconds when secsOnly option is used" );
$test.countdown('destroy');
start();
}
});
});
asyncTest("Advanced Options - minsOnly: Far Future Date (Months)", 1, function() {
var $test = $("#test"),
date = new Date(),
future60Date;
date.setMilliseconds(0);
future60Date = new Date( date.getTime() + ( 2629800 * 11000 ) ); //11 months in future
$test.countdown({
date: future60Date,
minsOnly: true,
onChange: function( e,settings ) {
equal( settings.minsLeft, 482130, "Returns correct number of minutes when minsOnly option is used" );
$test.countdown('destroy');
start();
}
});
});
asyncTest("Advanced Options - minsOnly: Far Future Date (Years)", 1, function() {
var $test = $("#test"),
date = new Date(),
future60Date;
date.setMilliseconds(0);
future60Date = new Date( date.getTime() + ( 31557600 * 6000 ) ); //6 years in future
$test.countdown({
date: future60Date,
minsOnly: true,
onChange: function( e,settings ) {
equal( settings.minsLeft, 3155760, "Returns correct number of minutes when minsOnly option is used" );
$test.countdown('destroy');
start();
}
});
});
asyncTest("Advanced Options - hoursOnly : Far Future Date", 1, function() {
var $test = $("#test"),
date = new Date(),
future60Date;
date.setMilliseconds(0);
future60Date = new Date( date.getTime() + ( 2629800 * 6000 )); //6 months in future
$test.countdown({
date: future60Date,
hoursOnly: true,
onChange: function( e,settings ) {
equal( settings.hrsLeft, 4383, "Returns correct number of hours when hoursOnly option is used" );
$test.countdown('destroy');
start();
}
});
});
asyncTest("Advanced Options - hoursOnly : Far Future Date (Years)", 1, function() {
var $test = $("#test"),
date = new Date(),
future60Date;
date.setMilliseconds(0);
future60Date = new Date( date.getTime() + ( 31557600 * 6000 )); //6 years in future
$test.countdown({
date: future60Date,
hoursOnly: true,
onChange: function( e,settings ) {
equal( settings.hrsLeft, 52596, "Returns correct number of hours when hoursOnly option is used" );
$test.countdown('destroy');
start();
}
});
});
asyncTest("Advanced Options - yearsAndMonths: Future Date", 2, function() {
var $test = $("#test"),
date = new Date(),
future60Date;
date.setMilliseconds(0);
//1 hour * 24 hours * 364 days * 2 years + 32 days
future60Date = new Date( date.getTime() + ( ( 86400 * 365000 * 2 ) + ( 86400 * 32000 ) ) );
$test.countdown({
date: future60Date,
yearsAndMonths: true,
onChange: function( e,settings ) {
equal( settings.yearsLeft, 2, "Returns correct number of years when yearsAndMonths option is used" );
equal( settings.monthsLeft, 1, "Returns correct number of months when yearsAndMonths option is used" );
$test.countdown('destroy');
start();
}
});
});
asyncTest("Advanced Options - yearsAndMonths : Past Date", 2, function() {
var $test = $("#test"),
date = new Date(),
pastDate;
date.setMilliseconds(0);
pastDate = new Date( date.getTime() - ( 2629800 * 11000 ) ); //11 months ago
$test.countdown({
date: pastDate,
direction: "up",
yearsAndMonths: true,
onChange: function( e,settings ) {
equal( settings.yearsLeft, 0, "Returns correct number of years when yearsAndMonths option is used" );
equal( settings.monthsLeft, 10, "Returns correct number of months when yearsAndMonths option is used" );
$test.countdown('destroy');
start();
}
});
});
asyncTest("Advanced Options - weeks", 1, function() {
var $test = $("#test"),
date = new Date(),
pastDate;
date.setMilliseconds(0);
date.setTime( date.getTime() - ( 3600 * 24 * 28000 ) ); // 4 Weeks ago
$test.countdown({
date: date,
direction: "up",
//clientdateNow: new Date( serverMilliseconds ),
//servertime: serverMilliseconds,
weeks: true,
onChange: function( e,settings ) {
equal( settings.weeksLeft, 4, "Returns correct number of weeks when weeks option is used" );
$test.countdown('destroy');
start();
}
});
});
asyncTest("Advanced Options - stopwatch", 3, function() {
var $test = $("#test"),
date = new Date(),
pastDate,
hours;
pastDate = new Date( date.getTime() - ( 2629800 * 11000 ) ); //11 months ago
$test.countdown({
date: pastDate,
onPause: function( event ) {
ok( true, "Paused Event Fired" );
},
onResume: function( event, s ) {
ok( $test.countdown('getSettings').hrsLeft === hours, 'Hours left is correct');
ok( true, "Resumed Event Fired" );
start();
}
});
$test.countdown('pause');
hours = $test.countdown('getSettings').hrsLeft;
setTimeout(function(){
$test.countdown('resume');
}, 2000)
});
test("Locale", 2, function() {
var $test = $("#test"),
date = new Date(),
future60Date = new Date( date.getTime() + ( 60000 * 2 ) ); //60 secs * 2 minutes
$.extend( $.fn.countdown.defaults, $.fn.countdown.locale['de'] );
$test.countdown({
date: future60Date
});
ok( $test.countdown('getSettings').yearText === $.fn.countdown.locale['de'].yearText, 'Locale text has been set');
$test.countdown('changeLocale', 'fr');
ok( $test.countdown('getSettings').yearText === $.fn.countdown.locale['fr'].yearText, 'Locale text has been changed');
});
test("omitZero Option", 1, function() {
var $test = $("#test"),
date = new Date(),
past60Date = new Date( date.getTime() - ( 60000 * 2 ) ); //Date in past, so countdown completes
$test.countdown({
date: past60Date,
omitZero: true
});
ok( $test.countdown('getSettings').omitZero === true, 'omitZero is set correctly');
});
test("isRTL - Right to Left", 1, function() {
var $test = $("#test"),
date = new Date(),
future60Date = new Date( date.getTime() + ( 60000 * 2 ) ); //60 secs * 2 minutes
$test.countdown({
date: future60Date,
isRTL: true
});
ok( $test.countdown('getSettings').isRTL === true, 'isRTL is set correctly');
});
test("Template", 1, function() {
var $test = $("#test"),
date = new Date(),
future60Date = new Date( date.getTime() + ( 60000 * 2 ) ); //60 secs * 2 minutes
$test.countdown({
date: future60Date,
template: '%y %m %h %i %s'
});
ok( $test.countdown('getSettings').template === '%y %m %h %i %s', 'template is set correctly');
});
test("Template - Remove un-used tokens", 1, function() {
var $test = $("#test"),
date = new Date(),
future60Date = new Date( date.getTime() + ( 60000 * 2 ) ); //60 secs * 2 minutes
$test.countdown({
date: future60Date,
template: '%y %m %h %i %s'
});
ok( $test.html().indexOf('%y') === -1, 'Template is removed correctly');
});
test("dataAttr", 6, function() {
var $test = $("#test");
$test.attr("data-cdate", "february 2, 2013 09:00:00");
$test.countdown({
dataAttr: "cdate"
});
ok( $test.countdown('getSettings', 'dateObj').getMonth() == 1, 'Get correct month');
ok( $test.countdown('getSettings', 'dateObj').getDate() == 2, 'Get correct day');
ok( $test.countdown('getSettings', 'dateObj').getFullYear() == 2013, 'Get correct year');
$test.countdown('destroy');
$test.attr("data-cdate", "april 3, 2014 09:00:00");
$test.countdown({
dataAttr: "cdate"
});
ok( $test.countdown('getSettings', 'dateObj').getMonth() == 3, 'Get correct month');
ok( $test.countdown('getSettings', 'dateObj').getDate() == 3, 'Get correct day');
ok( $test.countdown('getSettings', 'dateObj').getFullYear() == 2014, 'Get correct year');
$test.removeAttr("data-cdate");
});
| mit |
tempbottle/rust-peg | src/bin.rs | 948 | extern crate peg;
use std::env;
use std::fs::File;
use std::io::{Read, Write};
use std::io::{stdin, stdout, stderr};
use std::path::Path;
use std::process;
fn main() {
let args = env::args_os().collect::<Vec<_>>();
let progname = &args[0];
let mut log = stderr();
let fname: &str;
let mut source = String::new();
if args.len() == 2 && &args[1] != "-h" {
fname = args[1].to_str().unwrap();
File::open(Path::new(&args[1])).unwrap().read_to_string(&mut source).unwrap();
} else if args.len() == 1 {
fname = "<stdin>";
stdin().read_to_string(&mut source).unwrap();
} else {
writeln!(log, "Usage: {} [file]", progname.to_string_lossy()).unwrap();
process::exit(0);
}
match peg::compile(fname.to_owned(), source) {
Ok(parser) => {
let mut out = stdout();
writeln!(&mut out, "// Generated by rust-peg. Do not edit.").unwrap();
write!(&mut out, "{}", parser).unwrap();
}
Err(()) => {
process::exit(1);
}
}
}
| mit |
emmanuelroecker/php-sync-sftp | tests/GlSyncFtpTest.php | 7828 | <?php
/**
* Test GlSyncFtp
*
* PHP version 5.4
*
* @category GLICER
* @package GlHtml\Tests
* @author Emmanuel ROECKER
* @author Rym BOUCHAGOUR
* @copyright 2015 GLICER
* @license MIT
* @link http://dev.glicer.com/
*
* Created : 22/05/15
* File : GlSyncFtpTest.php
*
*/
namespace GlSyncFtp\Tests;
use GlSyncFtp\GlSyncFtp;
/**
* @covers \GlSyncFtp\GlSyncFtp
* @backupGlobals disabled
*/
class GlSyncFtpTest extends \PHPUnit_Framework_TestCase
{
private function assertAndRemove($elem, array &$list)
{
if (($key = array_search($elem, $list)) !== false) {
unset($list[$key]);
} else {
$this->fail($elem);
}
}
public function testFtpDeleteAll()
{
$ftp = new GlSyncFtp(FTP_SERVER_HOST, FTP_SERVER_PORT, FTP_SERVER_USER, FTP_SERVER_PASSWORD);
if (!is_dir(__DIR__ . '/delete')) {
mkdir(__DIR__ . '/delete');
};
$ftp->syncDirectory(__DIR__ . '/delete', '/data');
$files = [];
$dirs = [];
$ftp->getAllFiles('/data', $files, $dirs);
$ftp->disconnect();
$filesname = array_keys($files);
$dirsname = array_keys($dirs);
$this->assertCount(0, $filesname, var_export($filesname, true));
$this->assertCount(0, $dirsname, var_export($dirsname, true));
}
public function testFtpNew()
{
$ftp = new GlSyncFtp(FTP_SERVER_HOST, FTP_SERVER_PORT, FTP_SERVER_USER, FTP_SERVER_PASSWORD);
$listDirs = ["/data/dir1", "/data/dir3"];
$listFiles = ["/data/dir3/Test4.txt", "/data/dir1/test1.txt", "/data/test2.txt"];
$ftp->syncDirectory(
__DIR__ . '/new',
'/data',
function ($op, $path) use (&$listDirs, &$listFiles) {
switch ($op) {
case GlSyncFtp::CREATE_DIR:
$this->assertAndRemove($path, $listDirs);
break;
case GlSyncFtp::NEW_FILE:
$this->assertAndRemove($path, $listFiles);
break;
default:
$this->fail($op);
}
}
);
if (count($listDirs) > 0) {
$this->fail("bad dirs " . var_export($listDirs, true));
};
if (count($listFiles) > 0) {
$this->fail("bad files " . var_export($listFiles, true));
};
$files = [];
$dirs = [];
$ftp->getAllFiles('/data', $files, $dirs);
$ftp->disconnect();
$filesname = array_keys($files);
$dirsname = array_keys($dirs);
$this->assertCount(3, $filesname);
$this->assertContains("/dir1/test1.txt", $filesname);
$this->assertContains("/dir3/Test4.txt", $filesname);
$this->assertContains("/test2.txt", $filesname);
$this->assertCount(2, $dirsname);
$this->assertContains("/dir1", $dirsname);
$this->assertContains("/dir3", $dirsname);
}
public function testFtpUpdate()
{
$ftp = new GlSyncFtp(FTP_SERVER_HOST, FTP_SERVER_PORT, FTP_SERVER_USER, FTP_SERVER_PASSWORD);
$deleteFiles = ["/data/dir1/test1.txt", "/data/dir3/Test4.txt"];
$deleteDirs = ["/data/dir1"];
$createDirs = ["/data/dir2"];
$updateFiles = ["/data/test2.txt"];
$newFiles = ["/data/dir2/test3.txt", "/data/test2.txt", "/data/dir3/test4.txt"];
$ftp->syncDirectory(
__DIR__ . '/update',
'/data',
function ($op, $path) use (&$deleteFiles, &$deleteDirs, &$createDirs, &$updateFiles, &$newFiles) {
switch ($op) {
case GlSyncFtp::DELETE_FILE:
$this->assertAndRemove($path, $deleteFiles);
break;
case GlSyncFtp::DELETE_DIR:
$this->assertAndRemove($path, $deleteDirs);
break;
case GlSyncFtp::CREATE_DIR:
$this->assertAndRemove($path, $createDirs);
break;
case GlSyncFtp::UPDATE_FILE:
$this->assertAndRemove($path, $updateFiles);
break;
case GlSyncFtp::NEW_FILE:
$this->assertAndRemove($path, $newFiles);
break;
default:
$this->fail();
}
}
);
$files = [];
$dirs = [];
$ftp->getAllFiles('/data', $files, $dirs);
$ftp->disconnect();
$filesname = array_keys($files);
$dirsname = array_keys($dirs);
$this->assertCount(3, $filesname);
$this->assertContains("/dir2/test3.txt", $filesname);
$this->assertContains("/dir3/test4.txt", $filesname);
$this->assertContains("/test2.txt", $filesname);
$this->assertCount(2, $dirsname);
$this->assertContains("/dir2", $dirsname);
$this->assertContains("/dir3", $dirsname);
}
public function testFtpDelete()
{
$ftp = new GlSyncFtp(FTP_SERVER_HOST, FTP_SERVER_PORT, FTP_SERVER_USER, FTP_SERVER_PASSWORD);
$deleteDirs = ["/data/dir2", "/data/dir3"];
$deleteFiles = ["/data/dir2/test3.txt", "/data/test2.txt", "/data/dir3/test4.txt"];
$ftp->syncDirectory(
__DIR__ . '/delete',
'/data',
function ($op, $path) use (&$deleteDirs, &$deleteFiles) {
switch ($op) {
case GlSyncFtp::DELETE_DIR:
$this->assertAndRemove($path, $deleteDirs);
break;
case GlSyncFtp::DELETE_FILE:
$this->assertAndRemove($path, $deleteFiles);
break;
default:
$this->fail();
}
}
);
$files = [];
$dirs = [];
$ftp->getAllFiles('/data', $files, $dirs);
$ftp->disconnect();
$this->assertCount(0, $files);
$this->assertCount(0, $dirs);
}
public function testFtpDirectories()
{
$list = [
__DIR__ . '/new' => '/data',
__DIR__ . '/update' => '/data',
__DIR__ . '/delete' => '/data'
];
$ftp = new GlSyncFtp(FTP_SERVER_HOST, FTP_SERVER_PORT, FTP_SERVER_USER, FTP_SERVER_PASSWORD);
$createDirs = ["/data/dir1", "/data/dir3", "/data/dir2"];
$newFiles = [
"/data/dir1/test1.txt",
"/data/test2.txt",
"/data/dir3/test4.txt",
"/data/dir3/Test4.txt",
"/data/dir2/test3.txt"
];
$ftp->syncDirectories(
$list,
function ($src, $dst) {
},
function ($op, $path) use (&$createDirs, &$newFiles) {
switch ($op) {
case GlSyncFtp::CREATE_DIR:
$this->assertAndRemove($path, $createDirs);
break;
case GlSyncFtp::NEW_FILE:
$this->assertAndRemove($path, $newFiles);
break;
default:
}
}
);
$files = [];
$dirs = [];
$ftp->getAllFiles('/data', $files, $dirs);
$ftp->disconnect();
$this->assertCount(0, $files);
$this->assertCount(0, $dirs);
}
}
| mit |
vuonghuynhthanhtu/administrator.lacasa.com | application/libraries/braintree-php-2.38.0/vendor/phpunit/phpunit/PHPUnit/Util/DeprecatedFeature/Logger.php | 6939 | <?php
/**
* PHPUnit
*
* Copyright (c) 2001-2014, Sebastian Bergmann <[email protected]>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Sebastian Bergmann nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package PHPUnit
* @subpackage Framework
* @author Ralph Schindler <[email protected]>
* @author Sebastian Bergmann <[email protected]>
* @copyright 2001-2014 Sebastian Bergmann <[email protected]>
* @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License
* @link http://www.phpunit.de/
* @since File available since Release 3.5.7
*/
/**
* Test Listener that tracks the usage of deprecated features.
*
* @package PHPUnit
* @subpackage Framework
* @author Ralph Schindler <[email protected]>
* @author Sebastian Bergmann <[email protected]>
* @copyright 2001-2014 Sebastian Bergmann <[email protected]>
* @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License
* @link http://www.phpunit.de/
* @since Class available since Release 3.5.7
*/
class PHPUnit_Util_DeprecatedFeature_Logger implements PHPUnit_Framework_TestListener
{
/**
* @var PHPUnit_Framework_TestCase
*/
protected static $currentTest = NULL;
/**
* This is the publicly accessible API for notifying the system that a
* deprecated feature has been used.
*
* If it is run via a TestRunner and the test extends
* PHPUnit_Framework_TestCase, then this will inject the result into the
* test runner for display, if not, it will throw the notice to STDERR.
*
* @param string $message
* @param int|bool $backtraceDepth
*/
public static function log($message, $backtraceDepth = 2)
{
if ($backtraceDepth !== FALSE) {
$trace = debug_backtrace(FALSE);
if (is_int($backtraceDepth)) {
$traceItem = $trace[$backtraceDepth];
}
if (!isset($traceItem['file'])) {
$reflectionClass = new ReflectionClass($traceItem['class']);
$traceItem['file'] = $reflectionClass->getFileName();
}
if (!isset($traceItem['line']) &&
isset($traceItem['class']) &&
isset($traceItem['function'])) {
if (!isset($reflectionClass)) {
$reflectionClass = new ReflectionClass($traceItem['class']);
}
$method = $reflectionClass->getMethod($traceItem['function']);
$traceItem['line'] = '(between ' . $method->getStartLine() .
' and ' . $method->getEndLine() . ')';
}
}
$deprecatedFeature = new PHPUnit_Util_DeprecatedFeature(
$message, $traceItem
);
if (self::$currentTest instanceof PHPUnit_Framework_TestCase) {
$result = self::$currentTest->getTestResultObject();
$result->addDeprecatedFeature($deprecatedFeature);
} else {
file_put_contents('php://stderr', $deprecatedFeature);
}
}
/**
* An error occurred.
*
* @param PHPUnit_Framework_Test $test
* @param Exception $e
* @param float $time
*/
public function addError(PHPUnit_Framework_Test $test, Exception $e, $time)
{
}
/**
* A failure occurred.
*
* @param PHPUnit_Framework_Test $test
* @param PHPUnit_Framework_AssertionFailedError $e
* @param float $time
*/
public function addFailure(PHPUnit_Framework_Test $test, PHPUnit_Framework_AssertionFailedError $e, $time)
{
}
/**
* Incomplete test.
*
* @param PHPUnit_Framework_Test $test
* @param Exception $e
* @param float $time
*/
public function addIncompleteTest(PHPUnit_Framework_Test $test, Exception $e, $time)
{
}
/**
* Skipped test.
*
* @param PHPUnit_Framework_Test $test
* @param Exception $e
* @param float $time
* @since Method available since Release 3.0.0
*/
public function addSkippedTest(PHPUnit_Framework_Test $test, Exception $e, $time)
{
}
/**
* A test suite started.
*
* @param PHPUnit_Framework_TestSuite $suite
* @since Method available since Release 2.2.0
*/
public function startTestSuite(PHPUnit_Framework_TestSuite $suite)
{
}
/**
* A test suite ended.
*
* @param PHPUnit_Framework_TestSuite $suite
* @since Method available since Release 2.2.0
*/
public function endTestSuite(PHPUnit_Framework_TestSuite $suite)
{
}
/**
* A test started.
*
* @param PHPUnit_Framework_Test $test
*/
public function startTest(PHPUnit_Framework_Test $test)
{
self::$currentTest = $test;
}
/**
* A test ended.
*
* @param PHPUnit_Framework_Test $test
* @param float $time
*/
public function endTest(PHPUnit_Framework_Test $test, $time)
{
self::$currentTest = NULL;
}
}
| mit |
palicao/symrsvp | web/app_dev.php | 1195 | <?php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;
// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
//umask(0000);
// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
/*
if (isset($_SERVER['HTTP_CLIENT_IP'])
|| isset($_SERVER['HTTP_X_FORWARDED_FOR'])
|| !in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', 'fe80::1', '::1'))
) {
header('HTTP/1.0 403 Forbidden');
exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}*/
$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
Debug::enable();
require_once __DIR__.'/../app/AppKernel.php';
$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
Request::enableHttpMethodParameterOverride();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
| mit |
conversionfoundry/breeze_commerce | spec/models/breeze/commerce/shipping_method_spec.rb | 2024 | require 'spec_helper'
describe Breeze::Commerce::ShippingMethod do
it "has a valid factory" do
create(:shipping_method).should be_valid
end
it "is invalid without a name" do
build(:shipping_method, name: nil).should_not be_valid
end
it "is invalid with a duplicate name" do
create(:shipping_method, name: "Duplicate Shipping Method Name")
build(:shipping_method, name: "Duplicate Shipping Method Name").should_not be_valid
end
it "is invalid without price_cents" do
build(:shipping_method, price_cents: nil).should_not be_valid
end
it "ignores non-numerical price_cents" do
build(:shipping_method, price_cents: 'Eleventy-twelve').price_cents.should eq 0
end
it "is valid with zero price_cents" do
build(:shipping_method, price_cents: 0).should be_valid
end
it "is the default shipping method if it was the first created" do
store = Breeze::Commerce::Store.first
first_shipping_method = Breeze::Commerce::ShippingMethod.first
second_shipping_method = create(:shipping_method)
store.default_shipping_method.should eq first_shipping_method
store.default_shipping_method.should_not eq second_shipping_method
end
it "can set and retrieve a price" do
shipping_method = create :shipping_method
shipping_method.price = 5546
shipping_method.price.should eq 5546
end
describe "scopes" do
before :each do
@shipping_method_1 = create(:shipping_method)
@shipping_method_2 = create(:shipping_method, archived: true)
end
context "unarchived scope" do
it "returns an array of unarchived shipping methods" do
Breeze::Commerce::ShippingMethod.unarchived.to_a.should include @shipping_method_1
Breeze::Commerce::ShippingMethod.unarchived.should_not include @shipping_method_2
end
end
context "archived scope" do
it "returns an array of archived shipping methods" do
Breeze::Commerce::ShippingMethod.archived.to_a.should include @shipping_method_2
Breeze::Commerce::ShippingMethod.archived.should_not include @shipping_method_1
end
end
end
end | mit |
Vedin/corefxlab | src/System.Buffers.Experimental/System/Buffers/BufferManager.cs | 1633 | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace System.Buffers.Pools
{
public unsafe sealed partial class NativeBufferPool : BufferPool
{
internal sealed class BufferManager : ReferenceCountedBuffer<byte>
{
public BufferManager(NativeBufferPool pool, IntPtr memory, int length)
{
_pool = pool;
_pointer = memory;
_length = length;
}
public IntPtr Pointer => _pointer;
public override int Length => _length;
public override Span<byte> AsSpan(int index, int length)
{
if (IsDisposed) BuffersExperimentalThrowHelper.ThrowObjectDisposedException(nameof(BufferManager));
return new Span<byte>(_pointer.ToPointer(), _length).Slice(index, length);
}
protected override void Dispose(bool disposing)
{
_pool.Return(this);
base.Dispose(disposing);
}
protected override bool TryGetArray(out ArraySegment<byte> arraySegment)
{
arraySegment = default;
return false;
}
public override BufferHandle Pin(int index = 0)
{
Retain();
return new BufferHandle(this, Add(_pointer.ToPointer(), index));
}
private readonly NativeBufferPool _pool;
IntPtr _pointer;
int _length;
}
}
}
| mit |
raavanan/photosticker-app | js/app.js | 381 | angular.module('origami', ['ui.router'])
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('editor', {
url: "/editor",
templateUrl: "partials/editor.html",
controller: "editorCtrl"
})
$urlRouterProvider.otherwise("/editor");
})
.controller('appCtrl', ["$scope", appCtrl])
.controller('editorCtrl',["$scope", editorCtrl])
| mit |
Karasiq/scalajs-highcharts | src/main/scala/com/highstock/config/PlotOptionsHeatmapPathfinderMarker.scala | 5378 | /**
* Automatically generated file. Please do not edit.
* @author Highcharts Config Generator by Karasiq
* @see [[http://api.highcharts.com/highstock]]
*/
package com.highstock.config
import scalajs.js, js.`|`
import com.highcharts.CleanJsObject
import com.highcharts.HighchartsUtils._
/**
* @note JavaScript name: <code>plotOptions-heatmap-pathfinder-marker</code>
*/
@js.annotation.ScalaJSDefined
class PlotOptionsHeatmapPathfinderMarker extends com.highcharts.HighchartsGenericObject {
/**
* <p>Enable markers for the connectors.</p>
* @since 6.2.0
*/
val enabled: js.UndefOr[Boolean] = js.undefined
/**
* <p>Horizontal alignment of the markers relative to the points.</p>
* @since 6.2.0
*/
val align: js.UndefOr[String] = js.undefined
/**
* <p>Vertical alignment of the markers relative to the points.</p>
* @since 6.2.0
*/
val verticalAlign: js.UndefOr[String] = js.undefined
/**
* <p>Whether or not to draw the markers inside the points.</p>
* @since 6.2.0
*/
val inside: js.UndefOr[Boolean] = js.undefined
/**
* <p>Set the line/border width of the pathfinder markers.</p>
* @since 6.2.0
*/
val lineWidth: js.UndefOr[Double] = js.undefined
/**
* <p>Set the radius of the pathfinder markers. The default is
* automatically computed based on the algorithmMargin setting.</p>
* <p>Setting marker.width and marker.height will override this
* setting.</p>
* @since 6.2.0
*/
val radius: js.UndefOr[Double] = js.undefined
/**
* <p>Set the width of the pathfinder markers. If not supplied, this
* is inferred from the marker radius.</p>
* @since 6.2.0
*/
val width: js.UndefOr[Double] = js.undefined
/**
* <p>Set the height of the pathfinder markers. If not supplied, this
* is inferred from the marker radius.</p>
* @since 6.2.0
*/
val height: js.UndefOr[Double] = js.undefined
/**
* <p>Set the color of the pathfinder markers. By default this is the
* same as the connector color.</p>
* @since 6.2.0
*/
val color: js.UndefOr[String | js.Object] = js.undefined
/**
* <p>Set the line/border color of the pathfinder markers. By default
* this is the same as the marker color.</p>
* @since 6.2.0
*/
val lineColor: js.UndefOr[String | js.Object] = js.undefined
}
object PlotOptionsHeatmapPathfinderMarker {
/**
* @param enabled <p>Enable markers for the connectors.</p>
* @param align <p>Horizontal alignment of the markers relative to the points.</p>
* @param verticalAlign <p>Vertical alignment of the markers relative to the points.</p>
* @param inside <p>Whether or not to draw the markers inside the points.</p>
* @param lineWidth <p>Set the line/border width of the pathfinder markers.</p>
* @param radius <p>Set the radius of the pathfinder markers. The default is. automatically computed based on the algorithmMargin setting.</p>. <p>Setting marker.width and marker.height will override this. setting.</p>
* @param width <p>Set the width of the pathfinder markers. If not supplied, this. is inferred from the marker radius.</p>
* @param height <p>Set the height of the pathfinder markers. If not supplied, this. is inferred from the marker radius.</p>
* @param color <p>Set the color of the pathfinder markers. By default this is the. same as the connector color.</p>
* @param lineColor <p>Set the line/border color of the pathfinder markers. By default. this is the same as the marker color.</p>
*/
def apply(enabled: js.UndefOr[Boolean] = js.undefined, align: js.UndefOr[String] = js.undefined, verticalAlign: js.UndefOr[String] = js.undefined, inside: js.UndefOr[Boolean] = js.undefined, lineWidth: js.UndefOr[Double] = js.undefined, radius: js.UndefOr[Double] = js.undefined, width: js.UndefOr[Double] = js.undefined, height: js.UndefOr[Double] = js.undefined, color: js.UndefOr[String | js.Object] = js.undefined, lineColor: js.UndefOr[String | js.Object] = js.undefined): PlotOptionsHeatmapPathfinderMarker = {
val enabledOuter: js.UndefOr[Boolean] = enabled
val alignOuter: js.UndefOr[String] = align
val verticalAlignOuter: js.UndefOr[String] = verticalAlign
val insideOuter: js.UndefOr[Boolean] = inside
val lineWidthOuter: js.UndefOr[Double] = lineWidth
val radiusOuter: js.UndefOr[Double] = radius
val widthOuter: js.UndefOr[Double] = width
val heightOuter: js.UndefOr[Double] = height
val colorOuter: js.UndefOr[String | js.Object] = color
val lineColorOuter: js.UndefOr[String | js.Object] = lineColor
com.highcharts.HighchartsGenericObject.toCleanObject(new PlotOptionsHeatmapPathfinderMarker {
override val enabled: js.UndefOr[Boolean] = enabledOuter
override val align: js.UndefOr[String] = alignOuter
override val verticalAlign: js.UndefOr[String] = verticalAlignOuter
override val inside: js.UndefOr[Boolean] = insideOuter
override val lineWidth: js.UndefOr[Double] = lineWidthOuter
override val radius: js.UndefOr[Double] = radiusOuter
override val width: js.UndefOr[Double] = widthOuter
override val height: js.UndefOr[Double] = heightOuter
override val color: js.UndefOr[String | js.Object] = colorOuter
override val lineColor: js.UndefOr[String | js.Object] = lineColorOuter
})
}
}
| mit |
cuo9958/jquery-xcalendar | src/xcalendar.lite.js | 7066 | $.fn.xcalendar = function(options) {
var obj = $(this);
var defaults = {
onRender: null,
onRefresh: null,
onEnter: null,
onEnd: null,
onSelect: null
}
var options = $.extend(defaults, options);
var title, pre_month, next_month, now = new Date(),
days, min_height = 0,
now_month = now.getMonth(),
now_year = now.getFullYear(),
refresh, setting, today, tmp_today = new Date(),
day_active = false;
//日历的结构
var html = "<div class=\"title\"><a class=\"refresh\" href=\"javascript:\" ;></a><a class=\"today\" href=\"javascript:\">Today</a><span></span><a class=\"setting\" href=\"javascript:;\"></a><a class=\"next\" href=\"javascript:;\"></a><a class=\"pre\" href=\"javascript:;\"></a></div>" +
"<div class=\"weeks list\">" +
"<div class=\"week item\">Sun</div>" +
"<div class=\"week item\">Mon</div>" +
"<div class=\"week item\">Tue</div>" +
"<div class=\"week item\">Wed</div>" +
"<div class=\"week item\">Thu</div>" +
"<div class=\"week item\">Fri</div>" +
"<div class=\"week item\">Sat</div>" +
"</div><div class=\"days list\"></div>";
obj.html(html);
function calDate(i) {
if (i) now.setMonth(now.getMonth() + i);
now_month = now.getMonth();
now_year = now.getFullYear();
render();
}
//获取本月的具体天数
function getMonthes() {
var temp_date = now;
var first_week = temp_date.getDay();
var days_count = new Date(now_year, now_month + 1, 0).getDate();
var pre_month = new Date(now_year, now_month - 1, 0);
var pre_days_count = pre_month.getDate();
var day_arr = [];
for (var i = 0; i < first_week; i++) {
day_arr[first_week - i - 1] = {
day: pre_days_count - i,
date: new Date(now_year, now_month - 1, pre_days_count - i)
}
}
for (var i = 0; i < days_count; i++) {
day_arr[i + first_week] = {
day: i + 1,
date: new Date(now_year, now_month, i + 1)
}
}
var len = day_arr.length % 7;
for (var i = 0; i < 7 - len; i++) {
day_arr.push({
day: i + 1,
date: new Date(now_year, now_month + 1, i + 1)
});
}
return day_arr;
}
function load() {
days.html("<div class=\"load\"></div>");
}
function toString(curr_day) {
return curr_day.getFullYear() + "-" + (curr_day.getMonth() + 1) + "-" + curr_day.getDate();
}
function getRandomColor() {
var colors = [
"rgb(245, 105, 84)", "rgb(0, 115, 183)", "rgb(0, 192, 239)", "rgb(0, 166, 90)", "rgb(245, 105, 24)", "#025aa5", "#f0ad4e", "#5bc0de", "#5cb85c", "#d9534f"
];
return colors[Math.round(Math.random() * (colors.length - 1))];
}
//渲染方法
function render() {
function update() {
var arr = getMonthes();
title.text((now_month + 1) + "/" + now_year);
var cls = "pre";
days.empty();
for (var i = 0; i < arr.length; i++) {
var cls_now = "";
if (now_year == tmp_today.getFullYear() && now_month == tmp_today.getMonth() && arr[i].day == tmp_today.getDate()) cls_now = "now";
cls = cls == "" && arr[i].day == 1 ? "next" : cls == "pre" && arr[i].day == 1 ? "" : cls;
var data = options.onRender && options.onRender(arr[i].date);
var html = "<div class=\"day item " + cls + " " + cls_now + "\" style=\"min-height:" + min_height + "px;\" data-day=\"" + toString(arr[i].date) + "\">" +
"<div class=\"date\">" + arr[i].day + "</div>" +
"<div class=\"txt\">";
for (var j = 0; j < data.length; j++) {
html += "<div style=\"background:" + getRandomColor() + ";\">" + data[j] + "</div>";
}
html += "</div></div>";
days.append(html);
}
options.onEnd && options.onEnd(now);
}
if (options.onEnter) {
load();
options.onEnter(now, update);
} else { update(); }
}
//初始化
function init() {
title = $(".title span", obj);
pre_month = $(".title .pre", obj);
next_month = $(".title .next", obj);
days = $(".days", obj);
refresh = $(".title .refresh", obj);
today = $(".title .today", obj);
setting = $(".title .setting", obj);
min_height = days.width() / 7 >> 0;
now.setDate(1);
render();
pre_month.click(function() {
calDate(-1);
});
next_month.click(function() {
calDate(1);
});
refresh.click(function() {
options.onRefresh && options.onRefresh(now);
render();
});
today.click(function() {
now = new Date();
calDate();
render();
});
$(".weeks .week", obj).click(function() {
var index = $(this).index();
$(".day", obj).each(function() {
if ($(this).index() % 7 == index && !$(this).hasClass("active")) {
$(this).addClass("active");
} else {
$(this).removeClass("active");
}
});
});
obj.on("mouseleave", function() {
day_active = false;
}).on("mousedown", ".day", function() {
day_active = true;
}).on("mouseup", ".day", function() {
day_active = false;
}).on("mouseover", ".day", function() {
if (day_active) $(this).addClass("active");
}).on("click", ".day", function() {
if ($(this).hasClass("active")) {
$(this).removeClass("active");
} else {
$(this).addClass("active");
}
});
setting.click(function() {
options.onSelect && options.onSelect($(".days .active", obj));
});
}
init();
} | mit |
qcam/3llo | spec/3llo/command/card/list_spec.rb | 2170 | require "spec_helper"
describe "card list", type: :integration do
include IntegrationSpecHelper
before { $application = build_container() }
after { $application = nil }
it "requires board to be selected" do
interface = make_interface($application)
execute_command("card list")
output_string = interface.output.string
expect(output_string).to match("Board has not been selected.")
end
it "lists all cards in the selected board" do
interface = make_interface($application)
select_board($application, make_board("board:1"))
make_client_mock($application) do |client_mock|
lists_payload = [
{"id" => "list:1", "name" => "List 1"},
{"id" => "list:2", "name" => "List 2"}
]
expect(client_mock).to(
receive(:get)
.with(
req_path("/boards/board:1/lists", {list: true}),
{}
)
.and_return(lists_payload)
.once()
)
list1_card_payload = [
{
"id" => "card:1",
"name" => "Card 1",
"desc" => "first card",
"shortUrl" => "https://example.com/cards/1"
}
]
expect(client_mock).to(
receive(:get)
.with(
req_path("/lists/list:1/cards", {members: "true", member_fields: "id,username"}),
{}
)
.and_return(list1_card_payload)
.once()
)
list2_card_payload = [
{
"id" => "card:2",
"name" => "Card 2",
"desc" => "second card",
"shortUrl" => "https://example.com/cards/2"
}
]
expect(client_mock).to(
receive(:get)
.with(
req_path("/lists/list:2/cards", {members: "true", member_fields: "id,username"}),
{}
)
.and_return(list2_card_payload)
.once()
)
end
execute_command("card list")
output_string = interface.output.string
expect(output_string).to match("card:1")
expect(output_string).to match("card:2")
expect(output_string).to match("Card 1")
expect(output_string).to match("Card 2")
end
end
| mit |
conan-io/conan | conans/test/functional/command/export_test.py | 833 | import textwrap
import unittest
import pytest
from conans.model.ref import ConanFileReference
from conans.test.utils.tools import TestClient
class ExportMetadataTest(unittest.TestCase):
conanfile = textwrap.dedent("""
from conans import ConanFile
class Lib(ConanFile):
revision_mode = "{revision_mode}"
""")
summary_hash = "bfe8b4a6a2a74966c0c4e0b34705004a"
@pytest.mark.tool_git
def test_revision_mode_scm(self):
t = TestClient()
commit = t.init_git_repo({'conanfile.py': self.conanfile.format(revision_mode="scm")})
ref = ConanFileReference.loads("name/version@user/channel")
t.run("export . {}".format(ref))
meta = t.cache.package_layout(ref, short_paths=False).load_metadata()
self.assertEqual(meta.recipe.revision, commit)
| mit |
yogakurniawan/phone-catalogues | app/routes.js | 4765 | // These are the pages you can go to.
// They are all wrapped in the App component, which should contain the navbar etc
// See http://blog.mxstbr.com/2016/01/react-apps-with-pages for more information
// about the code splitting business
import { getAsyncInjectors } from './utils/asyncInjectors';
const errorLoading = (err) => {
console.error('Dynamic page loading failed', err); // eslint-disable-line no-console
};
const loadModule = (cb) => (componentModule) => {
cb(null, componentModule.default);
};
export default function createRoutes(store) {
// create reusable async injectors using getAsyncInjectors factory
const { injectReducer, injectSagas } = getAsyncInjectors(store);
return [
{
path: '/',
name: 'brands',
getComponent(nextState, cb) {
const importModules = Promise.all([
import('containers/BrandsPage/reducer'),
import('containers/ProductsPage/reducer'),
import('containers/BrandsPage/sagas'),
import('containers/ProductsPage/sagas'),
import('containers/BrandsPage'),
]);
const renderRoute = loadModule(cb);
importModules.then(([brandReducer, productReducer, brandSagas, productSagas, component]) => {
injectReducer('brands', brandReducer.default);
injectReducer('products', productReducer.default);
injectSagas(brandSagas.default);
injectSagas(productSagas.default);
renderRoute(component);
});
importModules.catch(errorLoading);
},
},
{
path: '/search',
name: 'search',
getComponent(nextState, cb) {
const importModules = Promise.all([
import('containers/App/actions'),
import('containers/SearchPage/reducer'),
import('containers/SearchPage/sagas'),
import('containers/SearchPage'),
]);
const renderRoute = loadModule(cb);
importModules.then(([appActions, reducer, sagas, component]) => {
injectReducer('search', reducer.default);
injectSagas(sagas.default);
// console.log(nextState.location.query);
store.dispatch(appActions.setSearchQuery(nextState.location.query.q));
renderRoute(component);
});
importModules.catch(errorLoading);
},
},
{
path: 'devices/:brand',
name: 'products',
getComponent(nextState, cb) {
const importModules = Promise.all([
import('containers/ProductsPage/actions'),
import('containers/App/actions'),
import('containers/ProductsPage/reducer'),
import('containers/ProductsPage/sagas'),
import('containers/ProductsPage'),
]);
const renderRoute = loadModule(cb);
importModules.then(([productsActions, appActions, reducer, sagas, component]) => {
injectReducer('products', reducer.default);
injectSagas(sagas.default);
store.dispatch(appActions.setProductBrand(nextState.params.brand));
store.dispatch(productsActions.setPage(parseInt(nextState.location.query.page, 10)));
renderRoute(component);
});
importModules.catch(errorLoading);
},
},
{
path: 'detail',
name: 'deviceDetail',
getComponent(nextState, cb) {
const importModules = Promise.all([
import('containers/DeviceDetailPage/actions'),
import('containers/App/actions'),
import('containers/DeviceDetailPage/reducer'),
import('containers/ProductsPage/reducer'),
import('containers/DeviceDetailPage/sagas'),
import('containers/ProductsPage/sagas'),
import('containers/DeviceDetailPage'),
]);
const renderRoute = loadModule(cb);
importModules.then(([
deviceDetailActions,
appActions,
deviceDetailreducer,
productReducer,
deviceDetailSagas,
productSagas,
component,
]) => {
injectReducer('deviceDetail', deviceDetailreducer.default);
injectReducer('products', productReducer.default);
injectSagas(deviceDetailSagas.default);
injectSagas(productSagas.default);
store.dispatch(appActions.setProductBrand(nextState.location.query.brand));
store.dispatch(deviceDetailActions.setDeviceName(nextState.location.query.device));
renderRoute(component);
});
importModules.catch(errorLoading);
},
},
{
path: '*',
name: 'notfound',
getComponent(nextState, cb) {
import('containers/NotFoundPage')
.then(loadModule(cb))
.catch(errorLoading);
},
},
];
}
| mit |
hawkphantomnet/leetcode | InterleavingString/Solution.js | 873 | /**
* @param {string} s1
* @param {string} s2
* @param {string} s3
* @return {boolean}
*/
var isInterleave = function(s1, s2, s3) {
let size1 = s1.length;
let size2 = s2.length;
let size3 = s3.length;
if (size1 + size2 != size3) return false;
let dp = [];
for (let i = 0; i <= size1; i++) {
dp[i] = [];
for (let j = 0; j <= size2; j++) {
if (i === 0 && j === 0) {
dp[i][j] = true;
} else if (i === 0) {
dp[i][j] = (dp[i][j - 1] && s2[j - 1] == s3[i + j - 1]);
} else if (j === 0) {
dp[i][j] = (dp[i - 1][j] && s1[i - 1] == s3[i + j - 1]);
} else {
dp[i][j] = ((dp[i][j - 1] && s2[j - 1] == s3[i + j - 1]) || (dp[i - 1][j] && s1[i - 1] == s3[i + j - 1]));
}
}
}
return dp[size1][size2];
}; | mit |
qweqq/dwmb | ui/js/route.js | 794 | ( function () {
var menuUrl;
var jsUrl;
if ( HELPERS_MODULE.checkCookie( 'sessionId' ) ) {
menuUrl = "../loged-user-header.html";
jsUrl = "js/user.js";
} else {
menuUrl = "../main-header.html";
}
var mainJsUrl = "js/main.js";
var contentUrl = "../main-content.html";
$.ajax({
url: menuUrl,
context: document.body
}).done( function( data ) {
$( '.menu' ).append( data );
$.ajax({
url: contentUrl,
context: document.body
}).done( function( data ) {
$( '.content-container' ).append( data );
$.ajax({
url: mainJsUrl,
context: document.body
});
if ( jsUrl != 'undefined' ) {
$.ajax({
url: jsUrl,
context: document.body
});
}
});
});
} )(); | mit |
lidox/nccn-distress-thermometer | NCCN/app/src/main/java/com/artursworld/nccn/controller/util/OperationType.java | 515 | package com.artursworld.nccn.controller.util;
import java.util.HashMap;
import java.util.Map;
public enum OperationType {
PRE, POST, FOLLOW_UP;
private static final Map<String, OperationType> lookupByName = new HashMap<String, OperationType>();
static {
for (OperationType g : values()) {
lookupByName.put(g.name(), g);
}
}
public static OperationType findByName(String name) {
name = name.toUpperCase();
return lookupByName.get(name);
}
}
| mit |
barulicm/GazeboWorldDesigner | sdf/Color.cpp | 903 | #include "Color.h"
#include <sstream>
using namespace std;
Color::Color() {}
Color::Color(double red, double green, double blue, double alpha)
: r(red), g(green), b(blue), a(alpha) {}
QDomElement Color::toXML(QDomDocument &document) const {
QDomElement element = document.createElement("color");
element.appendChild(document.createTextNode((to_string(r) + " " + to_string(g) + " " + to_string(b) + " " + to_string(a)).c_str()));
return element;
}
Color Color::fromString(const std::string &s) {
stringstream ss{s};
Color color;
ss >> color.r;
ss >> color.g;
ss >> color.b;
ss >> color.a;
return color;
}
template<>
QDomElement SDFElement::optionalToXML(QDomDocument &document, const std::experimental::optional<Color> &optional) const {
if(optional) {
return optional->toXML(document);
} else {
return QDomElement{};
}
}
| mit |
kb-diangelo/phase-0 | week-7/group_project_solution.js | 737 | function sum(array_of_vals) {
var container = 0;
for (var counter = 0; counter < array_of_vals.length; counter++) {
container += array_of_vals[counter];
}
return container;
}
function median(array_of_vals) {
array_of_vals.sort()
if (array_of_vals.length % 2 != 0) {
var median_index = Math.floor(array_of_vals.length/2);
return array_of_vals[median_index];
} else {
var median_index = array_of_vals.length/2;
return (array_of_vals[median_index] + array_of_vals[median_index-1])/2;
}
}
function pony(){
console.log(" ./|,,/|");
console.log(" < o o)")
console.log(" <\\ ( |")
console.log(" <\\\\ |\\ |")
console.log(" <\\\\\\ |(__)")
console.log(" <\\\\\\\\ |")
} | mit |
dherault/serverless-offline | examples/tools/nodemon/src/handler.js | 164 | 'use strict'
const { stringify } = JSON
exports.hello = async function hello() {
return {
body: stringify({ hello: 'nodemon' }),
statusCode: 200,
}
}
| mit |
fashionweb/moraso | library/Aitsu/Init/SkinSource.php | 2802 | <?php
/**
* SkinSource.
*
* @author Christian Kehres, webtischlerei.de
* @author Frank Ammari, Ammari & Ammari GbR
* @author Andreas Kummer, w3concepts AG
* @copyright Copyright © 2010,webtischlerei.de
* @copyright Copyright © 2011, w3concepts AG
*/
class Aitsu_Init_SkinSource implements Aitsu_Event_Listener_Interface {
public static function notify(Aitsu_Event_Abstract $event) {
if (!isset ($_GET['skinsource'])) {
return;
}
if (ob_get_level() > 0) {
ob_end_clean();
}
if (isset ($_SERVER['HTTP_IF_NONE_MATCH'])) {
$etag = $_SERVER['HTTP_IF_NONE_MATCH'];
}
$source = $_GET['skinsource'];
if (substr($source, 0, 6) == 'admin/') {
$source = substr($source, 6);
}
$exploded = explode("/", $source);
$expires = 60 * 60 * 24 * 7;
header("Pragma: public");
header("Cache-Control: max-age=" . $expires);
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $expires) . ' GMT');
$file_extension = strtolower(pathinfo(end($exploded), PATHINFO_EXTENSION));
self :: setContentTypeHeader($file_extension);
if (isset ($etag)) {
$content = self :: _cache($etag);
}
if (isset ($content) && $content) {
header("HTTP/1.1 304 Not Modified");
header("Connection: Close");
} else {
$location = APPLICATION_PATH . "/skins/" . Aitsu_Registry :: get()->config->skin . "/{$source}";
if (is_readable($location)) {
$content = file_get_contents($location);
} else {
header("HTTP/1.1 404 Not Found");
header("Connection: Close");
exit ();
}
if ($file_extension === 'css') {
$etag = hash('md4', $content);
self :: _cache($etag, $content, array (
'css'
));
}
if ($file_extension === 'js') {
$etag = hash('md4', $content);
self :: _cache($etag, $content, array (
'js'
));
}
if (!isset ($etag)) {
$etag = hash('md4', $content);
}
header("ETag: {$etag}");
echo $content;
}
exit (0);
}
private static function _cache($etag, $content = null, array $tags = null) {
if (isset ($content)) {
Aitsu_Cache :: getInstance($etag)->save($content, $tags);
} else {
return Aitsu_Cache :: getInstance($etag)->load();
}
}
private static function setContentTypeHeader($file_extension) {
switch ($file_extension) {
case 'css' :
header('Content-type: text/css');
break;
case 'js' :
header('Content-type: application/javascript');
break;
case 'png' :
header('Content-type: image/png');
break;
case 'gif' :
header('Content-type: image/gif');
break;
case 'jpg' :
header('Content-type: image/jpeg');
break;
case 'jpeg' :
header('Content-type: image/jpeg');
break;
case 'pdf' :
header('Content-type: application/pdf');
break;
default :
break;
}
}
} | mit |
swimmesberger/OSUtil | org/fseek/thedeath/os/linux/LinuxUserDirectoryGuess.java | 3495 | /*
* The MIT License
*
* Copyright 2014 Simon Wimmesberger.
*
* 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.fseek.thedeath.os.linux;
import java.io.File;
import org.fseek.thedeath.os.DefaultRecentFolder;
/**
*
* @author Simon Wimmesberger
*/
public class LinuxUserDirectoryGuess implements LinuxUserDirectory{
protected static final String[] DOWNLOAD_TRIES = {"Downloads"};
protected static final String[] DESKTOP_TRIES = {"Desktop"};
protected static final String[] PICTURES_TRIES = {"Pictures", "Bilder"};
protected static final String[] DOCUMENTS_TRIES = {"Documents", "Dokumente"};
protected static final String[] VIDEOS_TRIES = {"Videos"};
protected static final String[] MUSIC_TRIES = {"Music", "Musik"};
@Override
public File getUserDirectory(String key) {
return getUserDirectoryImpl(key);
}
protected File getUserDirectoryImpl(String key){
switch(key){
case DESKTOP_DIR_KEY:
return getDesktopFolder();
case PICTURES_DIR_KEY:
return getImageFolder();
case DOCUMENTS_DIR_KEY:
break;
case DOWNLOAD_DIR_KEY:
return getDownloadsFolder();
case VIDEOS_DIR_KEY:
return getVideosFolder();
case MUSIC_DIR_KEY:
return getMusicFolder();
case TEMPLATES_DIR_KEY:
break;
case PUBLICSHARE_DIR_KEY:
break;
}
return null;
}
protected File getDownloadsFolder(){
return get(DOWNLOAD_TRIES);
}
protected File getMusicFolder(){
return get(MUSIC_TRIES);
}
protected File getDocumentsFolder(){
return get(DOCUMENTS_TRIES);
}
protected File getVideosFolder()
{
return get(VIDEOS_TRIES);
}
protected File getDesktopFolder(){
return get(DESKTOP_TRIES);
}
protected File getImageFolder(){
return get(PICTURES_TRIES);
}
protected File getHomeFolder()
{
return new File(System.getProperty("user.home"));
}
private File get(String[] trys){
File file = null;
for (String s : trys)
{
file = new File(getHomeFolder(), s);
if (file.exists())
{
return file;
}
}
return file;
}
}
| mit |
prototypely/mageflow | app/code/community/Mageflow/Connect/Helper/Media.php | 9026 | <?php
/**
* Media.php
*
* PHP version 5
*
* @category MFX
* @package Mageflow_Connect
* @subpackage Helper
* @author Prototypely Ltd, Estonia <[email protected]>
* @copyright Copyright © 2017 Prototypely Ltd, Estonia (http://prototypely.com)
* @license MIT Copyright (c) 2017 Prototypely Ltd
* @link http://mageflow.com/
*/
/**
* Mageflow_Connect_Helper_Media
*
* MageFlow Media helper indexes WYSIWYG images and
* calculates diffs of image directory contents
*
* @category MFX
* @package Mageflow_Connect
* @subpackage Helper
* @author Prototypely Ltd, Estonia <[email protected]>
* @copyright Copyright © 2017 Prototypely Ltd, Estonia (http://prototypely.com)
* @license MIT Copyright (c) 2017 Prototypely Ltd
* @link http://mageflow.com/
*/
class Mageflow_Connect_Helper_Media extends Mage_Core_Helper_Abstract
{
/**
* cli
*
* @var bool
*/
private $cli = false;
/**
* verbose
*
* @var bool
*/
private $verbose = false;
const PROGRESS_MARKER = '=';
const ADD_MARKER = '+';
const DEL_MARKER = '-';
/**
* set cli
*
* @param boolean $cli
*/
public function setCli($cli)
{
$this->cli = $cli;
}
/**
* get cli
*
* @return boolean
*/
public function getCli()
{
return $this->cli;
}
/**
* set verbose
*
* @param boolean $verbose
*/
public function setVerbose($verbose)
{
$this->verbose = $verbose;
}
/**
* get verbose
*
* @return boolean
*/
public function getVerbose()
{
return $this->verbose;
}
/**
* out
*
* @param $out
*/
private function out($out)
{
if ($this->getCli() && $this->getVerbose()) {
echo $out;
}
}
/**
* Refreshes media index
*
* @param bool $forceSave
*
* @return int
*/
public function refreshIndex($forceSave = false)
{
$baseDirList = $this->getMediaDirectoryList();
/**
* @var Mageflow_Connect_Model_Resource_Media_Index_Collection
* $mediaIndexModelCollection
*/
$mediaIndexModelCollection = Mage::getModel(
'mageflow_connect/media_index'
)->getCollection();
$this->out(
sprintf(
"%s items in Media Index before reindexing%s",
$mediaIndexModelCollection->count(), PHP_EOL
)
);
foreach ($baseDirList as $baseDir) {
/**
* @var Mage_Cms_Model_Wysiwyg_Images_Storage $model
*/
$model = Mage::getModel('cms/wysiwyg_images_storage');
$fileCollection = $model->getFilesCollection($baseDir);
$this->out(
sprintf(
"Re-indexing %s ... Found %s items\n", $baseDir,
$fileCollection->count()
)
);
/**
* @var Mage_Cms_Model_Wysiwyg_Images_Storage $fileModel
*/
$i = 0;
foreach ($fileCollection as $fileModel) {
if ($i > 0 && $i % 100 == 0) {
$this->out(sprintf(" %s %s", $i, PHP_EOL));
}
if (!$mediaIndexModelCollection->fileIsCurrent($fileModel)) {
$mediaIndexModel = $this->createMediaIndexModel($fileModel);
$mediaIndexModel->save();
$mediaIndexModelCollection->addItem($mediaIndexModel);
$this->out(self::ADD_MARKER);
} else {
$this->out(self::PROGRESS_MARKER);
}
$i++;
}
$this->out(sprintf(" %s %s", $i, PHP_EOL));
$this->out(sprintf("Re-indexed %s%s", $baseDir, PHP_EOL));
}
if ($forceSave) {
$mediaIndexModelCollection->save();
}
/**
* @var Mageflow_Connect_Model_Media_Index $mediaIndexModel
*/
//2nd loop for removing files from index that don't exists on the disk
$this->out(sprintf("Searching for deleted files ... %s", PHP_EOL));
$i = 0;
foreach ($mediaIndexModelCollection as $mediaIndexModel) {
if ($i > 0 && $i % 100 == 0) {
$this->out(sprintf(" %s %s", $i, PHP_EOL));
}
if (!file_exists($mediaIndexModel->getFilename())) {
$mediaIndexModel->delete();
$this->out(self::DEL_MARKER);
} else {
$this->out(self::PROGRESS_MARKER);
}
$i++;
}
$this->out(PHP_EOL);
$mediaIndexModelCollection->clear();
$this->out(
sprintf(
"%s items in Media Index after reindexing%s",
$mediaIndexModelCollection->load()->count(), PHP_EOL
)
);
$mediaIndexModelCollection->clear();
return 0;
}
/**
* Returns list of directories to be searched for wysiwyg media files
*
* @return array
*/
public function getMediaDirectoryList()
{
$baseDir = Mage::getBaseDir('media') . DS . 'wysiwyg';
$baseDirList = array($baseDir);
/**
* @var Varien_Data_Collection_Filesystem $fileSystemModel
*/
$fileSystemModel = Mage::getModel('Varien_Data_Collection_Filesystem');
$fileSystemModel->addTargetDir($baseDir);
$fileSystemModel->setCollectDirs(true);
$fileSystemModel->setCollectFiles(false);
$dirList = $fileSystemModel->loadData();
foreach ($dirList as $dirObject) {
$baseDirList[] = $dirObject->getFilename();
}
return $baseDirList;
}
/**
* Initializes index. I.e it flushes index, then reads and saves current
* state of files under wysiwyg folder
*/
public function initializeIndex()
{
$baseDirList = $this->getMediaDirectoryList();
/**
* @var Mageflow_Connect_Model_Resource_Media_Index_Collection
* $mediaIndexModelCollection
*/
$mediaIndexModelCollection = Mage::getModel(
'mageflow_connect/media_index'
)->getCollection();
foreach ($mediaIndexModelCollection as $mediaIndexItem) {
$mediaIndexItem->delete();
}
$mediaIndexModelCollection->clear();
foreach ($baseDirList as $baseDir) {
/**
* @var Mage_Cms_Model_Wysiwyg_Images_Storage $model
*/
$model = Mage::getModel('cms/wysiwyg_images_storage');
$fileCollection = $model->getFilesCollection($baseDir);
$this->out(
sprintf(
"Re-indexing %s ... Found %s items\n", $baseDir,
$fileCollection->count()
)
);
$i = 0;
foreach ($fileCollection as $fileModel) {
if ($i > 0 && $i % 100 == 0) {
$this->out(sprintf(" %s %s", $i, PHP_EOL));
}
$mediaIndexModel = $this->createMediaIndexModel($fileModel);
$mediaIndexModel->save();
$this->out(self::ADD_MARKER);
$i++;
}
$this->out(PHP_EOL);
}
$this->out(
sprintf(
"%s items in Media Index after reindexing%s",
$mediaIndexModelCollection->load()->count(), PHP_EOL
)
);
}
/**
* Creates media index model from filemodel
*
* @param $fileModel
*
* @return Mageflow_Connect_Model_Media_Index
*/
private function createMediaIndexModel($fileModel)
{
/**
* @var Mageflow_Connect_Model_Media_Index $mediaIndexModel
*/
$mediaIndexModel = Mage::getModel('mageflow_connect/media_index');
$mediaIndexModel->setData($fileModel->getData());
$mediaIndexModel->setHash($fileModel->getId());
//FIX Magento file URL bug
$absolutePath = str_replace(
Mage::getBaseDir('base'), '', $mediaIndexModel->getFilename()
);
$mediaIndexModel->setPath($absolutePath);
$absoluteUrl
= Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB) . ltrim(
$absolutePath, '/'
);
$mediaIndexModel->setUrl($absoluteUrl);
$now = new DateTime('now');
$mediaIndexModel->setCreatedAt($now);
$mediaIndexModel->setUpdatedAt($now);
$imageInfo = @getimagesize($mediaIndexModel->getFilename());
if (is_array($imageInfo)) {
$mediaIndexModel->setType($imageInfo['mime']);
}
$size = @filesize($mediaIndexModel->getFilename());
$mediaIndexModel->setSize($size);
return $mediaIndexModel;
}
} | mit |
rs/SDAdvancedWebView | SDAWVPluginOrientation.js | 1463 | /**
* This class provides access to the device orientation.
* @constructor
*/
function Orientation()
{
/**
* The current orientation, or null if the orientation hasn't changed yet.
*/
this.currentOrientation = null;
this.init = function()
{
this._notifyCurrentOrientation(this.currentOrientation);
}
this.shouldAutorotateToContentOrientation = function(orientation)
{
return null;
}
this._notifyCurrentOrientation = function(orientation)
{
if (document != null && document.body != null)
{
// swap portrait/landscape class on the body element
portrait = orientation == 0 || orientation == 180;
document.body.className = document.body.className.replace(/(?:^| +)(?:portrait|landscape)(?: +|$)/g, " ")
+ " " + (portrait ? "portrait" : "landscape");
if (this.currentOrientation != null && this.currentOrientation != orientation)
{
var event = document.createEvent('Events');
event.initEvent('orientationchange', true);
document.dispatchEvent(event);
}
}
this.currentOrientation = orientation;
}
this.setContentOrientation = function(orientation)
{
navigator.comcenter.exec("Orientation.setContentOrientation", orientation);
}
}
SDAdvancedWebViewObjects['orientation'] = new Orientation();
| mit |
odinhaus/Suffuz | Altus.Suffūz.Observables.SignalR/Properties/AssemblyInfo.cs | 1442 | 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("Altus.Suffūz.Observables.SignalR")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Altus.Suffūz.Observables.SignalR")]
[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("c8aeae25-dab9-414e-8120-021176da793e")]
// 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 |
jbenjore/JPs-love-project | annotate-models/ruby/1.9.1/gems/fog-0.8.1/lib/fog/compute/requests/bluebox/destroy_block.rb | 525 | module Fog
module Bluebox
class Compute
class Real
# Destroy a block
#
# ==== Parameters
# * block_id<~Integer> - Id of block to destroy
#
# ==== Returns
# * response<~Excon::Response>:
# * body<~Hash>:
# TODO
def destroy_block(block_id)
request(
:expects => 200,
:method => 'DELETE',
:path => "api/blocks/#{block_id}.json"
)
end
end
end
end
end
| mit |
thipokKub/Clique-WebFront-Personnal | src/reducers/reducer_fetch_all_channels.js | 893 | import { FETCH_ALL_CHANNELS } from '../actions/types';
const initalState = {
fetching: false,
fetched: false,
error: null,
response: null,
}
export default ( state = initalState, action ) => {
switch (action.type) {
case `${FETCH_ALL_CHANNELS}_PENDING`:
return {
...state,
fetching: true,
error: null,
};
case `${FETCH_ALL_CHANNELS}_FULFILLED`:
return {
...state,
fetching: false,
fetched: true,
error: null,
response: action.payload.data
};
case `${FETCH_ALL_CHANNELS}_REJECTED`:
return {
...state,
fetching: false,
error: action.payload
};
default:
return state;
}
}
| mit |
xhad/codetodo | server/tests/controllers/tokens.controller.spec.js | 1909 | const chai = require('chai');
const expect = chai.expect;
const Token = require('../../controllers/tokens');
const UsersCtrl = require('../../controllers/usersCtrl');
const usersCtrl = new UsersCtrl();
let res = {};
res.status = function(error) {
return {
json: function() {}
}
};
let next = {};
let req = {};
describe('Tokens Controller Test:', function() {
describe('token.generate(payload)', function() {
it('Should take new date() and userId and make JWT', (done) => {
usersCtrl.signUp("[email protected]", "bbb").then((result) => {
// console.log(result.token);
expect(result.token).to.be.a.String;
done();
}).then(() => {
usersCtrl.deleteAccount("[email protected]", "bbb");
}).catch(done);
})
})
describe('token.decode(payload)', function() {
it('Should decrypt the token and return the date and userId', (done) => {
usersCtrl.signUp("[email protected]", "bbb").then((result) => {
let payload = {
headers: {
'x-access-token': result.token
},
userId: result.userId
}
return Token.decode(payload, res)
}).then((token) => {
usersCtrl.deleteAccount("[email protected]", "bbb");
expect(token).to.be.undefined;
done();
}).catch(done);
})
})
describe('token.decode(Bad Payload)', function() {
it('Should fail and return error', (done) => {
usersCtrl.signUp("[email protected]", "bbb").then((result) => {
let payload = {
headers: {
'x-access-token': 'asdfasdfasdfasdfasdfasdf'
},
userId: result.userId
}
let token = Token.decode(payload, res);
usersCtrl.deleteAccount("[email protected]", "bbb");
return token;
}).then((result) => {
expect(result).to.equal(undefined);
done();
}).catch(done);
})
})
})
| mit |
instacart/rails_workflow | app/controllers/rails_workflow/processes_controller.rb | 1989 | module RailsWorkflow
class ProcessesController < ::ActionController::Base
layout 'rails_workflow/application'
respond_to :html
before_action :set_process, only: [:show, :edit, :update, :destroy]
before_filter do
@processes_section_active = true
end
def index
@processes = ProcessDecorator.decorate_collection(undecorated_collection)
@errors = Error.
unresolved.order(id: :asc).
includes(:parent).limit(10)
@open_user_operations = OperationDecorator.
decorate_collection(
RailsWorkflow::Operation.incompleted.
unassigned.includes(:template).
limit(20)
)
@statistic = {
all: RailsWorkflow::Process.count,
statuses: RailsWorkflow::Process.count_by_statuses
}
end
def new
@process = Process.new(permitted_params).decorate
end
def create
@process = RailsWorkflow::ProcessManager.start_process(
params[:process][:template_id], {}
)
redirect_to process_url(@process)
end
def update
@process.update(permitted_params)
redirect_to processes_path
end
def destroy
@process.destroy
redirect_to processes_path
end
protected
def permitted_params
params.permit(
process: [
:status,
:async,
:title,
:template_id
],
filter: [:status]
)[:process]
end
def undecorated_collection
collection_scope = Process.default_scoped
if params[:filter]
status = Process.get_status_code(params[:filter]['status'])
collection_scope = collection_scope.by_status(status)
end
collection_scope.paginate(page: params[:page]).order(created_at: :desc)
end
def set_process
@process ||= ProcessDecorator.decorate(Process.find params[:id]).decorate
end
end
end
| mit |
WellCommerce/CompanyBundle | Tests/Entity/CompanyTest.php | 1121 | <?php
/**
* WellCommerce Open-Source E-Commerce Platform
*
* This file is part of the WellCommerce package.
*
* (c) Adam Piotrowski <[email protected]>
*
* For the full copyright and license information,
* please view the LICENSE file that was distributed with this source code.
*/
namespace WellCommerce\Bundle\CompanyBundle\Tests\Entity;
use WellCommerce\Bundle\CompanyBundle\Entity\Company;
use WellCommerce\Bundle\CompanyBundle\Entity\CompanyAddress;
use WellCommerce\Bundle\CoreBundle\Test\Entity\AbstractEntityTestCase;
/**
* Class CompanyTest
*
* @author Adam Piotrowski <[email protected]>
*/
class CompanyTest extends AbstractEntityTestCase
{
protected function createEntity()
{
return new Company();
}
public function providerTestAccessor()
{
$faker = $this->getFakerGenerator();
return [
['address', new CompanyAddress()],
['name', $faker->company],
['shortName', $faker->company],
['createdAt', $faker->dateTime],
['updatedAt', $faker->dateTime],
];
}
}
| mit |
limpoxe/Android-Plugin-Framework | Samples/PluginTest/src/main/java/com/example/plugintest/manymethods/d/c/A2.java | 8249 | package com.example.plugintest.manymethods.d.c;
public class A2 {
public static void a0(String msg) { System.out.println("msg=" + msg + 0); }
public static void a1(String msg) { System.out.println("msg=" + msg + 1); }
public static void a2(String msg) { System.out.println("msg=" + msg + 2); }
public static void a3(String msg) { System.out.println("msg=" + msg + 3); }
public static void a4(String msg) { System.out.println("msg=" + msg + 4); }
public static void a5(String msg) { System.out.println("msg=" + msg + 5); }
public static void a6(String msg) { System.out.println("msg=" + msg + 6); }
public static void a7(String msg) { System.out.println("msg=" + msg + 7); }
public static void a8(String msg) { System.out.println("msg=" + msg + 8); }
public static void a9(String msg) { System.out.println("msg=" + msg + 9); }
public static void a10(String msg) { System.out.println("msg=" + msg + 10); }
public static void a11(String msg) { System.out.println("msg=" + msg + 11); }
public static void a12(String msg) { System.out.println("msg=" + msg + 12); }
public static void a13(String msg) { System.out.println("msg=" + msg + 13); }
public static void a14(String msg) { System.out.println("msg=" + msg + 14); }
public static void a15(String msg) { System.out.println("msg=" + msg + 15); }
public static void a16(String msg) { System.out.println("msg=" + msg + 16); }
public static void a17(String msg) { System.out.println("msg=" + msg + 17); }
public static void a18(String msg) { System.out.println("msg=" + msg + 18); }
public static void a19(String msg) { System.out.println("msg=" + msg + 19); }
public static void a20(String msg) { System.out.println("msg=" + msg + 20); }
public static void a21(String msg) { System.out.println("msg=" + msg + 21); }
public static void a22(String msg) { System.out.println("msg=" + msg + 22); }
public static void a23(String msg) { System.out.println("msg=" + msg + 23); }
public static void a24(String msg) { System.out.println("msg=" + msg + 24); }
public static void a25(String msg) { System.out.println("msg=" + msg + 25); }
public static void a26(String msg) { System.out.println("msg=" + msg + 26); }
public static void a27(String msg) { System.out.println("msg=" + msg + 27); }
public static void a28(String msg) { System.out.println("msg=" + msg + 28); }
public static void a29(String msg) { System.out.println("msg=" + msg + 29); }
public static void a30(String msg) { System.out.println("msg=" + msg + 30); }
public static void a31(String msg) { System.out.println("msg=" + msg + 31); }
public static void a32(String msg) { System.out.println("msg=" + msg + 32); }
public static void a33(String msg) { System.out.println("msg=" + msg + 33); }
public static void a34(String msg) { System.out.println("msg=" + msg + 34); }
public static void a35(String msg) { System.out.println("msg=" + msg + 35); }
public static void a36(String msg) { System.out.println("msg=" + msg + 36); }
public static void a37(String msg) { System.out.println("msg=" + msg + 37); }
public static void a38(String msg) { System.out.println("msg=" + msg + 38); }
public static void a39(String msg) { System.out.println("msg=" + msg + 39); }
public static void a40(String msg) { System.out.println("msg=" + msg + 40); }
public static void a41(String msg) { System.out.println("msg=" + msg + 41); }
public static void a42(String msg) { System.out.println("msg=" + msg + 42); }
public static void a43(String msg) { System.out.println("msg=" + msg + 43); }
public static void a44(String msg) { System.out.println("msg=" + msg + 44); }
public static void a45(String msg) { System.out.println("msg=" + msg + 45); }
public static void a46(String msg) { System.out.println("msg=" + msg + 46); }
public static void a47(String msg) { System.out.println("msg=" + msg + 47); }
public static void a48(String msg) { System.out.println("msg=" + msg + 48); }
public static void a49(String msg) { System.out.println("msg=" + msg + 49); }
public static void a50(String msg) { System.out.println("msg=" + msg + 50); }
public static void a51(String msg) { System.out.println("msg=" + msg + 51); }
public static void a52(String msg) { System.out.println("msg=" + msg + 52); }
public static void a53(String msg) { System.out.println("msg=" + msg + 53); }
public static void a54(String msg) { System.out.println("msg=" + msg + 54); }
public static void a55(String msg) { System.out.println("msg=" + msg + 55); }
public static void a56(String msg) { System.out.println("msg=" + msg + 56); }
public static void a57(String msg) { System.out.println("msg=" + msg + 57); }
public static void a58(String msg) { System.out.println("msg=" + msg + 58); }
public static void a59(String msg) { System.out.println("msg=" + msg + 59); }
public static void a60(String msg) { System.out.println("msg=" + msg + 60); }
public static void a61(String msg) { System.out.println("msg=" + msg + 61); }
public static void a62(String msg) { System.out.println("msg=" + msg + 62); }
public static void a63(String msg) { System.out.println("msg=" + msg + 63); }
public static void a64(String msg) { System.out.println("msg=" + msg + 64); }
public static void a65(String msg) { System.out.println("msg=" + msg + 65); }
public static void a66(String msg) { System.out.println("msg=" + msg + 66); }
public static void a67(String msg) { System.out.println("msg=" + msg + 67); }
public static void a68(String msg) { System.out.println("msg=" + msg + 68); }
public static void a69(String msg) { System.out.println("msg=" + msg + 69); }
public static void a70(String msg) { System.out.println("msg=" + msg + 70); }
public static void a71(String msg) { System.out.println("msg=" + msg + 71); }
public static void a72(String msg) { System.out.println("msg=" + msg + 72); }
public static void a73(String msg) { System.out.println("msg=" + msg + 73); }
public static void a74(String msg) { System.out.println("msg=" + msg + 74); }
public static void a75(String msg) { System.out.println("msg=" + msg + 75); }
public static void a76(String msg) { System.out.println("msg=" + msg + 76); }
public static void a77(String msg) { System.out.println("msg=" + msg + 77); }
public static void a78(String msg) { System.out.println("msg=" + msg + 78); }
public static void a79(String msg) { System.out.println("msg=" + msg + 79); }
public static void a80(String msg) { System.out.println("msg=" + msg + 80); }
public static void a81(String msg) { System.out.println("msg=" + msg + 81); }
public static void a82(String msg) { System.out.println("msg=" + msg + 82); }
public static void a83(String msg) { System.out.println("msg=" + msg + 83); }
public static void a84(String msg) { System.out.println("msg=" + msg + 84); }
public static void a85(String msg) { System.out.println("msg=" + msg + 85); }
public static void a86(String msg) { System.out.println("msg=" + msg + 86); }
public static void a87(String msg) { System.out.println("msg=" + msg + 87); }
public static void a88(String msg) { System.out.println("msg=" + msg + 88); }
public static void a89(String msg) { System.out.println("msg=" + msg + 89); }
public static void a90(String msg) { System.out.println("msg=" + msg + 90); }
public static void a91(String msg) { System.out.println("msg=" + msg + 91); }
public static void a92(String msg) { System.out.println("msg=" + msg + 92); }
public static void a93(String msg) { System.out.println("msg=" + msg + 93); }
public static void a94(String msg) { System.out.println("msg=" + msg + 94); }
public static void a95(String msg) { System.out.println("msg=" + msg + 95); }
public static void a96(String msg) { System.out.println("msg=" + msg + 96); }
public static void a97(String msg) { System.out.println("msg=" + msg + 97); }
public static void a98(String msg) { System.out.println("msg=" + msg + 98); }
public static void a99(String msg) { System.out.println("msg=" + msg + 99); }
}
| mit |
autorealm/faddle | src/Faddle/Storage/Cache/MySQLStore.php | 3321 | <?php namespace Faddle\Storage\Cache;
/**
* MySQL adapter. Basically just a wrapper over \PDO, but in an exchangeable
* (KeyValueStore) interface.
*
* @author Matthias Mullie <[email protected]>
* @copyright Copyright (c) 2014, Matthias Mullie. All rights reserved.
* @license LICENSE MIT
*/
class MySQLStore extends SQLStore
{
/**
* {@inheritdoc}
*/
public function set($key, $value, $expire = 0)
{
$value = $this->serialize($value);
$expire = $this->expire($expire);
$statement = $this->client->prepare(
"REPLACE INTO $this->table (k, v, e)
VALUES (:key, :value, :expire)"
);
$statement->execute(array(
':key' => $key,
':value' => $value,
':expire' => $expire,
));
// 1 = insert; 2 = update
return $statement->rowCount() === 1 || $statement->rowCount() === 2;
}
/**
* {@inheritdoc}
*/
public function setMulti(array $items, $expire = 0)
{
$i = 1;
$query = array();
$params = array();
$expire = $this->expire($expire);
foreach ($items as $key => $value) {
$value = $this->serialize($value);
$query[] = "(:key$i, :value$i, :expire$i)";
$params += array(
":key$i" => $key,
":value$i" => $value,
":expire$i" => $expire,
);
++$i;
}
$statement = $this->client->prepare(
"REPLACE INTO $this->table (k, v, e)
VALUES ".implode(',', $query)
);
$statement->execute($params);
/*
* As far as I can tell, there are no conditions under which this can go
* wrong (if item exists or not, REPLACE INTO will work either way),
* except for connection problems, in which case all or none will be
* stored.
* Can't compare with count($items) because rowCount could be 1 or 2,
* depending on if REPLACE was an INSERT or UPDATE.
*/
$success = $statement->rowCount() > 0;
return array_fill_keys(array_keys($items), $success);
}
/**
* {@inheritdoc}
*/
public function add($key, $value, $expire = 0)
{
$value = $this->serialize($value);
$expire = $this->expire($expire);
$this->clearExpired();
// MySQL-specific way to ignore insert-on-duplicate errors
$statement = $this->client->prepare(
"INSERT IGNORE INTO $this->table (k, v, e)
VALUES (:key, :value, :expire)"
);
$statement->execute(array(
':key' => $key,
':value' => $value,
':expire' => $expire,
));
return $statement->rowCount() === 1;
}
/**
* {@inheritdoc}
*/
public function flush()
{
return $this->client->exec("TRUNCATE TABLE $this->table") !== false;
}
/**
* {@inheritdoc}
*/
protected function init()
{
$this->client->exec(
"CREATE TABLE IF NOT EXISTS $this->table (
k VARBINARY(255) NOT NULL PRIMARY KEY,
v BLOB,
e TIMESTAMP NULL DEFAULT NULL,
KEY e (e)
)"
);
}
}
| mit |
nathanhood/mmdb | app/components/Card/index.js | 268 | import styled from 'styled-components';
import theme from 'theme';
const Card = styled.div`
background: ${theme.white};
box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.06);
border-radius: 2px;
margin-bottom: 25px;
padding: 15px;
`;
export default Card;
| mit |
aleripe/QueryBuilder | QueryBuilder/Select/From/FromClause.cs | 523 | using ReturnTrue.QueryBuilder.Elements;
namespace ReturnTrue.QueryBuilder.Select.From
{
public abstract class FromClause : QueryClause
{
public string Alias { get; private set; }
protected FromClause()
{
}
protected FromClause(string alias)
{
Alias = alias;
}
public static FromClauses operator &(FromClause leftClause, FromClause rightClause)
{
return new FromClauses(leftClause, rightClause);
}
}
} | mit |
aspnetboilerplate/sample-blog-module | app/MyAbpZeroProject.Core/MultiTenancy/Tenant.cs | 156 | using Abp.MultiTenancy;
using MyAbpZeroProject.Users;
namespace MyAbpZeroProject.MultiTenancy
{
public class Tenant : AbpTenant<User>
{
}
} | mit |
vithati/vsts-agent | src/Agent.Worker/Release/ZipStreamDownloader.cs | 4342 | using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Services.Agent.Util;
namespace Microsoft.VisualStudio.Services.Agent.Worker.Release
{
[ServiceLocator(Default = typeof(ZipStreamDownloader))]
public interface IZipStreamDownloader : IAgentService
{
Task<int> DownloadFromStream(
Stream zipStream,
string folderWithinStream,
string relativePathWithinStream,
string localFolderPath);
}
// TODO: Add tests for this
public class ZipStreamDownloader : AgentService, IZipStreamDownloader
{
private const char ForwardSlash = '/';
private const char Backslash = '\\';
public Task<int> DownloadFromStream(Stream zipStream, string folderWithinStream, string relativePathWithinStream, string localFolderPath)
{
Trace.Entering();
ArgUtil.NotNullOrEmpty(localFolderPath, nameof(localFolderPath));
ArgUtil.NotNull(folderWithinStream, nameof(folderWithinStream));
return DownloadStreams(zipStream, localFolderPath, folderWithinStream, relativePathWithinStream);
}
private async Task<int> DownloadStreams(Stream zipStream, string localFolderPath, string folderWithinStream, string relativePathWithinStream)
{
Trace.Entering();
int streamsDownloaded = 0;
var fileSystemManager = HostContext.CreateService<IReleaseFileSystemManager>();
foreach (ZipEntryStream stream in GetZipEntryStreams(zipStream))
{
try
{
// Remove leading '/'s if any
var path = stream.FullName.TrimStart(ForwardSlash);
Trace.Verbose($"Downloading {path}");
if (!string.IsNullOrWhiteSpace(folderWithinStream))
{
var normalizedFolderWithInStream = folderWithinStream.TrimStart(ForwardSlash).TrimEnd(ForwardSlash) + ForwardSlash;
// If this zip entry does not start with the expected folderName, skip it.
if (!path.StartsWith(normalizedFolderWithInStream, StringComparison.OrdinalIgnoreCase))
{
continue;
}
path = path.Substring(normalizedFolderWithInStream.Length);
}
if (!string.IsNullOrWhiteSpace(relativePathWithinStream)
&& !relativePathWithinStream.Equals(ForwardSlash.ToString())
&& !relativePathWithinStream.Equals(Backslash.ToString()))
{
var normalizedRelativePath =
relativePathWithinStream.Replace(Backslash, ForwardSlash).TrimStart(ForwardSlash).TrimEnd(ForwardSlash)
+ ForwardSlash;
// Remove Blob Prefix path like "FabrikamFiber.DAL/bin/debug/" from the beginning of artifact full path
if (!path.StartsWith(normalizedRelativePath, StringComparison.OrdinalIgnoreCase))
{
continue;
}
path = path.Substring(normalizedRelativePath.Length);
}
await fileSystemManager.WriteStreamToFile(stream.ZipStream, Path.Combine(localFolderPath, path));
streamsDownloaded++;
}
finally
{
stream.ZipStream.Dispose();
}
}
return streamsDownloaded;
}
private static IEnumerable<ZipEntryStream> GetZipEntryStreams(Stream zipStream)
{
return
new ZipArchive(zipStream).Entries
.Where(entry => !entry.FullName.EndsWith("/", StringComparison.OrdinalIgnoreCase))
.Select(entry => new ZipEntryStream { FullName = entry.FullName, ZipStream = entry.Open() });
}
}
internal class ZipEntryStream
{
public string FullName { get; set; }
public Stream ZipStream { get; set; }
}
} | mit |
blakcat7/aegis-infinite | js/scrolling-nav.js | 10177 | //jQuery to collapse the navbar on scroll
$(window).scroll(function () {
if ($(".navbar").offset().top > 60) {
$(".navbar-fixed-top").addClass("top-nav-collapse");
} else {
$(".navbar-fixed-top").removeClass("top-nav-collapse");
}
});
//jQuery for page scrolling feature - requires jQuery Easing plugin
$(function () {
$(document).on('click', 'a.page-scroll', function (event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top
}, 1000, 'easeInOutExpo');
event.preventDefault();
});
});
!function (a) {
function b(b, d) {
function e() {
if (w) {
$canvas = a('<canvas class="pg-canvas"></canvas>'), v.prepend($canvas), p = $canvas[0], q = p.getContext("2d"), f();
for (var b = Math.round(p.width * p.height / d.density), c = 0; b > c; c++) {
var e = new l;
e.setStackPos(c), x.push(e)
}
a(window).on("resize", function () {
h()
}), a(document).on("mousemove", function (a) {
y = a.pageX, z = a.pageY
}), B && !A && window.addEventListener("deviceorientation", function () {
D = Math.min(Math.max(-event.beta, -30), 30), C = Math.min(Math.max(-event.gamma, -30), 30)
}, !0), g(), o("onInit")
}
}
function f() {
p.width = v.width(), p.height = v.height(), q.fillStyle = d.dotColor, q.strokeStyle = d.lineColor, q.lineWidth = d.lineWidth
}
function g() {
if (w) {
s = a(window).width(), t = a(window).height(), q.clearRect(0, 0, p.width, p.height);
for (var b = 0; b < x.length; b++)
x[b].updatePosition();
for (var b = 0; b < x.length; b++)
x[b].draw();
E || (r = requestAnimationFrame(g))
}
}
function h() {
for (f(), i = x.length - 1; i >= 0; i--)
(x[i].position.x > v.width() || x[i].position.y > v.height()) && x.splice(i, 1);
var a = Math.round(p.width * p.height / d.density);
if (a > x.length)
for (; a > x.length; ) {
var b = new l;
x.push(b)
}
else
a < x.length && x.splice(a);
for (i = x.length - 1; i >= 0; i--)
x[i].setStackPos(i)
}
function j() {
E = !0
}
function k() {
E = !1, g()
}
function l() {
switch (this.stackPos, this.active = !0, this.layer = Math.ceil(3 * Math.random()), this.parallaxOffsetX = 0, this.parallaxOffsetY = 0, this.position = {
x: Math.ceil(Math.random() * p.width), y: Math.ceil(Math.random() * p.height)}, this.speed = {}, d.directionX){case"left":
this.speed.x = +(-d.maxSpeedX + Math.random() * d.maxSpeedX - d.minSpeedX).toFixed(2);
break;
case"right":
this.speed.x = +(Math.random() * d.maxSpeedX + d.minSpeedX).toFixed(2);
break;
default:
this.speed.x = +(-d.maxSpeedX / 2 + Math.random() * d.maxSpeedX).toFixed(2), this.speed.x += this.speed.x > 0 ? d.minSpeedX : -d.minSpeedX
}
switch (d.directionY) {
case"up":
this.speed.y = +(-d.maxSpeedY + Math.random() * d.maxSpeedY - d.minSpeedY).toFixed(2);
break;
case"down":
this.speed.y = +(Math.random() * d.maxSpeedY + d.minSpeedY).toFixed(2);
break;
default:
this.speed.y = +(-d.maxSpeedY / 2 + Math.random() * d.maxSpeedY).toFixed(2), this.speed.x += this.speed.y > 0 ? d.minSpeedY : -d.minSpeedY
}
}
function m(a, b) {
return b ? void(d[a] = b) : d[a]
}
function n() {
v.find(".pg-canvas").remove(), o("onDestroy"), v.removeData("plugin_" + c)
}
function o(a) {
void 0 !== d[a] && d[a].call(u)
}
var p, q, r, s, t, u = b, v = a(b), w = !!document.createElement("canvas").getContext, x = [], y = 0, z = 0, A = !navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry|BB10|mobi|tablet|opera mini|nexus 7)/i), B = !!window.DeviceOrientationEvent, C = 0, D = 0, E = !1;
return d = a.extend({}, a.fn[c].defaults, d), l.prototype.draw = function () {
q.beginPath(), q.arc(this.position.x + this.parallaxOffsetX, this.position.y + this.parallaxOffsetY, d.particleRadius / 2, 0, 2 * Math.PI, !0), q.closePath(), q.fill(), q.beginPath();
for (var a = x.length - 1; a > this.stackPos; a--) {
var b = x[a], c = this.position.x - b.position.x, e = this.position.y - b.position.y, f = Math.sqrt(c * c + e * e).toFixed(2);
f < d.proximity && (q.moveTo(this.position.x + this.parallaxOffsetX, this.position.y + this.parallaxOffsetY), d.curvedLines ? q.quadraticCurveTo(Math.max(b.position.x, b.position.x), Math.min(b.position.y, b.position.y), b.position.x + b.parallaxOffsetX, b.position.y + b.parallaxOffsetY) : q.lineTo(b.position.x + b.parallaxOffsetX, b.position.y + b.parallaxOffsetY))
}
q.stroke(), q.closePath()
}, l.prototype.updatePosition = function () {
if (d.parallax) {
if (B && !A) {
var a = (s - 0) / 60;
pointerX = (C - -30) * a + 0;
var b = (t - 0) / 60;
pointerY = (D - -30) * b + 0
} else
pointerX = y, pointerY = z;
this.parallaxTargX = (pointerX - s / 2) / (d.parallaxMultiplier * this.layer), this.parallaxOffsetX += (this.parallaxTargX - this.parallaxOffsetX) / 10, this.parallaxTargY = (pointerY - t / 2) / (d.parallaxMultiplier * this.layer), this.parallaxOffsetY += (this.parallaxTargY - this.parallaxOffsetY) / 10
}
switch (d.directionX) {
case"left":
this.position.x + this.speed.x + this.parallaxOffsetX < 0 && (this.position.x = v.width() - this.parallaxOffsetX);
break;
case"right":
this.position.x + this.speed.x + this.parallaxOffsetX > v.width() && (this.position.x = 0 - this.parallaxOffsetX);
break;
default:
(this.position.x + this.speed.x + this.parallaxOffsetX > v.width() || this.position.x + this.speed.x + this.parallaxOffsetX < 0) && (this.speed.x = -this.speed.x)
}
switch (d.directionY) {
case"up":
this.position.y + this.speed.y + this.parallaxOffsetY < 0 && (this.position.y = v.height() - this.parallaxOffsetY);
break;
case"down":
this.position.y + this.speed.y + this.parallaxOffsetY > v.height() && (this.position.y = 0 - this.parallaxOffsetY);
break;
default:
(this.position.y + this.speed.y + this.parallaxOffsetY > v.height() || this.position.y + this.speed.y + this.parallaxOffsetY < 0) && (this.speed.y = -this.speed.y)
}
this.position.x += this.speed.x, this.position.y += this.speed.y
}, l.prototype.setStackPos = function (a) {
this.stackPos = a
}, e(), {option: m, destroy: n, start: k, pause: j}
}
var c = "particleground";
a.fn[c] = function (d) {
if ("string" == typeof arguments[0]) {
var e, f = arguments[0], g = Array.prototype.slice.call(arguments, 1);
return this.each(function () {
a.data(this, "plugin_" + c) && "function" == typeof a.data(this, "plugin_" + c)[f] && (e = a.data(this, "plugin_" + c)[f].apply(this, g))
}), void 0 !== e ? e : this
}
return"object" != typeof d && d ? void 0 : this.each(function () {
a.data(this, "plugin_" + c) || a.data(this, "plugin_" + c, new b(this, d))
})
}, a.fn[c].defaults = {minSpeedX: .1, maxSpeedX: .7, minSpeedY: .1, maxSpeedY: .7, directionX: "center", directionY: "center", density: 1e4, dotColor: "#666666", lineColor: "#666666", particleRadius: 7, lineWidth: 1, curvedLines: !1, proximity: 100, parallax: !0, parallaxMultiplier: 5, onInit: function () {}, onDestroy: function () {}}
}(jQuery), /**
* requestAnimationFrame polyfill by Erik Möller. fixes from Paul Irish and Tino Zijdel
* @see: http://paulirish.com/2011/requestanimationframe-for-smart-animating/
* @see: http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
* @license: MIT license
*/
function () {
for (var a = 0, b = ["ms", "moz", "webkit", "o"], c = 0; c < b.length && !window.requestAnimationFrame; ++c)
window.requestAnimationFrame = window[b[c] + "RequestAnimationFrame"], window.cancelAnimationFrame = window[b[c] + "CancelAnimationFrame"] || window[b[c] + "CancelRequestAnimationFrame"];
window.requestAnimationFrame || (window.requestAnimationFrame = function (b) {
var c = (new Date).getTime(), d = Math.max(0, 16 - (c - a)), e = window.setTimeout(function () {
b(c + d)
}, d);
return a = c + d, e
}), window.cancelAnimationFrame || (window.cancelAnimationFrame = function (a) {
clearTimeout(a)
})
}();
/*MAIN JS*/
/**
* Particleground demo
* @author Jonathan Nicol - @mrjnicol
*/
$(document).ready(function () {
$('#particles').particleground({
dotColor: '#fff',
lineColor: '#fff'
});
$('.intro').css({
'margin-top': -($('.intro').height() / 2)
});
}); | mit |
Azure/azure-sdk-for-java | sdk/databoxedge/azure-resourcemanager-databoxedge/src/main/java/com/azure/resourcemanager/databoxedge/models/NodeStatus.java | 1489 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.databoxedge.models;
import com.azure.core.util.ExpandableStringEnum;
import com.fasterxml.jackson.annotation.JsonCreator;
import java.util.Collection;
/** Defines values for NodeStatus. */
public final class NodeStatus extends ExpandableStringEnum<NodeStatus> {
/** Static value Unknown for NodeStatus. */
public static final NodeStatus UNKNOWN = fromString("Unknown");
/** Static value Up for NodeStatus. */
public static final NodeStatus UP = fromString("Up");
/** Static value Down for NodeStatus. */
public static final NodeStatus DOWN = fromString("Down");
/** Static value Rebooting for NodeStatus. */
public static final NodeStatus REBOOTING = fromString("Rebooting");
/** Static value ShuttingDown for NodeStatus. */
public static final NodeStatus SHUTTING_DOWN = fromString("ShuttingDown");
/**
* Creates or finds a NodeStatus from its string representation.
*
* @param name a name to look for.
* @return the corresponding NodeStatus.
*/
@JsonCreator
public static NodeStatus fromString(String name) {
return fromString(name, NodeStatus.class);
}
/** @return known NodeStatus values. */
public static Collection<NodeStatus> values() {
return values(NodeStatus.class);
}
}
| mit |
myo/Experimental | MySharpSupport/Evade/Config.cs | 828 | namespace MySharpSupport.Evade
{
internal static class Config
{
public const int CrossingTimeOffset = 250;
public const int DiagonalEvadePointsCount = 7;
public const int DiagonalEvadePointsStep = 20;
public const int EvadePointChangeInterval = 300;
public const int EvadingFirstTimeOffset = 250;
public const int EvadingRouteChangeTimeOffset = 250;
public const int EvadingSecondTimeOffset = 0;
public const int ExtraEvadeDistance = 15;
public const int GridSize = 10;
public const bool PrintSpellData = false;
public const int SkillShotsExtraRadius = 9;
public const int SkillShotsExtraRange = 20;
public const bool TestOnAllies = false;
public static int LastEvadePointChangeT = 0;
}
} | mit |
doctrine/mongodb-odm | tests/Doctrine/ODM/MongoDB/Tests/Functional/HasLifecycleCallbacksTest.php | 6106 | <?php
declare(strict_types=1);
namespace Doctrine\ODM\MongoDB\Tests\Functional\Ticket;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use Doctrine\ODM\MongoDB\Tests\BaseTest;
class HasLifecycleCallbacksTest extends BaseTest
{
public function testHasLifecycleCallbacksSubExtendsSuper(): void
{
$document = new HasLifecycleCallbacksSubExtendsSuper();
$this->dm->persist($document);
$this->dm->flush();
// Neither class is annotated. No callback is invoked.
$this->assertCount(0, $document->invoked);
}
public function testHasLifecycleCallbacksSubExtendsSuperAnnotated(): void
{
$document = new HasLifecycleCallbacksSubExtendsSuperAnnotated();
$this->dm->persist($document);
$this->dm->flush();
/* The sub-class is not annotated, so the callback in the annotated
* super-class is invokved.
*/
$this->assertCount(1, $document->invoked);
$this->assertEquals('super', $document->invoked[0]);
}
public function testHasLifecycleCallbacksSubAnnotatedExtendsSuper(): void
{
$document = new HasLifecycleCallbacksSubAnnotatedExtendsSuper();
$this->dm->persist($document);
$this->dm->flush();
/* The sub-class is annotated, but the method is declared in the super-
* class, which is not annotated. No callback is invoked.
*/
$this->assertCount(0, $document->invoked);
}
public function testHasLifecycleCallbacksSubAnnotatedExtendsSuperAnnotated(): void
{
$document = new HasLifecycleCallbacksSubAnnotatedExtendsSuperAnnotated();
$this->dm->persist($document);
$this->dm->flush();
/* The sub-class is annotated, but it doesn't override the method, so
* the callback in the annotated super-class is invoked.
*/
$this->assertCount(1, $document->invoked);
$this->assertEquals('super', $document->invoked[0]);
}
public function testHasLifecycleCallbacksSubOverrideExtendsSuper(): void
{
$document = new HasLifecycleCallbacksSubOverrideExtendsSuper();
$this->dm->persist($document);
$this->dm->flush();
// Neither class is annotated. No callback is invoked.
$this->assertCount(0, $document->invoked);
}
public function testHasLifecycleCallbacksSubOverrideExtendsSuperAnnotated(): void
{
$document = new HasLifecycleCallbacksSubOverrideExtendsSuperAnnotated();
$this->dm->persist($document);
$this->dm->flush();
/* The sub-class is invoked because it overrides the method in the
* annotated super-class.
*/
$this->assertCount(1, $document->invoked);
$this->assertEquals('sub', $document->invoked[0]);
}
public function testHasLifecycleCallbacksSubOverrideAnnotatedExtendsSuper(): void
{
$document = new HasLifecycleCallbacksSubOverrideAnnotatedExtendsSuper();
$this->dm->persist($document);
$this->dm->flush();
/* The sub-class is invoked because it overrides the method and is
* annotated.
*/
$this->assertCount(1, $document->invoked);
$this->assertEquals('sub', $document->invoked[0]);
}
public function testHasLifecycleCallbacksSubOverrideAnnotatedExtendsSuperAnnotated(): void
{
$document = new HasLifecycleCallbacksSubOverrideAnnotatedExtendsSuperAnnotated();
$this->dm->persist($document);
$this->dm->flush();
/* Since both classes are annotated and declare the method, the callback
* is registered twice but the sub-class should be invoked only once.
*/
$this->assertCount(1, $document->invoked);
$this->assertEquals('sub', $document->invoked[0]);
}
}
/** @ODM\MappedSuperclass */
abstract class HasLifecycleCallbacksSuper
{
/**
* @ODM\Id
*
* @var string|null
*/
public $id;
/** @var string[] */
public $invoked = [];
/**
* @ODM\PrePersist
*/
public function prePersist(): void
{
$this->invoked[] = 'super';
}
}
/** @ODM\MappedSuperclass @ODM\HasLifecycleCallbacks */
abstract class HasLifecycleCallbacksSuperAnnotated
{
/**
* @ODM\Id
*
* @var string|null
*/
public $id;
/** @var string[] */
public $invoked = [];
/**
* @ODM\PrePersist
*/
public function prePersist(): void
{
$this->invoked[] = 'super';
}
}
/** @ODM\Document */
class HasLifecycleCallbacksSubExtendsSuper extends HasLifecycleCallbacksSuper
{
}
/** @ODM\Document */
class HasLifecycleCallbacksSubExtendsSuperAnnotated extends HasLifecycleCallbacksSuperAnnotated
{
}
/** @ODM\Document @ODM\HasLifecycleCallbacks */
class HasLifecycleCallbacksSubAnnotatedExtendsSuper extends HasLifecycleCallbacksSuper
{
}
/** @ODM\Document @ODM\HasLifecycleCallbacks */
class HasLifecycleCallbacksSubAnnotatedExtendsSuperAnnotated extends HasLifecycleCallbacksSuperAnnotated
{
}
/** @ODM\Document */
class HasLifecycleCallbacksSubOverrideExtendsSuper extends HasLifecycleCallbacksSuper
{
/**
* @ODM\PrePersist
*/
public function prePersist(): void
{
$this->invoked[] = 'sub';
}
}
/** @ODM\Document */
class HasLifecycleCallbacksSubOverrideExtendsSuperAnnotated extends HasLifecycleCallbacksSuperAnnotated
{
/**
* @ODM\PrePersist
*/
public function prePersist(): void
{
$this->invoked[] = 'sub';
}
}
/** @ODM\Document @ODM\HasLifecycleCallbacks */
class HasLifecycleCallbacksSubOverrideAnnotatedExtendsSuper extends HasLifecycleCallbacksSuper
{
/**
* @ODM\PrePersist
*/
public function prePersist(): void
{
$this->invoked[] = 'sub';
}
}
/** @ODM\Document @ODM\HasLifecycleCallbacks */
class HasLifecycleCallbacksSubOverrideAnnotatedExtendsSuperAnnotated extends HasLifecycleCallbacksSuperAnnotated
{
/**
* @ODM\PrePersist
*/
public function prePersist(): void
{
$this->invoked[] = 'sub';
}
}
| mit |
PeqNP/GameKit | src/ad/NetworkModule.lua | 763 | --
-- @copyright 2015 Upstart Illustration LLC. All rights resevered.
--
local NetworkModule = Class()
NetworkModule.abstract(Protocol(
-- Return the ID of the network.
Method("getAdNetwork")
-- Returns dictionary containing configuration.
, Method("getConfig")
-- Returns the ad network ID used by this module.
, Method("getName")
))
function NetworkModule.new(self)
local ads
local function configureAds()
for _, ad in ipairs(ads) do
ad.setAdNetwork(self.getAdNetwork())
end
end
function self.init(_ads)
ads = _ads
configureAds()
end
function self.getConfig()
return {}
end
function self.getAds()
return ads
end
end
return NetworkModule
| mit |
philou/concurrency-kata | src/main/java/net/bourgau/philippe/concurrency/kata/actors/threads/real/ActorsRealThreads.java | 1606 | package net.bourgau.philippe.concurrency.kata.actors.threads.real;
import net.bourgau.philippe.concurrency.kata.common.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ActorsRealThreads extends ThreadPoolImplementation {
private List<ExecutorService> clientThreadPools;
@Override
public ChatRoom startNewChatRoom() {
clientThreadPools = new ArrayList<>();
return super.startNewChatRoom();
}
@Override
protected ExecutorService newThreadPool() {
return Executors.newFixedThreadPool(1);
}
@Override
protected ChatRoom newChatRoom() {
return new ConcurrentChatRoom(
new InProcessChatRoom(new HashMap<Output, String>()),
threadPool());
}
@Override
public Client newClient(String name, ChatRoom chatRoom, Output out) {
ExecutorService threadPool = newThreadPool();
clientThreadPools.add(threadPool);
return new ConcurrentClient(new InProcessClient(name, chatRoom, out), threadPool);
}
@Override
public void awaitOrShutdown(int count, TimeUnit timeUnit) throws InterruptedException {
super.awaitOrShutdown(count, timeUnit);
for (ExecutorService clientThreadPool : clientThreadPools) {
awaitOrShutdown(clientThreadPool, 100, TimeUnit.MILLISECONDS);
}
}
@Override
public String toString() {
return "Actors with real threads";
}
}
| mit |
bbojkov/MushroomMusicLibrary | MusicLibrary.Web/Account/ResetPasswordConfirmation.aspx.cs | 133 | using System.Web.UI;
namespace MusicLibrary.Web.Account
{
public partial class ResetPasswordConfirmation : Page
{
}
} | mit |
MalloyPower/parsing-python | front-end/testsuite-python-lib/Python-2.2/Lib/distutils/version.py | 11519 | #
# distutils/version.py
#
# Implements multiple version numbering conventions for the
# Python Module Distribution Utilities.
#
# written by Greg Ward, 1998/12/17
#
# $Id: version.py,v 1.6 2001/12/06 20:51:35 fdrake Exp $
#
"""Provides classes to represent module version numbers (one class for
each style of version numbering). There are currently two such classes
implemented: StrictVersion and LooseVersion.
Every version number class implements the following interface:
* the 'parse' method takes a string and parses it to some internal
representation; if the string is an invalid version number,
'parse' raises a ValueError exception
* the class constructor takes an optional string argument which,
if supplied, is passed to 'parse'
* __str__ reconstructs the string that was passed to 'parse' (or
an equivalent string -- ie. one that will generate an equivalent
version number instance)
* __repr__ generates Python code to recreate the version number instance
* __cmp__ compares the current instance with either another instance
of the same class or a string (which will be parsed to an instance
of the same class, thus must follow the same rules)
"""
import string, re
from types import StringType
class Version:
"""Abstract base class for version numbering classes. Just provides
constructor (__init__) and reproducer (__repr__), because those
seem to be the same for all version numbering classes.
"""
def __init__ (self, vstring=None):
if vstring:
self.parse(vstring)
def __repr__ (self):
return "%s ('%s')" % (self.__class__.__name__, str(self))
# Interface for version-number classes -- must be implemented
# by the following classes (the concrete ones -- Version should
# be treated as an abstract class).
# __init__ (string) - create and take same action as 'parse'
# (string parameter is optional)
# parse (string) - convert a string representation to whatever
# internal representation is appropriate for
# this style of version numbering
# __str__ (self) - convert back to a string; should be very similar
# (if not identical to) the string supplied to parse
# __repr__ (self) - generate Python code to recreate
# the instance
# __cmp__ (self, other) - compare two version numbers ('other' may
# be an unparsed version string, or another
# instance of your version class)
class StrictVersion (Version):
"""Version numbering for anal retentives and software idealists.
Implements the standard interface for version number classes as
described above. A version number consists of two or three
dot-separated numeric components, with an optional "pre-release" tag
on the end. The pre-release tag consists of the letter 'a' or 'b'
followed by a number. If the numeric components of two version
numbers are equal, then one with a pre-release tag will always
be deemed earlier (lesser) than one without.
The following are valid version numbers (shown in the order that
would be obtained by sorting according to the supplied cmp function):
0.4 0.4.0 (these two are equivalent)
0.4.1
0.5a1
0.5b3
0.5
0.9.6
1.0
1.0.4a3
1.0.4b1
1.0.4
The following are examples of invalid version numbers:
1
2.7.2.2
1.3.a4
1.3pl1
1.3c4
The rationale for this version numbering system will be explained
in the distutils documentation.
"""
version_re = re.compile(r'^(\d+) \. (\d+) (\. (\d+))? ([ab](\d+))?$',
re.VERBOSE)
def parse (self, vstring):
match = self.version_re.match(vstring)
if not match:
raise ValueError, "invalid version number '%s'" % vstring
(major, minor, patch, prerelease, prerelease_num) = \
match.group(1, 2, 4, 5, 6)
if patch:
self.version = tuple(map(string.atoi, [major, minor, patch]))
else:
self.version = tuple(map(string.atoi, [major, minor]) + [0])
if prerelease:
self.prerelease = (prerelease[0], string.atoi(prerelease_num))
else:
self.prerelease = None
def __str__ (self):
if self.version[2] == 0:
vstring = string.join(map(str, self.version[0:2]), '.')
else:
vstring = string.join(map(str, self.version), '.')
if self.prerelease:
vstring = vstring + self.prerelease[0] + str(self.prerelease[1])
return vstring
def __cmp__ (self, other):
if isinstance(other, StringType):
other = StrictVersion(other)
compare = cmp(self.version, other.version)
if (compare == 0): # have to compare prerelease
# case 1: neither has prerelease; they're equal
# case 2: self has prerelease, other doesn't; other is greater
# case 3: self doesn't have prerelease, other does: self is greater
# case 4: both have prerelease: must compare them!
if (not self.prerelease and not other.prerelease):
return 0
elif (self.prerelease and not other.prerelease):
return -1
elif (not self.prerelease and other.prerelease):
return 1
elif (self.prerelease and other.prerelease):
return cmp(self.prerelease, other.prerelease)
else: # numeric versions don't match --
return compare # prerelease stuff doesn't matter
# end class StrictVersion
# The rules according to Greg Stein:
# 1) a version number has 1 or more numbers separate by a period or by
# sequences of letters. If only periods, then these are compared
# left-to-right to determine an ordering.
# 2) sequences of letters are part of the tuple for comparison and are
# compared lexicographically
# 3) recognize the numeric components may have leading zeroes
#
# The LooseVersion class below implements these rules: a version number
# string is split up into a tuple of integer and string components, and
# comparison is a simple tuple comparison. This means that version
# numbers behave in a predictable and obvious way, but a way that might
# not necessarily be how people *want* version numbers to behave. There
# wouldn't be a problem if people could stick to purely numeric version
# numbers: just split on period and compare the numbers as tuples.
# However, people insist on putting letters into their version numbers;
# the most common purpose seems to be:
# - indicating a "pre-release" version
# ('alpha', 'beta', 'a', 'b', 'pre', 'p')
# - indicating a post-release patch ('p', 'pl', 'patch')
# but of course this can't cover all version number schemes, and there's
# no way to know what a programmer means without asking him.
#
# The problem is what to do with letters (and other non-numeric
# characters) in a version number. The current implementation does the
# obvious and predictable thing: keep them as strings and compare
# lexically within a tuple comparison. This has the desired effect if
# an appended letter sequence implies something "post-release":
# eg. "0.99" < "0.99pl14" < "1.0", and "5.001" < "5.001m" < "5.002".
#
# However, if letters in a version number imply a pre-release version,
# the "obvious" thing isn't correct. Eg. you would expect that
# "1.5.1" < "1.5.2a2" < "1.5.2", but under the tuple/lexical comparison
# implemented here, this just isn't so.
#
# Two possible solutions come to mind. The first is to tie the
# comparison algorithm to a particular set of semantic rules, as has
# been done in the StrictVersion class above. This works great as long
# as everyone can go along with bondage and discipline. Hopefully a
# (large) subset of Python module programmers will agree that the
# particular flavour of bondage and discipline provided by StrictVersion
# provides enough benefit to be worth using, and will submit their
# version numbering scheme to its domination. The free-thinking
# anarchists in the lot will never give in, though, and something needs
# to be done to accommodate them.
#
# Perhaps a "moderately strict" version class could be implemented that
# lets almost anything slide (syntactically), and makes some heuristic
# assumptions about non-digits in version number strings. This could
# sink into special-case-hell, though; if I was as talented and
# idiosyncratic as Larry Wall, I'd go ahead and implement a class that
# somehow knows that "1.2.1" < "1.2.2a2" < "1.2.2" < "1.2.2pl3", and is
# just as happy dealing with things like "2g6" and "1.13++". I don't
# think I'm smart enough to do it right though.
#
# In any case, I've coded the test suite for this module (see
# ../test/test_version.py) specifically to fail on things like comparing
# "1.2a2" and "1.2". That's not because the *code* is doing anything
# wrong, it's because the simple, obvious design doesn't match my
# complicated, hairy expectations for real-world version numbers. It
# would be a snap to fix the test suite to say, "Yep, LooseVersion does
# the Right Thing" (ie. the code matches the conception). But I'd rather
# have a conception that matches common notions about version numbers.
class LooseVersion (Version):
"""Version numbering for anarchists and software realists.
Implements the standard interface for version number classes as
described above. A version number consists of a series of numbers,
separated by either periods or strings of letters. When comparing
version numbers, the numeric components will be compared
numerically, and the alphabetic components lexically. The following
are all valid version numbers, in no particular order:
1.5.1
1.5.2b2
161
3.10a
8.02
3.4j
1996.07.12
3.2.pl0
3.1.1.6
2g6
11g
0.960923
2.2beta29
1.13++
5.5.kw
2.0b1pl0
In fact, there is no such thing as an invalid version number under
this scheme; the rules for comparison are simple and predictable,
but may not always give the results you want (for some definition
of "want").
"""
component_re = re.compile(r'(\d+ | [a-z]+ | \.)', re.VERBOSE)
def __init__ (self, vstring=None):
if vstring:
self.parse(vstring)
def parse (self, vstring):
# I've given up on thinking I can reconstruct the version string
# from the parsed tuple -- so I just store the string here for
# use by __str__
self.vstring = vstring
components = filter(lambda x: x and x != '.',
self.component_re.split(vstring))
for i in range(len(components)):
try:
components[i] = int(components[i])
except ValueError:
pass
self.version = components
def __str__ (self):
return self.vstring
def __repr__ (self):
return "LooseVersion ('%s')" % str(self)
def __cmp__ (self, other):
if isinstance(other, StringType):
other = LooseVersion(other)
return cmp(self.version, other.version)
# end class LooseVersion
| mit |