code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 4
991
| language
stringclasses 9
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using SimplePersistence.Example.Console.Models.Logging;
using SimplePersistence.Example.Console.UoW.EF.Mapping;
namespace SimplePersistence.Example.Console.UoW.EF.Migrations
{
public sealed class Configuration : DropCreateDatabaseIfModelChanges<ConsoleDbContext>//DbMigrationsConfiguration<ConsoleDbContext>
{
//public Configuration()
//{
// AutomaticMigrationsEnabled = false;
//}
protected override void Seed(ConsoleDbContext context)
{
context.Applications.AddOrUpdate(
e => e.Id,
new Application
{
Id = "SimplePersistence.Example.Console",
Description = "The SimplePersistence.Example.Console application",
CreatedOn = DateTime.Now,
CreatedBy = "seed.migration"
});
context.Levels.AddOrUpdate(
e => e.Id,
new Level
{
Id = "DEBUG",
Description = "Debug",
CreatedOn = DateTime.Now,
CreatedBy = "seed.migration"
},
new Level
{
Id = "Info",
Description = "Information",
CreatedOn = DateTime.Now,
CreatedBy = "seed.migration"
},
new Level
{
Id = "WARN",
Description = "Warning",
CreatedOn = DateTime.Now,
CreatedBy = "seed.migration"
},
new Level
{
Id = "ERROR",
Description = "Error",
CreatedOn = DateTime.Now,
CreatedBy = "seed.migration"
},
new Level
{
Id = "FATAL",
Description = "Fatal",
CreatedOn = DateTime.Now,
CreatedBy = "seed.migration"
});
}
}
}
|
gravity00/SimplePersistence
|
Examples/SimplePersistence.Example.Console/SimplePersistence.Example.Console.UoW.EF/Migrations/Configuration.cs
|
C#
|
mit
| 2,232 |
class CreateItineraries < ActiveRecord::Migration
def change
create_table :itineraries do |t|
t.references :user
t.timestamps null: false
end
end
end
|
nyc-fiddler-crabs-2015/Velox
|
db/migrate/20150328200056_create_itineraries.rb
|
Ruby
|
mit
| 176 |
import assert from 'assert'
import {
THREAD_COUNT,
CURSOR_BUFFER_SIZE,
THREAD_COUNTER_BYTE_LENGTH,
} from './constants'
import {
InputCursor,
StoredEventBatchPointer,
StoredEventPointer,
} from './types'
const checkThreadArrayLength = (threadArray: Array<number>): void => {
assert.strictEqual(
threadArray.length,
THREAD_COUNT,
'Cursor must be represented by array of 256 numbers'
)
}
export const initThreadArray = (): Array<number> => {
const threadCounters = new Array<number>(THREAD_COUNT)
threadCounters.fill(0)
return threadCounters
}
export const threadArrayToCursor = (threadArray: Array<number>): string => {
checkThreadArrayLength(threadArray)
const cursorBuffer: Buffer = Buffer.alloc(CURSOR_BUFFER_SIZE)
for (let i = 0; i < threadArray.length; ++i) {
cursorBuffer.writeUIntBE(
threadArray[i],
i * THREAD_COUNTER_BYTE_LENGTH,
THREAD_COUNTER_BYTE_LENGTH
)
}
return cursorBuffer.toString('base64')
}
export const cursorToThreadArray = (cursor: InputCursor): Array<number> => {
if (cursor == null) return initThreadArray()
const cursorBuffer = Buffer.from(cursor, 'base64')
assert.strictEqual(
cursorBuffer.length,
CURSOR_BUFFER_SIZE,
'Wrong size of cursor buffer'
)
const threadCounters = new Array<number>(THREAD_COUNT)
for (let i = 0; i < cursorBuffer.length / THREAD_COUNTER_BYTE_LENGTH; i++) {
threadCounters[i] = cursorBuffer.readUIntBE(
i * THREAD_COUNTER_BYTE_LENGTH,
THREAD_COUNTER_BYTE_LENGTH
)
}
return threadCounters
}
export const emptyLoadEventsResult = (
cursor: InputCursor
): StoredEventBatchPointer => {
return {
cursor: cursor == null ? threadArrayToCursor(initThreadArray()) : cursor,
events: [],
}
}
const calculateMaxThreadArray = (
threadArrays: Array<Array<number>>
): Array<number> => {
const maxThreadArray = initThreadArray()
for (const threadArray of threadArrays) {
checkThreadArrayLength(threadArray)
for (let i = 0; i < THREAD_COUNT; ++i) {
maxThreadArray[i] = Math.max(maxThreadArray[i], threadArray[i])
}
}
return maxThreadArray
}
export const checkEventsContinuity = (
startingCursor: InputCursor,
eventCursorPairs: StoredEventPointer[]
): boolean => {
const startingThreadArray = cursorToThreadArray(startingCursor)
const tuples = eventCursorPairs.map(({ event, cursor }) => {
return {
event,
cursor,
threadArray: cursorToThreadArray(cursor),
}
})
for (let i = 0; i < tuples.length; ++i) {
assert.strictEqual(
tuples[i].event.threadCounter,
tuples[i].threadArray[tuples[i].event.threadId] - 1
)
if (
startingThreadArray[tuples[i].event.threadId] >
tuples[i].event.threadCounter
) {
return false
}
}
const maxThreadArray = calculateMaxThreadArray(
tuples.map((t) => t.threadArray)
)
for (const t of tuples) {
startingThreadArray[t.event.threadId]++
}
for (let i = 0; i < THREAD_COUNT; ++i) {
if (maxThreadArray[i] !== startingThreadArray[i]) {
return false
}
}
return true
}
|
reimagined/resolve
|
packages/runtime/adapters/eventstore-adapters/eventstore-base/src/cursor-operations.ts
|
TypeScript
|
mit
| 3,122 |
'use strict'
let
ugly = require('gulp-uglify')
,gulp = require('gulp')
,watch = require('gulp-watch')
,plumber = require('gulp-plumber')
,newer = require('gulp-newer')
,stylus = require('gulp-stylus')
,jade = require('gulp-jade')
,concat = require('gulp-concat')
,rename = require('gulp-rename')
,runSequence = require('run-sequence')
,_ = require('lodash')
,path = require('path')
,fs = require('fs')
,spawn = require('cross-spawn')
let
cssFolder = __dirname + '/public/css'
,jsFolder = __dirname + '/public/js'
,views = __dirname + '/views'
,stylusOptions = {
compress: true
}
,uglyOptions = {
}
gulp.task('stylus', function() {
gulp.src(cssFolder + '/*.styl')
/*
.pipe(newer({
dest: cssFolder
,map: function(path) {
return path.replace(/\.styl$/, '.css')
}
}))
*/
.pipe(plumber())
.pipe(stylus(stylusOptions))
.pipe(gulp.dest(cssFolder))
})
gulp.task('ugly', function() {
gulp.src(jsFolder + '/*.js')
.pipe(newer({
dest: jsFolder
,map: function(path) {
return path.replace(/\.dev.js$/, '.min.js')
}
}))
.pipe(plumber())
.pipe(rename(function (path) {
path.basename = path.basename.replace('.dev', '.min')
}))
.pipe(gulp.dest(jsFolder))
.pipe(ugly(uglyOptions))
.pipe(gulp.dest(jsFolder))
})
let config = require('./config')
let pack = require('./package.json')
let packj = require('./node_modules/jade-press/package.json')
config.version = pack.version
config.siteDesc = packj.description
gulp.task('jade', function() {
gulp.src(views + '/*.jade')
.pipe(plumber())
.pipe(jade({
locals: config
}))
.pipe(gulp.dest(__dirname))
})
gulp.task('server', function (cb) {
var runner = spawn(
'node'
,['server']
,{
stdio: 'inherit'
}
)
runner.on('exit', function (code) {
process.exit(code)
})
runner.on('error', function (err) {
cb(err)
})
})
gulp.task('watch', function () {
runSequence('server')
watch([cssFolder + '/*.styl', cssFolder + '/parts/*.styl'], function() {
runSequence('stylus')
})
watch(jsFolder, function() {
runSequence('ugly')
})
watch([
views + '/*.jade'
,views + '/parts/*.jade'
], function() {
runSequence('jade')
}
)
})
gulp.task('default', ['watch'])
gulp.task('dist', function() {
runSequence('stylus', 'ugly', 'jade')
})
|
jade-press/jade-press.org
|
gulpfile.js
|
JavaScript
|
mit
| 2,290 |
<?php
require_once __DIR__.'/../../../vendor/autoload.php';
require 'templates/base.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Slide-Summarizer");
if ($credentials_file = getOAuthCredentialsFile()) {
// set the location manually
$client->setAuthConfig($credentials_file);
$credentials_json = json_decode(file_get_contents($credentials_file));
}
else {
echo missingServiceAccountDetailsWarning();
return;
}
$client->setRedirectUri('https://' . $_SERVER['HTTP_HOST'] . '/oauth2callback');
$client->addScope(Google_Service_Drive::DRIVE_READONLY);
if (! isset($_GET['code'])) {
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect_uri = 'https://' . $_SERVER['HTTP_HOST'] . '/';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
|
esimkowitz/Slide-Summarizer
|
web/public/views/oauth2callback.php
|
PHP
|
mit
| 998 |
/** ---------------------------------------------------------------------------
* -*- c++ -*-
* @file: particlebody.cpp
*
* Copyright (c) 2017 Yann Herklotz Grave <ymherklotz@gmail.com>
* MIT License, see LICENSE file for more details.
* ----------------------------------------------------------------------------
*/
#include <yage/physics/particlebody.h>
#include <cmath>
namespace yage
{
ParticleBody::ParticleBody(const Vector2d &position, double mass,
const Vector2d &velocity, bool gravity)
: Body(position, mass, velocity, gravity)
{
}
void ParticleBody::applyForce(const Vector2d &force)
{
force_ += force;
}
void ParticleBody::update()
{
// set the time_step for 60fps
double time_step = 1.0 / 60.0;
// set the last acceleration
Vector2d last_acceleration = acceleration_;
// update the position of the body
position_ += velocity_ * time_step +
(0.5 * last_acceleration * std::pow(time_step, 2));
// update the acceleration
if (gravity_) {
acceleration_ =
Vector2d(force_.x() / mass_, (GRAVITY + force_.y()) / mass_);
} else {
acceleration_ = Vector2d(force_.x() / mass_, force_.y() / mass_);
}
Vector2d avg_acceleration = (acceleration_ + last_acceleration) / 2.0;
// update the velocity of the body
velocity_ += avg_acceleration * time_step;
}
} // namespace yage
|
ymherklotz/YAGE
|
yage/physics/particlebody.cpp
|
C++
|
mit
| 1,426 |
package hu.autsoft.nytimes.exception;
public class OkHttpException extends RuntimeException {
public OkHttpException(Throwable cause) {
super(cause);
}
}
|
chriske/nytimes_api_demo
|
app/src/main/java/hu/autsoft/nytimes/exception/OkHttpException.java
|
Java
|
mit
| 172 |
const Lib = require("../src/main");
const assert = require("assert");
describe("plain object output", function () {
context("for `JSON.stringify` serializable objects", function () {
it("should have resembling structure", function () {
const obj1 = { a: 1, b: "b", c: true };
const res = Lib.write(obj1);
const exp1 = {
f: [
["a", 1],
["b", "b"],
["c", true]
]
};
assert.deepStrictEqual(res, exp1);
assert.equal(Lib.stringify(obj1), JSON.stringify(res));
const obj2 = { obj1 };
const exp2 = { f: [["obj1", exp1]] };
assert.deepStrictEqual(Lib.write(obj2), exp2);
assert.equal(Lib.stringify(obj2), JSON.stringify(exp2));
});
context("with `alwaysByRef: true`", function () {
it("should use references environment", function () {
const obj1 = { a: { a: 1 }, b: { b: "b" }, c: { c: true } };
const res = Lib.write(obj1, { alwaysByRef: true });
const exp1 = {
r: 3,
x: [
{ f: [["c", true]] },
{ f: [["b", "b"]] },
{ f: [["a", 1]] },
{
f: [
["a", { r: 2 }],
["b", { r: 1 }],
["c", { r: 0 }]
]
}
]
};
assert.deepStrictEqual(res, exp1);
const obj2 = Lib.read(res);
assert.notStrictEqual(obj1, obj2);
assert.deepStrictEqual(obj1, obj2);
});
});
});
it("should have correct format for shared values", function () {
const root = { val: "hi" };
root.rec1 = { obj1: root, obj2: root, obj3: { obj: root } };
root.rec2 = root;
assert.deepStrictEqual(Lib.write(root), {
r: 0,
x: [
{
f: [
["val", "hi"],
[
"rec1",
{
f: [
["obj1", { r: 0 }],
["obj2", { r: 0 }],
["obj3", { f: [["obj", { r: 0 }]] }]
]
}
],
["rec2", { r: 0 }]
]
}
]
});
});
});
describe("special values", function () {
it("should correctly restore them", function () {
const root = { undef: undefined, nul: null, nan: NaN };
const res = Lib.write(root);
assert.deepStrictEqual(res, {
f: [
["undef", { $: "undefined" }],
["nul", null],
["nan", { $: "NaN" }]
]
});
const { undef, nul, nan } = Lib.read(res);
assert.strictEqual(undef, undefined);
assert.strictEqual(nul, null);
assert.ok(typeof nan === "number" && Number.isNaN(nan));
});
});
describe("reading plain object", function () {
it("should correctly assign shared values", function () {
const obj = Lib.read({
r: 0,
x: [
{
f: [
["val", "hi"],
[
"rec1",
{
f: [
["obj1", { r: 0 }],
["obj2", { r: 0 }],
["obj3", { f: [["obj", { r: 0 }]] }]
]
}
],
["rec2", { r: 0 }]
]
}
]
});
assert.strictEqual(Object.keys(obj).sort().join(), "rec1,rec2,val");
assert.strictEqual(obj.val, "hi");
assert.strictEqual(Object.keys(obj.rec1).sort().join(), "obj1,obj2,obj3");
assert.strictEqual(Object.keys(obj.rec1.obj3).sort().join(), "obj");
assert.strictEqual(obj.rec2, obj);
assert.strictEqual(obj.rec1.obj1, obj);
assert.strictEqual(obj.rec1.obj2, obj);
assert.strictEqual(obj.rec1.obj3.obj, obj);
});
});
describe("object with parent", function () {
function MyObj() {
this.a = 1;
this.b = "b";
this.c = true;
}
Lib.regConstructor(MyObj);
it("should output `$` attribute", function () {
const obj1 = new MyObj();
assert.deepEqual(Lib.write(obj1), {
$: "MyObj",
f: [
["a", 1],
["b", "b"],
["c", true]
]
});
function Object() {
this.a = obj1;
}
Lib.regConstructor(Object);
assert.deepEqual(Lib.write(new Object()), {
$: "Object_1",
f: [
[
"a",
{
f: [
["a", 1],
["b", "b"],
["c", true]
],
$: "MyObj"
}
]
]
});
});
it("should use `$` attribute to resolve a type on read", function () {
const obj1 = Lib.read({
$: "MyObj",
f: [
["a", 1],
["b", "b"],
["c", true]
]
});
assert.strictEqual(obj1.constructor, MyObj);
assert.equal(Object.keys(obj1).sort().join(), "a,b,c");
assert.strictEqual(obj1.a, 1);
assert.strictEqual(obj1.b, "b");
assert.strictEqual(obj1.c, true);
});
context("for shared values", function () {
function Obj2() {}
Lib.regConstructor(Obj2);
it("should write shared values in `shared` map", function () {
const root = new Obj2();
root.l1 = new Obj2();
root.l1.back = root.l1;
assert.deepStrictEqual(Lib.write(root), {
f: [["l1", { r: 0 }]],
$: "Obj2",
x: [{ f: [["back", { r: 0 }]], $: "Obj2" }]
});
});
it("should use `#shared` keys to resolve prototypes on read", function () {
const obj1 = Lib.read({
f: [["l1", { r: 0 }]],
$: "Obj2",
x: [{ f: [["back", { r: 0 }]], $: "Obj2" }]
});
assert.strictEqual(obj1.constructor, Obj2);
assert.deepEqual(Object.keys(obj1), ["l1"]);
assert.deepEqual(Object.keys(obj1.l1), ["back"]);
assert.strictEqual(obj1.l1.constructor, Obj2);
assert.strictEqual(obj1.l1.back, obj1.l1);
});
});
});
describe("prototypes chain", function () {
it("should correctly store and recover all references", function () {
class C1 {
constructor(p) {
this.p1 = p;
}
}
class C2 extends C1 {
constructor() {
super("A");
this.c1 = new C1(this);
}
}
Lib.regOpaqueObject(C1.prototype, "C1");
Lib.regOpaqueObject(C2.prototype, "C2");
const obj = new C2();
C1.prototype.p_prop_1 = "prop_1";
const res = Lib.write(obj);
C1.prototype.p_prop_1 = "changed";
assert.deepEqual(res, {
r: 0,
x: [
{
p: { $: "C2" },
f: [
["p1", "A"],
[
"c1",
{
p: { $: "C1", f: [["p_prop_1", "prop_1"]] },
f: [["p1", { r: 0 }]]
}
]
]
}
]
});
const r2 = Lib.read(res);
assert.ok(r2 instanceof C1);
assert.ok(r2 instanceof C2);
assert.strictEqual(r2.constructor, C2);
assert.strictEqual(Object.getPrototypeOf(r2).constructor, C2);
assert.strictEqual(r2.c1.constructor, C1);
assert.strictEqual(r2.c1.p1, r2);
assert.equal(r2.p1, "A");
assert.strictEqual(C1.prototype.p_prop_1, "prop_1");
class C3 {
constructor(val) {
this.a = val;
}
}
Lib.regOpaqueObject(C3.prototype, "C3", { props: false });
class C4 extends C3 {
constructor() {
super("A");
this.b = "B";
}
}
Lib.regOpaqueObject(C4.prototype, "C4");
const obj2 = new C4();
const res2 = Lib.write(obj2);
assert.deepEqual(res2, {
p: {
$: "C4"
},
f: [
["a", "A"],
["b", "B"]
]
});
const obj3 = Lib.read(res2);
assert.ok(obj3 instanceof C3);
assert.ok(obj3 instanceof C4);
assert.equal(obj3.a, "A");
assert.equal(obj3.b, "B");
assert.equal(
Object.getPrototypeOf(Object.getPrototypeOf(obj3)),
Object.getPrototypeOf(Object.getPrototypeOf(obj2))
);
});
});
describe("property's descriptor", function () {
it("should correctly store and recover all settings", function () {
const a = {};
let setCalled = 0;
let getCalled = 0;
let back;
let val;
const descr = {
set(value) {
assert.strictEqual(this, back);
setCalled++;
val = value;
},
get() {
assert.strictEqual(this, back);
getCalled++;
return a;
}
};
Object.defineProperty(a, "prop", descr);
const psym1 = Symbol("prop");
const psym2 = Symbol("prop");
Object.defineProperty(a, psym1, {
value: "B",
enumerable: true
});
Object.defineProperty(a, psym2, {
value: "C",
configurable: true
});
Object.defineProperty(a, Symbol.for("prop"), {
value: "D",
writable: true
});
Lib.regOpaqueObject(descr.set, "dset");
Lib.regOpaqueObject(descr.get, "dget");
const opts = { symsByName: new Map() };
const res = Lib.write(a, opts);
assert.deepEqual(res, {
f: [
["prop", null, 15, { $: "dget" }, { $: "dset" }],
[{ name: "prop" }, "B", 5],
[{ name: "prop", id: 1 }, "C", 6],
[{ key: "prop" }, "D", 3]
]
});
back = Lib.read(res, opts);
assert.deepEqual(Object.getOwnPropertySymbols(back), [
psym1,
psym2,
Symbol.for("prop")
]);
assert.strictEqual(setCalled, 0);
assert.strictEqual(getCalled, 0);
back.prop = "A";
assert.strictEqual(setCalled, 1);
assert.strictEqual(getCalled, 0);
assert.strictEqual(val, "A");
assert.strictEqual(back.prop, a);
assert.strictEqual(
Object.getOwnPropertyDescriptor(back, Symbol("prop")),
void 0
);
assert.deepEqual(Object.getOwnPropertyDescriptor(back, "prop"), {
enumerable: false,
configurable: false,
...descr
});
assert.deepEqual(Object.getOwnPropertyDescriptor(back, psym1), {
value: "B",
writable: false,
enumerable: true,
configurable: false
});
assert.deepEqual(Object.getOwnPropertyDescriptor(back, psym2), {
value: "C",
writable: false,
enumerable: false,
configurable: true
});
assert.deepEqual(
Object.getOwnPropertyDescriptor(back, Symbol.for("prop")),
{
value: "D",
writable: true,
enumerable: false,
configurable: false
}
);
});
});
describe("arrays serialization", function () {
context("without shared references", function () {
it("should be similar to `JSON.stringify`/`JSON.parse`", function () {
const obj = { arr: [1, "a", [true, [false, null]], undefined] };
const res = Lib.write(obj);
assert.deepStrictEqual(res, {
f: [["arr", [1, "a", [true, [false, null]], { $: "undefined" }]]]
});
const back = Lib.read(res);
assert.deepStrictEqual(obj, back);
});
it("doesn't support Array as root", function () {
assert.throws(() => Lib.write([1, 2]), TypeError);
});
});
it("should handle shared references", function () {
const obj = { arr: [1, "a", [true, [false, null]], undefined] };
obj.arr.push(obj.arr);
const res = Lib.write(obj);
assert.notStrictEqual(res, obj);
assert.deepStrictEqual(res, {
f: [["arr", { r: 0 }]],
x: [[1, "a", [true, [false, null]], { $: "undefined" }, { r: 0 }]]
});
const back = Lib.read(res);
assert.notStrictEqual(res, back);
assert.deepStrictEqual(obj, back);
});
});
describe("`Set` serialization", function () {
context("without shared references", function () {
it("should output `JSON.stringify` serializable object", function () {
const arr = [1, "a", [true, [false, null]], undefined];
const obj = { set: new Set(arr) };
obj.set.someNum = 100;
obj.set.self = obj.set;
const res = Lib.write(obj);
assert.deepStrictEqual(res, {
f: [["set", { r: 0 }]],
x: [
{
$: "Set",
l: [1, "a", [true, [false, null]], { $: "undefined" }],
f: [
["someNum", 100],
["self", { r: 0 }]
]
}
]
});
const back = Lib.read(res);
assert.deepStrictEqual(obj, back);
});
});
it("should handle shared references", function () {
const obj = new Set([1, "a", [true, [false, null]], undefined]);
obj.add(obj);
const res = Lib.write(obj);
assert.notStrictEqual(res, obj);
assert.deepStrictEqual(res, {
r: 0,
x: [
{
$: "Set",
l: [1, "a", [true, [false, null]], { $: "undefined" }, { r: 0 }]
}
]
});
const back = Lib.read(res);
assert.notStrictEqual(res, back);
assert.deepStrictEqual(obj, back);
});
});
describe("`Map` serialization", function () {
context("without shared references", function () {
it("should output `JSON.stringify` serializable object", function () {
const arr = [[1, "a"], [true, [false, null]], [undefined]];
const obj = { map: new Map(arr) };
const res = Lib.write(obj);
assert.deepStrictEqual(res, {
f: [
[
"map",
{
$: "Map",
k: [1, true, { $: "undefined" }],
v: ["a", [false, null], { $: "undefined" }]
}
]
]
});
const back = Lib.read(res);
assert.deepStrictEqual(obj, back);
});
});
it("should handle shared references", function () {
const obj = new Map([[1, "a"], [true, [false, null]], [undefined]]);
obj.set(obj, obj);
const res = Lib.write(obj);
assert.notStrictEqual(res, obj);
assert.deepStrictEqual(res, {
r: 0,
x: [
{
$: "Map",
k: [1, true, { $: "undefined" }, { r: 0 }],
v: ["a", [false, null], { $: "undefined" }, { r: 0 }]
}
]
});
const back = Lib.read(res);
assert.notStrictEqual(res, back);
assert.deepStrictEqual(obj, back);
});
});
describe("opaque objects serialization", function () {
it("should throw for not registered objects", function () {
function a() {}
assert.throws(() => Lib.write({ a }), TypeError);
});
it("should not throw if `ignore:true`", function () {
function a() {}
assert.deepStrictEqual(Lib.write({ a }, { ignore: true }), {});
});
it("should output object's name if registered", function () {
function a() {}
Lib.regOpaqueObject(a);
assert.deepStrictEqual(Lib.write({ a }), { f: [["a", { $: "a" }]] });
Lib.regOpaqueObject(a);
assert.deepStrictEqual(Lib.read({ f: [["a", { $: "a" }]] }), { a });
(function () {
function a() {}
Lib.regOpaqueObject(a);
assert.deepStrictEqual(Lib.write({ a }), { f: [["a", { $: "a_1" }]] });
assert.deepStrictEqual(Lib.read({ f: [["a", { $: "a_1" }]] }), { a });
})();
});
it("should not serialize properties specified before its registration", function () {
const obj = {
prop1: "p1",
[Symbol.for("sym#a")]: "s1",
[Symbol.for("sym#b")]: "s2",
prop2: "p2",
[3]: "N3",
[4]: "N4"
};
Lib.regOpaqueObject(obj, "A");
obj.prop1 = "P2";
obj.prop3 = "p3";
obj[Symbol.for("sym#a")] = "S1";
obj[Symbol.for("sym#c")] = "s3";
obj[4] = "n4";
obj[5] = "n5";
assert.deepStrictEqual(Lib.write({ obj }), {
f: [
[
"obj",
{
$: "A",
f: [
["4", "n4"],
["5", "n5"],
["prop1", "P2"],
["prop3", "p3"],
[
{
key: "sym#a"
},
"S1"
],
[
{
key: "sym#c"
},
"s3"
]
]
}
]
]
});
});
});
describe("opaque primitive value serialization", function () {
it("should output object's name if registered", function () {
const a = Symbol("a");
Lib.regOpaquePrim(a, "sa");
assert.ok(!a[Lib.descriptorSymbol]);
assert.deepStrictEqual(Lib.write({ a }), {
f: [["a", { $: "sa" }]]
});
Lib.regOpaquePrim(a, "sb");
assert.deepStrictEqual(Lib.read({ f: [["a", { $: "sa" }]] }), {
a
});
(function () {
const a = Symbol("a");
Lib.regOpaquePrim(a, "sa");
assert.deepStrictEqual(Lib.write({ a }), {
f: [["a", { $: "sa_1" }]]
});
assert.deepStrictEqual(Lib.read({ f: [["a", { $: "sa_1" }]] }), { a });
})();
});
});
describe("Symbols serialization", function () {
it("should keep values", function () {
const a1 = Symbol("a");
const a2 = Symbol("a");
const b = Symbol("b");
const g = Symbol.for("g");
const opts = { symsByName: new Map() };
const res = Lib.write({ a1, a2, b1: b, b2: b, g }, opts);
assert.deepStrictEqual(res, {
f: [
["a1", { name: "a", $: "Symbol" }],
["a2", { name: "a", id: 1, $: "Symbol" }],
["b1", { name: "b", $: "Symbol" }],
["b2", { name: "b", $: "Symbol" }],
["g", { key: "g", $: "Symbol" }]
]
});
const { a1: ra1, a2: ra2, b1: rb1, b2: rb2, g: rg } = Lib.read(res, opts);
assert.strictEqual(a1, ra1);
assert.strictEqual(a2, ra2);
assert.strictEqual(b, rb1);
assert.strictEqual(b, rb2);
assert.strictEqual(rg, g);
const { a1: la1, a2: la2, b1: lb1, b2: lb2, g: lg } = Lib.read(res, {
ignore: true
});
assert.notStrictEqual(a1, la1);
assert.notStrictEqual(a2, la2);
assert.notStrictEqual(lb1, b);
assert.notStrictEqual(lb2, b);
assert.strictEqual(lg, g);
assert.strictEqual(lb1, lb2);
assert.equal(String(la1), "Symbol(a)");
assert.equal(String(la2), "Symbol(a)");
assert.equal(String(lb1), "Symbol(b)");
assert.equal(String(lb2), "Symbol(b)");
});
});
describe("type with `$$typeof` attribute", function () {
Lib.regDescriptor({
name: "hundred",
typeofTag: 100,
read(ctx, json) {
return { $$typeof: 100 };
},
write(ctx, value) {
return { $: "hundred" };
},
props: false
});
it("should use overriden methods", function () {
assert.deepStrictEqual(Lib.write({ $$typeof: 100 }), {
$: "hundred"
});
assert.deepStrictEqual(Lib.read({ $: "hundred" }), { $$typeof: 100 });
});
});
describe("bind function arguments", function () {
it("should be serializable", function () {
const obj = {};
function f1(a1, a2, a3) {
return [this, a1, a2, a3];
}
const a1 = {},
a2 = {},
a3 = {};
Lib.regOpaqueObject(obj, "obj");
Lib.regOpaqueObject(f1);
Lib.regOpaqueObject(a1, "arg");
Lib.regOpaqueObject(a2, "arg");
const bind = Lib.bind(f1, obj, a1, a2);
bind.someNum = 100;
bind.rec = bind;
const fjson = Lib.write({ f: bind });
assert.deepStrictEqual(fjson, {
f: [
[
"f",
{
r: 0
}
]
],
x: [
{
f: [
["someNum", 100],
[
"rec",
{
r: 0
}
],
[
{
$: "#this"
},
{
$: "obj"
}
],
[
{
$: "#fun"
},
{
$: "f1"
}
],
[
{
$: "#args"
},
[
{
$: "arg"
},
{
$: "arg_1"
}
]
]
],
$: "Bind"
}
]
});
const f2 = Lib.read(fjson).f;
assert.notStrictEqual(f1, f2);
const res = f2(a3);
assert.strictEqual(res.length, 4);
const [robj, ra1, ra2, ra3] = res;
assert.strictEqual(obj, robj);
assert.strictEqual(a1, ra1);
assert.strictEqual(a2, ra2);
assert.strictEqual(a3, ra3);
});
});
describe("RegExp", function () {
it("should be serializable", function () {
const re1 = /\w+/;
const re2 = /ho/g;
const s1 = "uho-ho-ho";
re2.test(s1);
const res = Lib.write({ re1, re2 });
assert.deepEqual(res, {
f: [
["re1", { src: "\\w+", flags: "", $: "RegExp" }],
["re2", { src: "ho", flags: "g", last: 3, $: "RegExp" }]
]
});
const { re1: bre1, re2: bre2 } = Lib.read(res);
assert.equal(re1.src, bre1.src);
assert.equal(re1.flags, bre1.flags);
assert.equal(re1.lastIndex, bre1.lastIndex);
assert.equal(re2.src, bre2.src);
assert.equal(re2.flags, bre2.flags);
assert.equal(re2.lastIndex, bre2.lastIndex);
});
});
describe("not serializable values", function () {
it("should throw an exception if `ignore:falsy`", function () {
function A() {}
try {
Lib.write({ A });
} catch (e) {
assert.equal(e.constructor, TypeError);
assert.equal(
e.message,
`not serializable value "function A() {}" at "1"(A) of "A"`
);
return;
}
assert.fail("should throw");
});
it("should be ignored if `ignore:true`", function () {
function A() {}
const d = Lib.write({ A }, { ignore: true });
const r = Lib.read(d);
assert.deepEqual(r, {});
});
it('should register an opaque descriptor `ignore:"opaque"`', function () {
function A() {}
const d = Lib.write({ A, b: A }, { ignore: "opaque" });
const r = Lib.read(d);
assert.deepEqual(r, { A, b: A });
});
it("should register an opaque descriptor with auto-opaque descriptor", function () {
function A() {}
Lib.regAutoOpaqueConstr(A, true);
const a = new A();
const d = Lib.write({ a, b: a }, { ignore: "opaque" });
const r = Lib.read(d);
assert.deepEqual(r, { a, b: a });
});
it('should be converted into a not usable placeholder if `ignore:"placeholder"`', function () {
function A() {}
const d = Lib.write({ A }, { ignore: "placeholder" });
const r = Lib.read(d);
try {
r.A();
} catch (e) {
assert.equal(e.constructor, TypeError);
assert.equal(e.message, "apply in a not restored object");
return;
}
assert.fail("should throw");
});
});
describe("TypedArray", function () {
it("should be serializable", function () {
const arr1 = new Int32Array([1, 2, 3, 4, 5]);
const arr2 = new Uint32Array(arr1.buffer, 8);
const d = Lib.write({ arr1, arr2 }, {});
assert.deepStrictEqual(d, {
f: [
[
"arr1",
{
o: 0,
l: 5,
b: {
r: 0
},
$: "Int32Array"
}
],
[
"arr2",
{
o: 8,
l: 3,
b: {
r: 0
},
$: "Uint32Array"
}
]
],
x: [
{
d: "AQAAAAIAAAADAAAABAAAAAUAAAA=",
$: "ArrayBuffer"
}
]
});
const { arr1: rarr1, arr2: rarr2 } = Lib.read(d);
assert.equal(rarr1.constructor, Int32Array);
assert.equal(rarr2.constructor, Uint32Array);
assert.notStrictEqual(arr1, rarr1);
assert.notStrictEqual(arr2, rarr2);
assert.deepStrictEqual(arr1, rarr1);
assert.deepStrictEqual(arr2, rarr2);
});
});
describe("WeakSet/WeakMap", function () {
it("should be serializable", function () {
const set = new WeakSet();
const map = new WeakMap();
const map2 = new WeakMap();
const obj1 = {};
const obj2 = {};
Lib.regOpaqueObject(obj1, "w#obj1");
set.add(obj1).add(obj2);
map.set(obj1, "obj1").set(obj2, "obj2");
map2.set(obj1, "2obj1");
assert.ok(set.has(obj1));
assert.ok(map.has(obj1));
assert.strictEqual(map.get(obj1), "obj1");
assert.strictEqual(map.get({}), void 0);
const d = Lib.write({ set, map, map2, obj1, obj2 });
assert.deepStrictEqual(d, {
x: [{}, { $: "w#obj1" }],
f: [
["set", { v: [{ r: 0 }, { r: 1 }], $: "WeakSet" }],
[
"map",
{
k: [{ r: 1 }, { r: 0 }],
v: ["obj1", "obj2"],
$: "WeakMap"
}
],
[
"map2",
{
k: [{ r: 1 }],
v: ["2obj1"],
$: "WeakMap"
}
],
["obj1", { r: 1 }],
["obj2", { r: 0 }]
]
});
const {
set: rset,
map: rmap,
map2: rmap2,
obj1: robj1,
obj2: robj2
} = Lib.read(d);
assert.strictEqual(robj1, obj1);
assert.notStrictEqual(robj2, obj2);
assert.ok(rset.has(obj1));
assert.ok(set.delete(obj1));
assert.ok(!set.has(obj1));
assert.ok(rset.has(obj1));
assert.ok(rset.has(robj2));
assert.ok(!rset.has(obj2));
assert.ok(!set.has(robj2));
assert.strictEqual(rmap.get(obj1), "obj1");
assert.strictEqual(rmap2.get(obj1), "2obj1");
assert.ok(map.delete(obj1));
assert.strictEqual(rmap.get(obj1), "obj1");
assert.ok(rset.delete(robj2));
assert.ok(!rset.has(robj2));
assert.ok(!rset.delete(robj2));
assert.ok(!rset.has(robj2));
});
});
describe("WeakSet/WeakMap workaround", function () {
it("should be serializable", function () {
const set = new Lib.WeakSetWorkaround();
const map = new Lib.WeakMapWorkaround();
const map2 = new Lib.WeakMapWorkaround();
const obj1 = {};
const obj2 = {};
Lib.regOpaqueObject(obj1, "w##obj1");
set.add(obj1).add(obj2);
map.set(obj1, "obj1").set(obj2, "obj2");
map2.set(obj1, "2obj1");
assert.ok(set.has(obj1));
assert.ok(map.has(obj1));
assert.strictEqual(map.get(obj1), "obj1");
assert.strictEqual(map.get({}), void 0);
const d = Lib.write({ set, map, map2, obj1, obj2 });
assert.deepStrictEqual(d, {
f: [
[
"set",
{
f: [["prop", { name: "@effectful/weakset", $: "Symbol" }]],
$: "WeakSet#"
}
],
[
"map",
{
f: [["prop", { name: "@effectful/weakmap", $: "Symbol" }]],
$: "WeakMap#"
}
],
[
"map2",
{
f: [["prop", { name: "@effectful/weakmap", id: 1, $: "Symbol" }]],
$: "WeakMap#"
}
],
[
"obj1",
{
$: "w##obj1",
f: [
[{ name: "@effectful/weakset" }, true, 2],
[{ name: "@effectful/weakmap" }, "obj1", 2],
[{ name: "@effectful/weakmap", id: 1 }, "2obj1", 2]
]
}
],
[
"obj2",
{
f: [
[{ name: "@effectful/weakset" }, true, 2],
[{ name: "@effectful/weakmap" }, "obj2", 2]
]
}
]
]
});
const {
set: rset,
map: rmap,
map2: rmap2,
obj1: robj1,
obj2: robj2
} = Lib.read(d);
assert.strictEqual(robj1, obj1);
assert.notStrictEqual(robj2, obj2);
assert.ok(rset.has(obj1));
assert.ok(set.delete(obj1));
assert.ok(!set.has(obj1));
assert.ok(rset.has(obj1));
assert.ok(rset.has(robj2));
assert.ok(!rset.has(obj2));
assert.ok(!set.has(robj2));
assert.strictEqual(rmap.get(obj1), "obj1");
assert.strictEqual(rmap2.get(obj1), "2obj1");
assert.ok(map.delete(obj1));
assert.strictEqual(rmap.get(obj1), "obj1");
assert.ok(rset.delete(robj2));
assert.ok(!rset.has(robj2));
assert.ok(!rset.delete(robj2));
assert.ok(!rset.has(robj2));
});
});
describe("BigInt", function () {
it("should be serializable", function () {
const num = 2n ** 10000n;
const doc = Lib.write({ num });
assert.equal(doc.f[0][0], "num");
assert.ok(doc.f[0][1].int.substr);
assert.equal(doc.f[0][1].int.length, 3011);
assert.strictEqual(Lib.read(doc).num, num);
});
});
|
awto/effectfuljs
|
packages/serialization/test/main.js
|
JavaScript
|
mit
| 27,905 |
package se.leiflandia.lroi.utils;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import se.leiflandia.lroi.auth.model.AccessToken;
import se.leiflandia.lroi.auth.model.UserCredentials;
public class AuthUtils {
private static final String PREF_ACTIVE_ACCOUNT = "active_account";
private static final String PREFS_NAME = "se.leiflandia.lroi.prefs";
public static void removeActiveAccount(Context context, String accountType) {
Account account = getActiveAccount(context, accountType);
if (account != null) {
AccountManager.get(context).removeAccount(account, null, null);
}
setActiveAccountName(context, null);
}
public static Account getActiveAccount(final Context context, final String accountType) {
Account[] accounts = AccountManager.get(context).getAccountsByType(accountType);
return getActiveAccount(accounts, getActiveAccountName(context));
}
public static boolean hasActiveAccount(final Context context, final String accountType) {
return getActiveAccount(context, accountType) != null;
}
private static String getActiveAccountName(final Context context) {
return getSharedPreferences(context)
.getString(PREF_ACTIVE_ACCOUNT, null);
}
public static void setActiveAccountName(final Context context, final String name) {
getSharedPreferences(context).edit()
.putString(PREF_ACTIVE_ACCOUNT, name)
.commit();
}
private static Account getActiveAccount(final Account[] accounts, final String activeAccountName) {
for (Account account : accounts) {
if (TextUtils.equals(account.name, activeAccountName)) {
return account;
}
}
return null;
}
private static SharedPreferences getSharedPreferences(final Context context) {
return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
}
/**
* Saves an authorized account in account manager and set as active account.
*/
public static void setAuthorizedAccount(Context context, UserCredentials credentials, AccessToken token, String authtokenType, String accountType) {
final AccountManager accountManager = AccountManager.get(context);
Account account = findOrCreateAccount(accountManager, credentials.getUsername(), token.getRefreshToken(), accountType);
accountManager.setAuthToken(account, authtokenType, token.getAccessToken());
setActiveAccountName(context, account.name);
}
/**
* Sets password of account, creates a new account if necessary.
*/
private static Account findOrCreateAccount(AccountManager accountManager, String username, String refreshToken, String accountType) {
for (Account account : accountManager.getAccountsByType(accountType)) {
if (account.name.equals(username)) {
accountManager.setPassword(account, refreshToken);
return account;
}
}
Account account = new Account(username, accountType);
accountManager.addAccountExplicitly(account, refreshToken, null);
return account;
}
}
|
Wadpam/lets-the-right-one-in
|
lroi-lib/src/main/java/se/leiflandia/lroi/utils/AuthUtils.java
|
Java
|
mit
| 3,349 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Xml.Linq;
using Reportz.Scripting.Attributes;
using Reportz.Scripting.Classes;
using Reportz.Scripting.Interfaces;
namespace Reportz.Scripting.Commands
{
[ScriptElementAlias("execute-script")]
public class ExecuteScriptCommand : IExecutable, IScriptElement
{
private IScriptParser _instantiator;
private XElement _element;
private ArgCollection _argsCollection;
private EventCollection _eventsCollection;
public ExecuteScriptCommand()
{
}
public string ScriptName { get; private set; }
public IExecutableResult Execute(IExecutableArgs args)
{
IExecutableResult result = null;
args = args ?? new ExecutableArgs { Scope = new VariableScope() };
try
{
var ctx = args?.Scope.GetScriptContext();
var scriptName = args?.Arguments?.FirstOrDefault(x => x.Key == "scriptName")?.Value?.ToString();
scriptName = scriptName ?? ScriptName;
if (string.IsNullOrWhiteSpace(scriptName))
throw new Exception($"Invalid script name.");
var script = ctx?.ScriptScope?.GetScript(scriptName);
if (script == null)
throw new Exception($"Could not get script '{scriptName}'. ");
var scriptArgs = new ExecutableArgs();
scriptArgs.Scope = args.Scope.CreateChild();
//scriptArgs.Arguments = _argsCollection?._vars?.Values?.ToArray();
var scriptArgVars = _argsCollection?._vars?.Values?.ToArray();
if (scriptArgVars != null)
{
foreach (var scriptVar in scriptArgVars)
{
var r = scriptVar.Execute(scriptArgs);
}
}
result = script.Execute(scriptArgs);
return result;
}
catch (Exception ex)
{
IEvent errorEvent;
if (_eventsCollection._events.TryGetValue("error", out errorEvent) && errorEvent != null)
{
var exceptionVar = new Variable
{
Key = "$$Exception",
Value = ex,
};
args.Scope?.SetVariable(exceptionVar);
errorEvent.Execute(args);
}
return result;
// todo: implement 'catch' logic. catch="true" on <event key="error">. Or only if wrapped inside <try> <catch>
// todo: implement test <throw> tag
//throw;
}
finally
{
IEvent completeEvent;
if (_eventsCollection._events.TryGetValue("complete", out completeEvent) && completeEvent != null)
{
var resultVar = new Variable
{
Key = "$$Result",
Value = result?.Result,
};
args.Scope?.SetVariable(resultVar);
completeEvent.Execute(args);
}
}
}
public void Configure(IScriptParser parser, XElement element)
{
_instantiator = parser;
_element = element;
ScriptName = element?.Attribute("scriptName")?.Value ??
element?.Attribute("name")?.Value;
var argsElem = element?.Element("arguments");
if (argsElem != null)
{
var arg = new ArgCollection();
arg.Configure(parser, argsElem);
_argsCollection = arg;
}
var eventsElem = element?.Element("events");
if (eventsElem != null)
{
var events = new EventCollection();
events.Configure(parser, eventsElem);
_eventsCollection = events;
}
}
}
}
|
LazyTarget/Reportz
|
Reportz.Scripting/Commands/ExecuteScriptCommand.cs
|
C#
|
mit
| 4,213 |
(function () {
'use strict';
angular
.module('crimes.routes')
.config(routeConfig);
routeConfig.$inject = ['$stateProvider'];
function routeConfig($stateProvider) {
$stateProvider
.state('crimes', {
abstract: true,
url: '/crimes',
template: '<ui-view/>'
})
.state('crimes.list', {
url: '',
templateUrl: '/modules/crimes/client/views/list-crimes.client.view.html',
controller: 'CrimesListController',
controllerAs: 'vm',
data: {
pageTitle: 'Crimes List'
}
})
.state('crimes.view', {
url: '/:crimeId',
templateUrl: '/modules/crimes/client/views/view-crimes.client.view.html',
controller: 'CrimesController',
controllerAs: 'vm',
resolve: {
crimeResolve: getCrime
},
data: {
pageTitle: 'Crimes {{ crimeResolve.title }}'
}
});
}
getCrime.$inject = ['$stateParams', 'CrimesService'];
function getCrime($stateParams, CrimesService) {
return CrimesService.get({
crimeId: $stateParams.crimeId
}).$promise;
}
}());
|
ravikumargh/Police
|
modules/crimes/client/config/crime.client.routes.js
|
JavaScript
|
mit
| 1,154 |
<?php
if( $kind = ic_get_post( 'kind' ) ) {
if( $kind == 'c' || $kind == 'cod' ) { $sym = '#'; $kind = 'cod'; }
else if( $kind == 'l' || $kind == 'loc' ) { $sym = '@'; $kind = 'loc'; }
else if( $kind == 's' || $kind == 'str' ) { $sym = '*'; $kind = 'str'; }
else if( $kind == 'u' || $kind == 'usr' ) { $sym = '+'; $kind = 'usr'; }
if( $name = ic_get_post( 'filters-req' ) ) {
$filter = $_SESSION['filters'][$sym.$name];
$filter->manage( 'req' );
} else if( $name = ic_get_post( 'filters-sign' ) ) {
$filter = $_SESSION['filters'][$sym.$name];
$filter->manage( 'sign' );
} else if( $name = ic_get_post( 'trashed_filter' ) ) {
$filter = $_SESSION['filters'][$sym.$name];
$filter->manage( 'clear' );
} else if( $name = ic_get_post( 'new_filter' ) ) {
$sign = ( $post_meta = ic_get_post( 'new_sign' ) ) ? $post_meta : 'd';
$filter = new filter( $name, $kind, $sign );
$filter->manage( 'add' );
} $filter_change = TRUE;
}
if( isset( $filter_change ) || ic_get_post( 'filters_refresh' ) ) {
foreach( $_SESSION['filters'] as $filter ) $filter->tag();
} else {
$sign_filters = get_setting( 'sign_filters');
$on = $sign_filters != 1 ? ',\'d\'' : ',0';
$filts = $sign_filters != 1 ? 'style="display:none;"' : '';
$hover = get_setting( 'hover_help' );
?>
<div id="hover-help">
<div class="hover-off" id="hh-ftradd"><?php tr( 'ftradd', 'h' ) ?></div>
</div>
<div class="text-box" id="shell-filters">
<div class="filters-choice filters-choice-signs"><?php filter::add_filters( 'input-filters', 'addFilter()', 'addFilterSelect()' ) ?></div>
<div id="filters">
<?php
$filter_change = TRUE;
include( 'filters-main.php' );
echo '</div></div>';
}
|
mhaddir/draco
|
apps/filters/filters-news.php
|
PHP
|
mit
| 1,680 |
class IssueTrackerService < Service
validate :one_issue_tracker, if: :activated?, on: :manual_change
default_value_for :category, 'issue_tracker'
# Pattern used to extract links from comments
# Override this method on services that uses different patterns
# This pattern does not support cross-project references
# The other code assumes that this pattern is a superset of all
# overriden patterns. See ReferenceRegexes::EXTERNAL_PATTERN
def self.reference_pattern
@reference_pattern ||= %r{(\b[A-Z][A-Z0-9_]+-|#{Issue.reference_prefix})(?<issue>\d+)}
end
def default?
default
end
def issue_url(iid)
self.issues_url.gsub(':id', iid.to_s)
end
def issue_tracker_path
project_url
end
def new_issue_path
new_issue_url
end
def issue_path(iid)
issue_url(iid)
end
def fields
[
{ type: 'text', name: 'description', placeholder: description },
{ type: 'text', name: 'project_url', placeholder: 'Project url', required: true },
{ type: 'text', name: 'issues_url', placeholder: 'Issue url', required: true },
{ type: 'text', name: 'new_issue_url', placeholder: 'New Issue url', required: true }
]
end
# Initialize with default properties values
# or receive a block with custom properties
def initialize_properties(&block)
return unless properties.nil?
if enabled_in_gitlab_config
if block_given?
yield
else
self.properties = {
title: issues_tracker['title'],
project_url: issues_tracker['project_url'],
issues_url: issues_tracker['issues_url'],
new_issue_url: issues_tracker['new_issue_url']
}
end
else
self.properties = {}
end
end
def self.supported_events
%w(push)
end
def execute(data)
return unless supported_events.include?(data[:object_kind])
message = "#{self.type} was unable to reach #{self.project_url}. Check the url and try again."
result = false
begin
response = HTTParty.head(self.project_url, verify: true)
if response
message = "#{self.type} received response #{response.code} when attempting to connect to #{self.project_url}"
result = true
end
rescue HTTParty::Error, Timeout::Error, SocketError, Errno::ECONNRESET, Errno::ECONNREFUSED, OpenSSL::SSL::SSLError => error
message = "#{self.type} had an error when trying to connect to #{self.project_url}: #{error.message}"
end
Rails.logger.info(message)
result
end
private
def enabled_in_gitlab_config
Gitlab.config.issues_tracker &&
Gitlab.config.issues_tracker.values.any? &&
issues_tracker
end
def issues_tracker
Gitlab.config.issues_tracker[to_param]
end
def one_issue_tracker
return if template?
return if project.blank?
if project.services.external_issue_trackers.where.not(id: id).any?
errors.add(:base, 'Another issue tracker is already in use. Only one issue tracker service can be active at a time')
end
end
end
|
dplarson/gitlabhq
|
app/models/project_services/issue_tracker_service.rb
|
Ruby
|
mit
| 3,048 |
/**
* Compile sass files to css using compass
*/
module.exports = {
dev: {
options: {
config: 'config.rb',
environment: 'development'
}
},
};
|
timothytran/ngModular
|
grunt/compass.js
|
JavaScript
|
mit
| 192 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Cognito.Stripe.Classes
{
public class FileUpload : BaseObject
{
public override string Object { get { return "file_upload"; } }
public string Purpose { get; set; }
public int Size { get; set; }
public string Type { get; set; }
public string URL { get; set; }
}
}
|
vc3/Cognito.Stripe
|
Cognito.Stripe/Classes/FileUpload.cs
|
C#
|
mit
| 377 |
class ChangeIntegerLimits < ActiveRecord::Migration
def change
change_column :projects, :federal_contribution, :integer, limit: 8
change_column :projects, :total_eligible_cost, :integer, limit: 8
end
end
|
anquinn/infrastructure_projects
|
db/migrate/20170513191438_change_integer_limits.rb
|
Ruby
|
mit
| 214 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright: (c) 2017, F5 Networks Inc.
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = r'''
---
module: bigiq_regkey_license_assignment
short_description: Manage regkey license assignment on BIG-IPs from a BIG-IQ
description:
- Manages the assignment of regkey licenses on a BIG-IQ. Assignment means
the license is assigned to a BIG-IP, or it needs to be assigned to a BIG-IP.
Additionally, this module supports revoking the assignments from BIG-IP devices.
version_added: "1.0.0"
options:
pool:
description:
- The registration key pool to use.
type: str
required: True
key:
description:
- The registration key you want to assign from the pool.
type: str
required: True
device:
description:
- When C(managed) is C(no), specifies the address, or hostname, where the BIG-IQ
can reach the remote device to register.
- When C(managed) is C(yes), specifies the managed device, or device UUID, that
you want to register.
- If C(managed) is C(yes), it is very important you do not have more than
one device with the same name. BIG-IQ internally recognizes devices by their ID,
and therefore, this module cannot guarantee the correct device will be
registered. The device returned is the device that is used.
type: str
required: True
managed:
description:
- Whether the specified device is a managed or un-managed device.
- When C(state) is C(present), this parameter is required.
type: bool
device_port:
description:
- Specifies the port of the remote device to connect to.
- If this parameter is not specified, the default is C(443).
type: int
default: 443
device_username:
description:
- The username used to connect to the remote device.
- This username should be one that has sufficient privileges on the remote device
to do licensing. Usually this is the C(Administrator) role.
- When C(managed) is C(no), this parameter is required.
type: str
device_password:
description:
- The password of the C(device_username).
- When C(managed) is C(no), this parameter is required.
type: str
state:
description:
- When C(present), ensures the device is assigned the specified license.
- When C(absent), ensures the license is revoked from the remote device and freed
on the BIG-IQ.
type: str
choices:
- present
- absent
default: present
extends_documentation_fragment: f5networks.f5_modules.f5
author:
- Tim Rupp (@caphrim007)
'''
EXAMPLES = r'''
- name: Register an unmanaged device
bigiq_regkey_license_assignment:
pool: my-regkey-pool
key: XXXX-XXXX-XXXX-XXXX-XXXX
device: 1.1.1.1
managed: no
device_username: admin
device_password: secret
state: present
provider:
user: admin
password: secret
server: lb.mydomain.com
delegate_to: localhost
- name: Register a managed device, by name
bigiq_regkey_license_assignment:
pool: my-regkey-pool
key: XXXX-XXXX-XXXX-XXXX-XXXX
device: bigi1.foo.com
managed: yes
state: present
provider:
user: admin
password: secret
server: lb.mydomain.com
delegate_to: localhost
- name: Register a managed device, by UUID
bigiq_regkey_license_assignment:
pool: my-regkey-pool
key: XXXX-XXXX-XXXX-XXXX-XXXX
device: 7141a063-7cf8-423f-9829-9d40599fa3e0
managed: yes
state: present
provider:
user: admin
password: secret
server: lb.mydomain.com
delegate_to: localhost
'''
RETURN = r'''
# only common fields returned
'''
import re
import time
from datetime import datetime
from ansible.module_utils.basic import AnsibleModule
from ..module_utils.bigip import F5RestClient
from ..module_utils.common import (
F5ModuleError, AnsibleF5Parameters, f5_argument_spec
)
from ..module_utils.icontrol import bigiq_version
from ..module_utils.ipaddress import is_valid_ip
from ..module_utils.teem import send_teem
class Parameters(AnsibleF5Parameters):
api_map = {
'deviceReference': 'device_reference',
'deviceAddress': 'device_address',
'httpsPort': 'device_port'
}
api_attributes = [
'deviceReference', 'deviceAddress', 'httpsPort', 'managed'
]
returnables = [
'device_address', 'device_reference', 'device_username', 'device_password',
'device_port', 'managed'
]
updatables = [
'device_reference', 'device_address', 'device_username', 'device_password',
'device_port', 'managed'
]
def to_return(self):
result = {}
try:
for returnable in self.returnables:
result[returnable] = getattr(self, returnable)
result = self._filter_params(result)
except Exception:
raise
return result
class ApiParameters(Parameters):
pass
class ModuleParameters(Parameters):
@property
def device_password(self):
if self._values['device_password'] is None:
return None
return self._values['device_password']
@property
def device_username(self):
if self._values['device_username'] is None:
return None
return self._values['device_username']
@property
def device_address(self):
if self.device_is_address:
return self._values['device']
@property
def device_port(self):
if self._values['device_port'] is None:
return None
return int(self._values['device_port'])
@property
def device_is_address(self):
if is_valid_ip(self.device):
return True
return False
@property
def device_is_id(self):
pattern = r'[A-Za-z0-9]{8}-[A-Za-z0-9]{4}-[A-Za-z0-9]{4}-[A-Za-z0-9]{4}-[A-Za-z0-9]{12}'
if re.match(pattern, self.device):
return True
return False
@property
def device_is_name(self):
if not self.device_is_address and not self.device_is_id:
return True
return False
@property
def device_reference(self):
if not self.managed:
return None
if self.device_is_address:
# This range lookup is how you do lookups for single IP addresses. Weird.
filter = "address+eq+'{0}...{0}'".format(self.device)
elif self.device_is_name:
filter = "hostname+eq+'{0}'".format(self.device)
elif self.device_is_id:
filter = "uuid+eq+'{0}'".format(self.device)
else:
raise F5ModuleError(
"Unknown device format '{0}'".format(self.device)
)
uri = "https://{0}:{1}/mgmt/shared/resolver/device-groups/cm-bigip-allBigIpDevices/devices/" \
"?$filter={2}&$top=1".format(self.client.provider['server'],
self.client.provider['server_port'], filter)
resp = self.client.api.get(uri)
try:
response = resp.json()
except ValueError as ex:
raise F5ModuleError(str(ex))
if resp.status == 200 and response['totalItems'] == 0:
raise F5ModuleError(
"No device with the specified address was found."
)
elif 'code' in response and response['code'] == 400:
if 'message' in response:
raise F5ModuleError(response['message'])
else:
raise F5ModuleError(resp._content)
id = response['items'][0]['uuid']
result = dict(
link='https://localhost/mgmt/shared/resolver/device-groups/cm-bigip-allBigIpDevices/devices/{0}'.format(id)
)
return result
@property
def pool_id(self):
filter = "(name%20eq%20'{0}')".format(self.pool)
uri = 'https://{0}:{1}/mgmt/cm/device/licensing/pool/regkey/licenses?$filter={2}&$top=1'.format(
self.client.provider['server'],
self.client.provider['server_port'],
filter
)
resp = self.client.api.get(uri)
try:
response = resp.json()
except ValueError as ex:
raise F5ModuleError(str(ex))
if resp.status == 200 and response['totalItems'] == 0:
raise F5ModuleError(
"No pool with the specified name was found."
)
elif 'code' in response and response['code'] == 400:
if 'message' in response:
raise F5ModuleError(response['message'])
else:
raise F5ModuleError(resp._content)
return response['items'][0]['id']
@property
def member_id(self):
if self.device_is_address:
# This range lookup is how you do lookups for single IP addresses. Weird.
filter = "deviceAddress+eq+'{0}...{0}'".format(self.device)
elif self.device_is_name:
filter = "deviceName+eq+'{0}'".format(self.device)
elif self.device_is_id:
filter = "deviceMachineId+eq+'{0}'".format(self.device)
else:
raise F5ModuleError(
"Unknown device format '{0}'".format(self.device)
)
uri = 'https://{0}:{1}/mgmt/cm/device/licensing/pool/regkey/licenses/{2}/offerings/{3}/members/' \
'?$filter={4}'.format(self.client.provider['server'], self.client.provider['server_port'],
self.pool_id, self.key, filter)
resp = self.client.api.get(uri)
try:
response = resp.json()
except ValueError as ex:
raise F5ModuleError(str(ex))
if resp.status == 200 and response['totalItems'] == 0:
return None
elif 'code' in response and response['code'] == 400:
if 'message' in response:
raise F5ModuleError(response['message'])
else:
raise F5ModuleError(resp._content)
result = response['items'][0]['id']
return result
class Changes(Parameters):
pass
class UsableChanges(Changes):
@property
def device_port(self):
if self._values['managed']:
return None
return self._values['device_port']
@property
def device_username(self):
if self._values['managed']:
return None
return self._values['device_username']
@property
def device_password(self):
if self._values['managed']:
return None
return self._values['device_password']
@property
def device_reference(self):
if not self._values['managed']:
return None
return self._values['device_reference']
@property
def device_address(self):
if self._values['managed']:
return None
return self._values['device_address']
@property
def managed(self):
return None
class ReportableChanges(Changes):
pass
class Difference(object):
def __init__(self, want, have=None):
self.want = want
self.have = have
def compare(self, param):
try:
result = getattr(self, param)
return result
except AttributeError:
return self.__default(param)
def __default(self, param):
attr1 = getattr(self.want, param)
try:
attr2 = getattr(self.have, param)
if attr1 != attr2:
return attr1
except AttributeError:
return attr1
class ModuleManager(object):
def __init__(self, *args, **kwargs):
self.module = kwargs.get('module', None)
self.client = F5RestClient(**self.module.params)
self.want = ModuleParameters(params=self.module.params, client=self.client)
self.have = ApiParameters()
self.changes = UsableChanges()
def _set_changed_options(self):
changed = {}
for key in Parameters.returnables:
if getattr(self.want, key) is not None:
changed[key] = getattr(self.want, key)
if changed:
self.changes = UsableChanges(params=changed)
def _update_changed_options(self):
diff = Difference(self.want, self.have)
updatables = Parameters.updatables
changed = dict()
for k in updatables:
change = diff.compare(k)
if change is None:
continue
else:
if isinstance(change, dict):
changed.update(change)
else:
changed[k] = change
if changed:
self.changes = UsableChanges(params=changed)
return True
return False
def should_update(self):
result = self._update_changed_options()
if result:
return True
return False
def exec_module(self):
start = datetime.now().isoformat()
version = bigiq_version(self.client)
changed = False
result = dict()
state = self.want.state
if state == "present":
changed = self.present()
elif state == "absent":
changed = self.absent()
reportable = ReportableChanges(params=self.changes.to_return())
changes = reportable.to_return()
result.update(**changes)
result.update(dict(changed=changed))
self._announce_deprecations(result)
send_teem(start, self.module, version)
return result
def _announce_deprecations(self, result):
warnings = result.pop('__warnings', [])
for warning in warnings:
self.module.deprecate(
msg=warning['msg'],
version=warning['version']
)
def present(self):
if self.exists():
return False
return self.create()
def exists(self):
if self.want.member_id is None:
return False
uri = 'https://{0}:{1}/mgmt/cm/device/licensing/pool/regkey/licenses/{2}/offerings/{3}/members/{4}'.format(
self.client.provider['server'],
self.client.provider['server_port'],
self.want.pool_id,
self.want.key,
self.want.member_id
)
resp = self.client.api.get(uri)
if resp.status == 200:
return True
return False
def remove(self):
self._set_changed_options()
if self.module.check_mode:
return True
self.remove_from_device()
if self.exists():
raise F5ModuleError("Failed to delete the resource.")
# Artificial sleeping to wait for remote licensing (on BIG-IP) to complete
#
# This should be something that BIG-IQ can do natively in 6.1-ish time.
time.sleep(60)
return True
def create(self):
self._set_changed_options()
if not self.want.managed:
if self.want.device_username is None:
raise F5ModuleError(
"You must specify a 'device_username' when working with unmanaged devices."
)
if self.want.device_password is None:
raise F5ModuleError(
"You must specify a 'device_password' when working with unmanaged devices."
)
if self.module.check_mode:
return True
self.create_on_device()
if not self.exists():
raise F5ModuleError(
"Failed to license the remote device."
)
self.wait_for_device_to_be_licensed()
# Artificial sleeping to wait for remote licensing (on BIG-IP) to complete
#
# This should be something that BIG-IQ can do natively in 6.1-ish time.
time.sleep(60)
return True
def create_on_device(self):
params = self.changes.api_params()
uri = 'https://{0}:{1}/mgmt/cm/device/licensing/pool/regkey/licenses/{2}/offerings/{3}/members/'.format(
self.client.provider['server'],
self.client.provider['server_port'],
self.want.pool_id,
self.want.key
)
if not self.want.managed:
params['username'] = self.want.device_username
params['password'] = self.want.device_password
resp = self.client.api.post(uri, json=params)
try:
response = resp.json()
except ValueError as ex:
raise F5ModuleError(str(ex))
if 'code' in response and response['code'] == 400:
if 'message' in response:
raise F5ModuleError(response['message'])
else:
raise F5ModuleError(resp.content)
def wait_for_device_to_be_licensed(self):
count = 0
uri = 'https://{0}:{1}/mgmt/cm/device/licensing/pool/regkey/licenses/{2}/offerings/{3}/members/{4}'.format(
self.client.provider['server'],
self.client.provider['server_port'],
self.want.pool_id,
self.want.key,
self.want.member_id
)
while count < 3:
resp = self.client.api.get(uri)
try:
response = resp.json()
except ValueError as ex:
raise F5ModuleError(str(ex))
if 'code' in response and response['code'] == 400:
if 'message' in response:
raise F5ModuleError(response['message'])
else:
raise F5ModuleError(resp.content)
if response['status'] == 'LICENSED':
count += 1
else:
count = 0
def absent(self):
if self.exists():
return self.remove()
return False
def remove_from_device(self):
uri = 'https://{0}:{1}/mgmt/cm/device/licensing/pool/regkey/licenses/{2}/offerings/{3}/members/{4}'.format(
self.client.provider['server'],
self.client.provider['server_port'],
self.want.pool_id,
self.want.key,
self.want.member_id
)
params = {}
if not self.want.managed:
params.update(self.changes.api_params())
params['id'] = self.want.member_id
params['username'] = self.want.device_username
params['password'] = self.want.device_password
self.client.api.delete(uri, json=params)
class ArgumentSpec(object):
def __init__(self):
self.supports_check_mode = True
argument_spec = dict(
pool=dict(required=True),
key=dict(required=True, no_log=True),
device=dict(required=True),
managed=dict(type='bool'),
device_port=dict(type='int', default=443),
device_username=dict(no_log=True),
device_password=dict(no_log=True),
state=dict(default='present', choices=['absent', 'present'])
)
self.argument_spec = {}
self.argument_spec.update(f5_argument_spec)
self.argument_spec.update(argument_spec)
self.required_if = [
['state', 'present', ['key', 'managed']],
['managed', False, ['device', 'device_username', 'device_password']],
['managed', True, ['device']]
]
def main():
spec = ArgumentSpec()
module = AnsibleModule(
argument_spec=spec.argument_spec,
supports_check_mode=spec.supports_check_mode,
required_if=spec.required_if
)
try:
mm = ModuleManager(module=module)
results = mm.exec_module()
module.exit_json(**results)
except F5ModuleError as ex:
module.fail_json(msg=str(ex))
if __name__ == '__main__':
main()
|
F5Networks/f5-ansible-modules
|
ansible_collections/f5networks/f5_modules/plugins/modules/bigiq_regkey_license_assignment.py
|
Python
|
mit
| 19,962 |
<?php
/**
*
* @author thiago
*/
interface ConsoleFactory {
public function create_console_microsoft();
public function create_console_sony();
}
|
thiagorthomaz/design-patterns
|
abstractFactory/ConsoleFactory.class.php
|
PHP
|
mit
| 153 |
class ApplicationController < Sinatra::Base
require 'bundler'
Bundler.require
end
|
timrourke/dotEnv
|
controllers/_ApplicationController.rb
|
Ruby
|
mit
| 84 |
// JSON Object of all of the icons and their tags
export default {
apple : {
name : 'apple',
color: '#be0000',
image : 'apple67.svg',
tags: ['apple', 'fruit', 'food'],
categories: ['food', 'supermarket']
},
bread : {
name : 'bread',
color: '#c26b24',
image : 'bread14.svg',
tags: ['bread', 'food', 'wheat', 'bake'],
categories: ['food', 'supermarket']
},
broccoli : {
name : 'broccoli',
color: '#16a900',
image : 'broccoli.svg',
tags: ['broccoli', 'food', 'vegetable'],
categories: ['food', 'supermarket']
},
cheese : {
name : 'cheese',
color: '#ffe625',
image : 'cheese7.svg',
tags: ['cheese', 'food', 'dairy'],
categories: ['food', 'supermarket']
},
shopping : {
name : 'shopping',
color: '#f32393',
image : 'shopping225.svg',
tags: ['shopping', 'bag'],
categories: ['shopping', 'supermarket']
},
cart : {
name : 'cart',
color: '#9ba990',
image : 'supermarket1.svg',
tags: ['cart', 'shopping'],
categories: ['shopping', 'supermarket']
},
fish : {
name : 'fish',
color: '#6d7ca9',
image : 'fish52.svg',
tags: ['fish', 'food'],
categories: ['fish', 'supermarket']
},
giftbox : {
name : 'giftbox',
color: '#f32393',
image : 'giftbox56.svg',
tags: ['giftbox', 'gift', 'present'],
categories: ['gift', 'shopping', 'supermarket']
}
};
|
una/heiroglyph
|
app/js/data/iconListInfo.js
|
JavaScript
|
mit
| 1,423 |
package sudoku
import "fmt"
const (
n = 3
N = 3 * 3
)
var (
resolved bool
)
func solveSudoku(board [][]byte) [][]byte {
// box size 3
row := make([][]int, N)
columns := make([][]int, N)
box := make([][]int, N)
res := make([][]byte, N)
for i := 0; i < N; i++ {
row[i] = make([]int, N+1)
columns[i] = make([]int, N+1)
box[i] = make([]int, N+1)
res[i] = make([]byte, N)
copy(res[i], board[i])
}
for i := 0; i < N; i++ {
for j := 0; j < N; j++ {
if board[i][j] != '.' {
placeNumberAtPos(res, i, j, int(board[i][j]-'0'), row, columns, box)
}
}
}
fmt.Printf("row: %v\n, column: %v\n, box: %v\n", row, columns, box)
permute(res, 0, 0, row, columns, box)
return res
}
func placeNumberAtPos(board [][]byte, i, j, num int, row, columns, box [][]int) {
boxIdx := (i/n)*n + j/n
(row)[i][num]++
(columns)[j][num]++
(box)[boxIdx][num]++
(board)[i][j] = byte('0' + num)
}
func removeNumberAtPos(board [][]byte, i, j, num int, row, columns, box [][]int) {
boxIdx := (i/n)*n + j/n
row[i][num]++
columns[j][num]++
box[boxIdx][num]++
board[i][j] = '.'
}
func isValidPosForNum(i, j, num int, row, columns, box [][]int) bool {
boxIdx := (i/n)*n + j/n
return row[i][num]+columns[j][num]+box[boxIdx][num] == 0
}
func permute(board [][]byte, i, j int, row, column, box [][]int) {
if board[i][j] == '.' {
for k := 1; k <= N; k++ {
if isValidPosForNum(i, j, k, row, column, box) {
placeNumberAtPos(board, i, j, k, row, column, box)
fmt.Printf("place k:%d at row: %d and col:%d, row[i][k]= %d, col[j][k] = %d and box[boxidx][k] = %d\n", k, i, j, row[i][k], column[j][k],
box[(i/n)*n+j/n][k])
placeNext(board, i, j, row, column, box)
fmt.Printf("place next then k:%d at row: %d and col:%d, row[i][k]= %d, col[j][k] = %d and box[boxidx][k] = %d\n", k, i, j, row[i][k], column[j][k],
box[(i/n)*n+j/n][k])
if !resolved {
removeNumberAtPos(board, i, j, k, row, column, box)
}
}
}
} else {
placeNext(board, i, j, row, column, box)
}
}
func placeNext(board [][]byte, i, j int, row, column, box [][]int) {
if i == N-1 && j == N-1 {
resolved = true
}
fmt.Printf("board: %v\n, row: %v \n, column: %v\n, box: %v\n", board, row, column, box)
if j == N-1 {
fmt.Println("next row")
permute(board, i+1, 0, row, column, box)
} else {
fmt.Println("next column")
permute(board, i, j+1, row, column, box)
}
}
func solveSudoku2(board [][]byte) [][]byte {
if len(board) == 0 {
return board
}
solve(board)
return board
}
func solve(board [][]byte) bool {
var c byte
for i := 0; i < len(board); i++ {
for j := 0; j < len(board[0]); j++ {
if board[i][j] == '.' {
for c = '1'; c <= '9'; c++ {
if isValid(board, i, j, c) {
board[i][j] = c
if solve(board) {
return true
} else {
board[i][j] = '.'
}
}
}
return false
}
}
}
return true
}
func isValid(board [][]byte, row int, col int, c byte) bool {
for i := 0; i < 9; i++ {
if board[i][col] != '.' && board[i][col] == c {
return false
}
if board[row][i] != '.' && board[row][i] == c {
return false
}
if board[3*(row/3)+i/3][3*(col/3)+i%3] != '.' && board[3*(row/3)+i/3][3*(col/3)+i%3] == c {
return false
}
}
return true
}
|
Catorpilor/LeetCode
|
37_sudoku_solver/sudoku.go
|
GO
|
mit
| 3,258 |
#include "Fractal.h"
Color::Color() : r(0.0), g(0.0), b(0.0) {}
Color::Color(double rin, double gin, double bin) : r(rin), g(gin), b(bin) {}
Fractal::Fractal(int width, int height)
: width_(width), height_(height), center_x_(0.0), center_y_(0.0),
max_distance_sqr_(4.0), max_iteration_(32) {
pixel_size_ = 4.0 / width_;
}
Fractal::~Fractal() {}
void Fractal::Initialize() {
RecalcMins();
CreateColors();
CalculateEscapeTime();
}
void Fractal::CreateColors() {
int i;
double r, g, b;
colors_.resize(max_iteration_ + 1);
for (i = 0; i < max_iteration_; i++) {
r = 1.0 * i / (double) max_iteration_;
g = 0.5 * i / (double) max_iteration_;
b = 1.0 * i / (double) max_iteration_;
colors_[i] = Color(r, g, b);
}
colors_[max_iteration_] = Color(0.0, 0.0, 0.0);
}
void Fractal::CalculateEscapeTime() {
int i, j;
double x, y, xmin, ymin;
xmin = center_x_ - pixel_size_ * (width_ / 2.0 - 0.5);
ymin = center_y_ - pixel_size_ * (height_ / 2.0 - 0.5);
escape_times_.resize(height_);
for (j = 0; j < height_; j++) {
escape_times_[j].resize(width_);
for (i = 0; i < width_; i++) {
x = xmin + i * pixel_size_;
y = ymin + j * pixel_size_;
escape_times_[j][i] = EscapeOne(x, y);
}
}
}
void Fractal::Draw() {
int x, y, iter;
for (y = 0; y < height_; y++) {
for (x = 0; x < width_; x++) {
iter = escape_times_[y][x];
glColor3d(colors_[iter].r, colors_[iter].g, colors_[iter].b);
glBegin(GL_POINTS);
glVertex2d(x, y);
glEnd();
}
}
}
void Fractal::Center(double x, double y) {
RecalcCenter(x, y);
RecalcMins();
CalculateEscapeTime();
}
void Fractal::ZoomIn(double x, double y) {
RecalcCenter(x, y);
pixel_size_ /= 2.0;
RecalcMins();
CalculateEscapeTime();
}
void Fractal::ZoomOut(double x, double y) {
RecalcCenter(x, y);
pixel_size_ *= 2.0;
RecalcMins();
CalculateEscapeTime();
}
void Fractal::RecalcCenter(double x, double y) {
center_x_ = min_x_ + pixel_size_ * x;
center_y_ = min_y_ + pixel_size_ * y;
}
void Fractal::RecalcMins() {
min_x_ = center_x_ - pixel_size_ * (width_ / 2.0 - 0.5);
min_y_ = center_y_ - pixel_size_ * (height_ / 2.0 - 0.5);
}
|
theDrake/opengl-experiments
|
Fractals/Fractals/Fractal.cpp
|
C++
|
mit
| 2,212 |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using Mechanical3.Core;
namespace Mechanical3.IO.FileSystems
{
//// NOTE: For still more speed, you could ditch abstract file systems, file paths and streams alltogether, and just use byte arrays directly.
//// Obviously this is a compromize between performance and ease of use.
/// <summary>
/// Provides performant, semi thread-safe access to an in-memory copy of the contants of an <see cref="IFileSystemReader"/>.
/// Access to <see cref="IFileSystemReader"/> members is thread-safe.
/// <see cref="Stream"/> instances returned are NOT thread-safe, and they must not be used after they are closed or disposed (one of which should happen exactly one time).
/// </summary>
public class SemiThreadSafeMemoryFileSystemReader : IFileSystemReader
{
#region ByteArrayReaderStream
/// <summary>
/// Provides thread-safe, read-only access to the wrapped byte array.
/// </summary>
private class ByteArrayReaderStream : Stream
{
//// NOTE: the default asynchronous implementations call their synchronous versions.
//// NOTE: we don't use Store*, to save a few allocations
#region ObjectPool
internal static class ObjectPool
{
private static readonly ConcurrentBag<ByteArrayReaderStream> Pool = new ConcurrentBag<ByteArrayReaderStream>();
internal static ByteArrayReaderStream Get( byte[] data )
{
ByteArrayReaderStream stream;
if( !Pool.TryTake(out stream) )
stream = new ByteArrayReaderStream();
stream.OnInitialize(data);
return stream;
}
internal static void Put( ByteArrayReaderStream stream )
{
Pool.Add(stream);
}
internal static void Clear()
{
ByteArrayReaderStream stream;
while( true )
{
if( Pool.TryTake(out stream) )
GC.SuppressFinalize(stream);
else
break; // pool is empty
}
}
}
#endregion
#region Private Fields
private byte[] array;
private int position; // NOTE: (position == length) == EOF
private bool isOpen;
#endregion
#region Constructor
private ByteArrayReaderStream()
: base()
{
}
#endregion
#region Private Methods
private void OnInitialize( byte[] data )
{
this.array = data;
this.position = 0;
this.isOpen = true;
}
private void OnClose()
{
this.isOpen = false;
this.array = null;
this.position = -1;
}
private void ThrowIfClosed()
{
if( !this.isOpen )
throw new ObjectDisposedException(message: "The stream was already closed!", innerException: null);
}
#endregion
#region Stream
protected override void Dispose( bool disposing )
{
this.OnClose();
ObjectPool.Put(this);
if( !disposing )
{
// called from finalizer
GC.ReRegisterForFinalize(this);
}
}
public override bool CanRead
{
get
{
this.ThrowIfClosed();
return true;
}
}
public override bool CanSeek
{
get
{
this.ThrowIfClosed();
return true;
}
}
public override bool CanTimeout
{
get
{
this.ThrowIfClosed();
return false;
}
}
public override bool CanWrite
{
get
{
this.ThrowIfClosed();
return false;
}
}
public override long Length
{
get
{
this.ThrowIfClosed();
return this.array.Length;
}
}
public override long Position
{
get
{
this.ThrowIfClosed();
return this.position;
}
set
{
this.ThrowIfClosed();
if( value < 0 || this.array.Length < value )
throw new ArgumentOutOfRangeException();
this.position = (int)value;
}
}
public override long Seek( long offset, SeekOrigin origin )
{
this.ThrowIfClosed();
int newPosition;
switch( origin )
{
case SeekOrigin.Begin:
newPosition = (int)offset;
break;
case SeekOrigin.Current:
newPosition = this.position + (int)offset;
break;
case SeekOrigin.End:
newPosition = this.array.Length + (int)offset;
break;
default:
throw new ArgumentException("Invalid SeekOrigin!");
}
if( newPosition < 0
|| newPosition > this.array.Length )
throw new ArgumentOutOfRangeException();
this.position = newPosition;
return this.position;
}
public override int ReadByte()
{
this.ThrowIfClosed();
if( this.position == this.array.Length )
{
// end of stream
return -1;
}
else
{
return this.array[this.position++];
}
}
public override int Read( byte[] buffer, int offset, int bytesToRead )
{
this.ThrowIfClosed();
int bytesLeft = this.array.Length - this.position;
if( bytesLeft < bytesToRead ) bytesToRead = bytesLeft;
if( bytesToRead == 0 )
return 0;
Buffer.BlockCopy(src: this.array, srcOffset: this.position, dst: buffer, dstOffset: offset, count: bytesToRead);
this.position += bytesToRead;
return bytesToRead;
}
public override void Flush()
{
throw new NotSupportedException();
}
public override void SetLength( long value )
{
throw new NotSupportedException();
}
public override void WriteByte( byte value )
{
throw new NotSupportedException();
}
public override void Write( byte[] buffer, int offset, int count )
{
throw new NotSupportedException();
}
#endregion
}
#endregion
#region Private Fields
/* From MSDN:
* A Dictionary can support multiple readers concurrently, as long as the collection is not modified.
* Even so, enumerating through a collection is intrinsically not a thread-safe procedure. In the
* rare case where an enumeration contends with write accesses, the collection must be locked during
* the entire enumeration. To allow the collection to be accessed by multiple threads for reading
* and writing, you must implement your own synchronization.
*
* ... (or there is also ConcurrentDictionary)
*/
//// NOTE: since after they are filled, the dictionaries won't be modified, we are fine.
private readonly FilePath[] rootFolderEntries;
private readonly Dictionary<FilePath, FilePath[]> nonRootFolderEntries;
private readonly Dictionary<FilePath, byte[]> fileContents;
private readonly Dictionary<FilePath, string> hostPaths;
private readonly string rootHostPath;
#endregion
#region Constructors
/// <summary>
/// Copies the current contents of the specified <see cref="IFileSystemReader"/>
/// into a new <see cref="SemiThreadSafeMemoryFileSystemReader"/> instance.
/// </summary>
/// <param name="readerToCopy">The abstract file system to copy the current contents of, into memory.</param>
/// <returns>A new <see cref="SemiThreadSafeMemoryFileSystemReader"/> instance.</returns>
public static SemiThreadSafeMemoryFileSystemReader CopyFrom( IFileSystemReader readerToCopy )
{
return new SemiThreadSafeMemoryFileSystemReader(readerToCopy);
}
/// <summary>
/// Initializes a new instance of the <see cref="SemiThreadSafeMemoryFileSystemReader"/> class.
/// </summary>
/// <param name="readerToCopy">The abstract file system to copy the current contents of, into memory.</param>
private SemiThreadSafeMemoryFileSystemReader( IFileSystemReader readerToCopy )
{
this.rootFolderEntries = readerToCopy.GetPaths();
this.nonRootFolderEntries = new Dictionary<FilePath, FilePath[]>();
this.fileContents = new Dictionary<FilePath, byte[]>();
if( readerToCopy.SupportsToHostPath )
{
this.hostPaths = new Dictionary<FilePath, string>();
this.rootHostPath = readerToCopy.ToHostPath(null);
}
using( var tmpStream = new MemoryStream() )
{
foreach( var e in this.rootFolderEntries )
this.AddRecursively(e, readerToCopy, tmpStream);
}
}
#endregion
#region Private Methods
private void AddRecursively( FilePath entry, IFileSystemReader readerToCopy, MemoryStream tmpStream )
{
if( entry.IsDirectory )
{
var subEntries = readerToCopy.GetPaths(entry);
this.nonRootFolderEntries.Add(entry, subEntries);
foreach( var e in subEntries )
this.AddRecursively(e, readerToCopy, tmpStream);
}
else
{
this.fileContents.Add(entry, ReadFileContents(entry, readerToCopy, tmpStream));
}
if( this.SupportsToHostPath )
this.hostPaths.Add(entry, readerToCopy.ToHostPath(entry));
}
private static byte[] ReadFileContents( FilePath filePath, IFileSystemReader readerToCopy, MemoryStream tmpStream )
{
tmpStream.SetLength(0);
long? fileSize = null;
if( readerToCopy.SupportsGetFileSize )
{
fileSize = readerToCopy.GetFileSize(filePath);
ThrowIfFileTooBig(filePath, fileSize.Value);
}
using( var stream = readerToCopy.ReadFile(filePath) )
{
if( !fileSize.HasValue
&& stream.CanSeek )
{
fileSize = stream.Length;
ThrowIfFileTooBig(filePath, fileSize.Value);
}
stream.CopyTo(tmpStream);
if( !fileSize.HasValue )
ThrowIfFileTooBig(filePath, tmpStream.Length);
return tmpStream.ToArray();
}
}
private static void ThrowIfFileTooBig( FilePath filePath, long fileSize )
{
if( fileSize > int.MaxValue ) // that's the largest our stream implementation can support
throw new Exception("One of the files is too large!").Store(nameof(filePath), filePath).Store(nameof(fileSize), fileSize);
}
#endregion
#region IFileSystemBase
/// <summary>
/// Gets a value indicating whether the ToHostPath method is supported.
/// </summary>
/// <value><c>true</c> if the method is supported; otherwise, <c>false</c>.</value>
public bool SupportsToHostPath
{
get { return this.hostPaths.NotNullReference(); }
}
/// <summary>
/// Gets the string the underlying system uses to represent the specified file or directory.
/// </summary>
/// <param name="path">The path to the file or directory.</param>
/// <returns>The string the underlying system uses to represent the specified <paramref name="path"/>.</returns>
public string ToHostPath( FilePath path )
{
if( !this.SupportsToHostPath )
throw new NotSupportedException().StoreFileLine();
if( path.NullReference() )
return this.rootHostPath;
string result;
if( this.hostPaths.TryGetValue(path, out result) )
return result;
else
throw new FileNotFoundException("The specified file or directory was not found!").Store(nameof(path), path);
}
#endregion
#region IFileSystemReader
/// <summary>
/// Gets the paths to the direct children of the specified directory.
/// Subdirectories are not searched.
/// </summary>
/// <param name="directoryPath">The path specifying the directory to list the direct children of; or <c>null</c> to specify the root of this file system.</param>
/// <returns>The paths of the files and directories found.</returns>
public FilePath[] GetPaths( FilePath directoryPath = null )
{
if( directoryPath.NotNullReference()
&& !directoryPath.IsDirectory )
throw new ArgumentException("Argument is not a directory!").Store(nameof(directoryPath), directoryPath);
FilePath[] paths;
if( directoryPath.NullReference() )
{
paths = this.rootFolderEntries;
}
else
{
if( !this.nonRootFolderEntries.TryGetValue(directoryPath, out paths) )
throw new FileNotFoundException("The specified file or directory was not found!").Store(nameof(directoryPath), directoryPath);
}
// NOTE: Unfortunately we need to make a copy, since arrays are writable.
// TODO: return ImmutableArray from GetPaths.
var copy = new FilePath[paths.Length];
Array.Copy(sourceArray: paths, destinationArray: copy, length: paths.Length);
return copy;
}
/// <summary>
/// Opens the specified file for reading.
/// </summary>
/// <param name="filePath">The path specifying the file to open.</param>
/// <returns>A <see cref="Stream"/> representing the file opened.</returns>
public Stream ReadFile( FilePath filePath )
{
if( filePath.NullReference()
|| filePath.IsDirectory )
throw new ArgumentException("Argument is not a file!").Store(nameof(filePath), filePath);
byte[] bytes;
if( !this.fileContents.TryGetValue(filePath, out bytes) )
throw new FileNotFoundException("The specified file or directory was not found!").Store(nameof(filePath), filePath);
return ByteArrayReaderStream.ObjectPool.Get(bytes);
}
/// <summary>
/// Gets a value indicating whether the GetFileSize method is supported.
/// </summary>
/// <value><c>true</c> if the method is supported; otherwise, <c>false</c>.</value>
public bool SupportsGetFileSize
{
get { return true; }
}
/// <summary>
/// Gets the size, in bytes, of the specified file.
/// </summary>
/// <param name="filePath">The file to get the size of.</param>
/// <returns>The size of the specified file in bytes.</returns>
public long GetFileSize( FilePath filePath )
{
if( filePath.NullReference()
|| filePath.IsDirectory )
throw new ArgumentException("Argument is not a file!").Store(nameof(filePath), filePath);
byte[] bytes;
if( !this.fileContents.TryGetValue(filePath, out bytes) )
throw new FileNotFoundException("The specified file or directory was not found!").Store(nameof(filePath), filePath);
return bytes.Length;
}
#endregion
}
}
|
MechanicalMen/Mechanical3
|
source/Mechanical3.Portable/IO/FileSystems/SemiThreadSafeMemoryFileSystemReader.cs
|
C#
|
mit
| 17,319 |
http_path = "/"
css_dir = "assets/css/src"
sass_dir = "assets/sass"
images_dir = "assets/img"
javascripts_dir = "assets/js"
fonts_dir = "assets/font"
http_fonts_path = "assets/font"
http_images_path = "assets/img"
output_style = :nested
relative_assets = false
line_comments = false
|
LunneMarketingGroup/Grunt-Website-Template
|
config.rb
|
Ruby
|
mit
| 323 |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.network.v2020_04_01;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Contains SKU in an ExpressRouteCircuit.
*/
public class ExpressRouteCircuitSku {
/**
* The name of the SKU.
*/
@JsonProperty(value = "name")
private String name;
/**
* The tier of the SKU. Possible values include: 'Standard', 'Premium',
* 'Basic', 'Local'.
*/
@JsonProperty(value = "tier")
private ExpressRouteCircuitSkuTier tier;
/**
* The family of the SKU. Possible values include: 'UnlimitedData',
* 'MeteredData'.
*/
@JsonProperty(value = "family")
private ExpressRouteCircuitSkuFamily family;
/**
* Get the name of the SKU.
*
* @return the name value
*/
public String name() {
return this.name;
}
/**
* Set the name of the SKU.
*
* @param name the name value to set
* @return the ExpressRouteCircuitSku object itself.
*/
public ExpressRouteCircuitSku withName(String name) {
this.name = name;
return this;
}
/**
* Get the tier of the SKU. Possible values include: 'Standard', 'Premium', 'Basic', 'Local'.
*
* @return the tier value
*/
public ExpressRouteCircuitSkuTier tier() {
return this.tier;
}
/**
* Set the tier of the SKU. Possible values include: 'Standard', 'Premium', 'Basic', 'Local'.
*
* @param tier the tier value to set
* @return the ExpressRouteCircuitSku object itself.
*/
public ExpressRouteCircuitSku withTier(ExpressRouteCircuitSkuTier tier) {
this.tier = tier;
return this;
}
/**
* Get the family of the SKU. Possible values include: 'UnlimitedData', 'MeteredData'.
*
* @return the family value
*/
public ExpressRouteCircuitSkuFamily family() {
return this.family;
}
/**
* Set the family of the SKU. Possible values include: 'UnlimitedData', 'MeteredData'.
*
* @param family the family value to set
* @return the ExpressRouteCircuitSku object itself.
*/
public ExpressRouteCircuitSku withFamily(ExpressRouteCircuitSkuFamily family) {
this.family = family;
return this;
}
}
|
selvasingh/azure-sdk-for-java
|
sdk/network/mgmt-v2020_04_01/src/main/java/com/microsoft/azure/management/network/v2020_04_01/ExpressRouteCircuitSku.java
|
Java
|
mit
| 2,518 |
class JudgePolicy < ApplicationPolicy
def create_scores?
record.competition.unlocked? && (user_match? || director?(record.event) || super_admin?)
end
def view_scores?
(user_match? || director?(record.event) || super_admin?)
end
def index?
director?(record.event) || super_admin?
end
def toggle_status?
director?(record.event) || super_admin?
end
def create?
update?
end
def update?
record.scores.count.zero? && record.competition.unlocked? && (director?(record.event) || super_admin?)
end
def destroy?
update?
end
def can_judge?
record.competition.unlocked? && (user_match? || director?(record.event) || super_admin?)
end
private
def user_match?
record.user == user
end
class Scope < Scope
def resolve
scope.none
end
end
end
|
rdunlop/unicycling-registration
|
app/policies/judge_policy.rb
|
Ruby
|
mit
| 827 |
const Nodelist = artifacts.require("./Nodelist.sol");
const BiathlonNode = artifacts.require("./BiathlonNode.sol");
const SecondNode = artifacts.require("./SecondNode.sol");
const BiathlonToken = artifacts.require("./BiathlonToken.sol");
const Ownable = artifacts.require('../contracts/ownership/Ownable.sol');
// const MintableToken = artifacts.require('MintableToken.sol');
const SecondBiathlonToken = artifacts.require("./SecondBiathlonToken.sol");
let nl;
let bn;
let bt;
let sn;
let st;
contract('BiathlonToken', function(accounts) {
beforeEach(async function() {
bn = await BiathlonNode.deployed();
nl = await Nodelist.deployed();
bt = await BiathlonToken.deployed();
st = await SecondBiathlonToken.deployed();
sn = await SecondNode.deployed();
});
it('should have an owner', async function() {
let owner = await bt.owner();
assert.isTrue(owner !== 0);
});
it('should belong to the correct node', async function() {
let node = await bt.node_address();
let bna = await bn.address;
assert.equal(node, bna, "Token was not initialised to correct node");
});
it('should have a storage contract that is separate', async function() {
let storage_address = await bt.storage_address();
assert.notEqual(storage_address, bt.address);
});
it("should be able to register itself with the Node list of tokens", async function() {
let registration = await bt.register_with_node();
let node_token_count = await bn.count_tokens();
assert.equal(node_token_count, 1, "Node array of tokens doesn't have deployed BiathlonToken");
});
it('should mint a given amount of tokens to a given address', async function() {
const result = await bt.mint(accounts[0], 100, { from: accounts[0] });
assert.equal(result.logs[0].event, 'Mint');
assert.equal(result.logs[0].args.to.valueOf(), accounts[0]);
assert.equal(result.logs[0].args.amount.valueOf(), 100);
assert.equal(result.logs[1].event, 'Transfer');
assert.equal(result.logs[1].args.from.valueOf(), 0x0);
let balance0 = await bt.balanceOf(accounts[0]);
assert(balance0 == 100);
let totalSupply = await bt.totalSupply();
assert.equal(totalSupply, 100);
})
it('should allow owner to mint 50 to account #2', async function() {
let result = await bt.mint(accounts[2], 50);
assert.equal(result.logs[0].event, 'Mint');
assert.equal(result.logs[0].args.to.valueOf(), accounts[2]);
assert.equal(result.logs[0].args.amount.valueOf(), 50);
assert.equal(result.logs[1].event, 'Transfer');
assert.equal(result.logs[1].args.from.valueOf(), 0x0);
let new_balance = await bt.balanceOf(accounts[2]);
assert.equal(new_balance, 50, 'Owner could not mint 50 to account #2');
});
it('should have account #2 on registry after first token minting', async function() {
let check_user = await nl.users(accounts[2]);
assert.equal(check_user, bn.address);
});
it('should spend 25 of the tokens minted to account #2', async function() {
let result = await bt.spend(accounts[2], 25);
assert.equal(result.logs[0].event, 'Burn');
let new_balance = await bt.balanceOf(accounts[2]);
assert.equal(new_balance, 25);
});
it('should have total supply changed by these minting and spending operations', async function() {
let result = await bt.totalSupply();
assert.equal(result, 125);
});
it('should not allow non-onwers to spend', async function() {
try {
let spendtask = await bt.spend(accounts[0], 1, {from: accounts[2]})
} catch (error) {
const invalidJump = error.message.search('invalid opcode') >= 0;
assert(invalidJump, "Expected throw, got '" + error + "' instead");
return;
}
assert.fail("Expected to reject spending from non-owner");
});
it('should not allow non-owners to mint', async function() {
try {
let minttask = await bt.mint(accounts[2], 50, {from: accounts[1]});
} catch (error) {
const invalidJump = error.message.search('invalid opcode') >= 0;
assert(invalidJump, "Expected throw, got '" + error + "' instead");
return;
}
assert.fail("Expected to reject minting from non-owner");
});
it('should not be able to spend more than it has', async function() {
try {
let spendtask = await bt.spend(accounts[2], 66)
} catch (error) {
const invalidJump = error.message.search('invalid opcode') >= 0;
assert(invalidJump, "Expected throw, got '" + error + "' instead");
return;
}
assert.fail("Expected to reject spending more than limit");
});
it('second deployed token should belong to the correct node', async function() {
let node = await st.node_address();
let bna = await bn.address;
assert.equal(node, bna, "Token was not initialised to correct node");
});
it('second token should be able to upgrade the token with the node', async function() {
let name = await st.name();
const upgraded = await bn.upgrade_token(bt.address, st.address, name);
assert.equal(upgraded.logs[0].event, 'UpgradeToken');
let count_of_tokens = await bn.count_tokens();
assert.equal(count_of_tokens, 1, 'Should only be one token in tokenlist still');
});
it('should deactivate original token after upgrade', async function () {
let tia = await bn.tokens.call(bt.address);
assert.isNotTrue(tia[1]);
let newtoken = await bn.tokens.call(st.address);
assert.isTrue(newtoken[1]);
});
it('should carry over the previous balances since storage contract is fixed', async function() {
let get_balance = await st.balanceOf(accounts[2]);
assert.equal(get_balance, 25);
});
it('should not allow the deactivated contract to mint', async function() {
try {
let newmint = await bt.mint(accounts[2], 10);
} catch(error) {
const invalidJump = error.message.search('invalid opcode') >= 0;
assert(invalidJump, "Expected throw, got '" + error + "' instead");
return;
}
assert.fail("Expected to reject spending more than limit");
});
it('should allow minting more tokens to accounts', async function() {
let newmint = await st.mint(accounts[2], 3);
let getbalance = await st.balanceOf(accounts[2]);
let totalsupply = await st.totalSupply();
assert.equal(totalsupply, 128);
assert.equal(getbalance, 28);
});
it('should be able to transfer as contract owner from one account to another', async function() {
let thetransfer = await st.biathlon_transfer(accounts[2], accounts[3], 2);
let getbalance2 = await st.balanceOf(accounts[2]);
let getbalance3 = await st.balanceOf(accounts[3]);
assert.equal(getbalance2, 26);
assert.equal(getbalance3, 2);
});
it('should not be able to transfer as non-owner from one account to another', async function() {
try {
let thetransfer = await st.biathlon_transfer(accounts[3], accounts[4], 1, {from: accounts[1]});
} catch(error) {
const invalidJump = error.message.search('invalid opcode') >= 0;
assert(invalidJump, "Expected throw, got '" + error + "' instead");
return;
}
assert.fail("Expected to reject transfering from non-owner");
})
});
|
BiathlonHelsinki/BiathlonContract
|
test/3_biathlontoken.js
|
JavaScript
|
mit
| 7,223 |
package classfile
import "encoding/binary"
type ClassReader struct {
data []byte
}
func (self *ClassReader) readUint8() uint8 {
val := self.data[0]
self.data = self.data[1:]
return val
}
func (self *ClassReader) readUint16() uint16 {
val := binary.BigEndian.Uint16(self.data)
self.data = self.data[2:]
return val
}
func (self *ClassReader) readUint32() uint32 {
val := binary.BigEndian.Uint32(self.data)
self.data = self.data[4:]
return val
}
func (self *ClassReader) readUint64() uint64 {
val := binary.BigEndian.Uint64(self.data)
self.data = self.data[8:]
return val
}
func (self *ClassReader) readUint16s() []uint16 {
n := self.readUint16()
s := make([]uint16, n)
for i := range s {
s[i] = self.readUint16()
}
return s
}
func (self *ClassReader) readBytes(n uint32) []byte {
bytes := self.data[:n]
self.data = self.data[n:]
return bytes
}
|
wonghoifung/tips
|
goworkspace/src/jvmgo/classfile/class_reader.go
|
GO
|
mit
| 874 |
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.LinkedList;
//this code contains the output assembly code that the program outputs.
//will have at least three functions:
//add(string, string, string, string) <- adds an assembly code line
//optimise(int) <- optimises the output code, wherever possible
//write(string) <- writes the code to the desired filename
public class ASMCode {
LinkedList<String> lines = new LinkedList<String>();
LinkedList<String> data = new LinkedList<String>();
HashMap<String, String> stringMap = new HashMap<String, String>();
LinkedList<lineWrapper> functionLines = new LinkedList<lineWrapper>();
boolean hasFCall;
private interface lineWrapper {
String compile(int stacksize, boolean funcCall);
}
private class stdLineWrapper implements lineWrapper {
private String line;
@Override
public String compile(int stacksize, boolean funcCall) {
return line;
}
public stdLineWrapper(String s) {
line = s;
}
}
private class functionReturnWrapper implements lineWrapper {
@Override
public String compile(int stacksize, boolean funcCall) {
StringBuilder s = new StringBuilder();
if(stacksize != 0) {
s.append("\tmov\tsp, fp");
s.append(System.getProperty("line.separator"));//system independent newline
s.append("\tpop\tfp");
s.append(System.getProperty("line.separator"));
}
if(hasFCall) {
s.append("\tpop\tra");
s.append(System.getProperty("line.separator"));
}
s.append("\tjmpr\tra");
return s.toString();
}
}
public void add(String inst, String reg1, String reg2, String reg3) {
if(deadCode) return;
String newInst = "\t"+inst;
if(reg1 != null) {
newInst = newInst + "\t" + reg1;
if(reg2 != null) {
newInst = newInst + ", " + reg2;
if(reg3 != null) {
newInst = newInst + ", " + reg3;
}
}
}
functionLines.addLast(new stdLineWrapper(newInst));
}
public void add(String inst, String reg1, String reg2) {
add(inst, reg1, reg2, null);
}
public void add(String inst, String reg1) {
add(inst, reg1, null, null);
}
public void add(String inst) {
add(inst, null, null, null);
}
int labIndex = 0;
public String addString(String s) {
//makes sure we don't have duplicate strings in memory
if(stringMap.containsKey(s)) return stringMap.get(s);
//generate a label
String label = "string" + labIndex++;
data.addLast(label+":");
data.addLast("#string " +s);
stringMap.put(s, label);
return label;
}
public void addGlobal(String data, String label) {
//generate a label
this.data.addLast(label+":");
this.data.addLast(data);
}
public void put(String s) {
if(!deadCode)
functionLines.addLast(new stdLineWrapper(s));
}
private String fname;
public void beginFunction(String name) {
functionLines = new LinkedList<lineWrapper>();
fname = name;
hasFCall = false;
}
public void endFunction(int varCount) {
lines.addLast("#global " + fname);
lines.addLast(fname+":");
if(hasFCall) {
lines.addLast("\tpush\tra");
}
if(varCount != 0) {
lines.addLast("\tpush\tfp");
lines.addLast("\tmov\tfp, sp");
lines.addLast("\taddi\tsp, sp, " + varCount);
}
for(lineWrapper w : functionLines) {
lines.addLast(w.compile(varCount, hasFCall));
}
}
public void setHasFCall() {
if(deadCode) return;
hasFCall = true;
}
public void functionReturn() {
if(deadCode) return;
functionLines.addLast(new functionReturnWrapper());
}
public void write(String filename) {
//System.out.println(".text");
//for(String s : lines) {
// System.out.println(s);
//}
//System.out.println(".data");
//for(String s : data) {
// System.out.println(s);
//}
System.out.println("Compilation successful!");
System.out.println("Writing...");
try {
PrintWriter out = new PrintWriter(new FileWriter(filename+".asm"));
out.println(".text");
for(String s : lines) {
out.println(s);
}
out.println(".data");
for(String s : data) {
out.println(s);
}
out.close();
} catch(IOException e) {
System.out.println("Writing failed");
return;
}
System.out.println("Program created!");
}
boolean deadCode;
public void deadCode(boolean codeIsDead) {
deadCode = codeIsDead;
}
}
|
mjsmith707/KSPCompiler
|
src/ASMCode.java
|
Java
|
mit
| 4,329 |
import { Component, OnInit, Input, EventEmitter, Output } from '@angular/core';
import { Filter, FilterType } from 'lib/filter';
@Component({
selector: 'iw-filter-input',
templateUrl: './filter-input.component.html',
styleUrls: ['./filter-input.component.css']
})
export class FilterInputComponent implements OnInit {
@Input() filter: Filter;
@Output() change = new EventEmitter<Filter>();
constructor() { }
ngOnInit() {
}
get FilterType() {
return FilterType;
}
applyFilter(filter: Filter, value: string) {
filter.value = value;
this.change.emit(filter);
}
itemsForField(filter: Filter) {
if (filter.options) {
return filter.options;
}
// put to initialization
// if (!this.rows) { return []; }
// const items = [];
// this.rows.forEach((r) => {
// if (items.indexOf(r[filter.key]) < 0) {
// items.push(r[filter.key]);
// }
// });
// return items;
}
}
/*
filterData(key: string, value: any) {
let filter: Filter = this.filters
.find((f) => f.key === key);
if (!filter) {
filter = {
type: FilterType.String, key, value
};
this.filters.push(filter);
} else {
// overwritte previous value
filter.value = value;
}
this.filterChange.emit();
}
}
*/
|
zorec/ng2-pack
|
src/app/filter-input/filter-input.component.ts
|
TypeScript
|
mit
| 1,320 |
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.get('/about', function(req, res, next) {
res.render('about', { title: 'About' });
});
module.exports = router;
|
Studio39/node-snapclone
|
routes/index.js
|
JavaScript
|
mit
| 301 |
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("10. Advanced Retake Exam - 22 August 2016")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("10. Advanced Retake Exam - 22 August 2016")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[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("8171b56b-59dc-4347-98ad-21d0c4690715")]
// 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")]
|
NikolaySpasov/Softuni
|
C# Advanced/10. Advanced Retake Exam - 22 August 2016/10. Advanced Retake Exam - 22 August 2016/Properties/AssemblyInfo.cs
|
C#
|
mit
| 1,453 |
'''
salt.utils
~~~~~~~~~~
'''
class lazy_property(object):
'''
meant to be used for lazy evaluation of an object attribute.
property should represent non-mutable data, as it replaces itself.
http://stackoverflow.com/a/6849299/564003
'''
def __init__(self, fget):
self.fget = fget
self.func_name = fget.__name__
def __get__(self, obj, cls):
if obj is None:
return None
value = self.fget(obj)
setattr(obj, self.func_name, value)
return value
|
johnnoone/salt-targeting
|
src/salt/utils/__init__.py
|
Python
|
mit
| 537 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Leap;
namespace LeapMIDI
{
class LeapStuff
{
private Controller controller = new Controller();
public float posX { get; private set; }
public float posY { get; private set; }
public float posZ { get; private set; }
public float velX { get; private set; }
public float velY { get; private set; }
public float velZ { get; private set; }
public float pinch { get; private set; }
public string info { get; private set; }
public LeapStuff()
{
//controller.EnableGesture(Gesture.GestureType.;
controller.SetPolicy(Controller.PolicyFlag.POLICY_BACKGROUND_FRAMES);
}
internal void Update()
{
Frame frame = controller.Frame();
info = "Connected: " + controller.IsConnected + "\n" +
"Frame ID: " + frame.Id + "\n" +
"Hands: " + frame.Hands.Count + "\n" +
"Fingers: " + frame.Fingers.Count + "\n\n";
if (frame.Hands.Count == 1)
{
info += "Hand #1 Position X:" + frame.Hands[0].PalmPosition.x + "\n";
info += "Hand #1 Position Y:" + frame.Hands[0].PalmPosition.y + "\n";
info += "Hand #1 Position Z:" + frame.Hands[0].PalmPosition.z + "\n\n";
info += "Hand #1 Velocity X:" + frame.Hands[0].PalmVelocity.x + "\n";
info += "Hand #1 Velocity Y:" + frame.Hands[0].PalmVelocity.y + "\n";
info += "Hand #1 Velocity Z:" + frame.Hands[0].PalmVelocity.z + "\n";
info += "Hand #1 Pinch:" + frame.Hands[0].PinchStrength + "\n";
posX = frame.Hands[0].PalmPosition.x;
posY = frame.Hands[0].PalmPosition.y;
posZ = frame.Hands[0].PalmPosition.z;
velX = frame.Hands[0].PalmVelocity.x;
velY = frame.Hands[0].PalmVelocity.y;
velZ = frame.Hands[0].PalmVelocity.z;
pinch = frame.Hands[0].PinchStrength;
}
else
{
velX = 0;
velY = 0;
velZ = 0;
pinch = 0;
}
}
}
}
|
LeifBloomquist/LeapMotion
|
C#/LeapMIDI/LeapStuff.cs
|
C#
|
mit
| 2,374 |
//
// Created by Aman LaChapelle on 5/26/17.
//
// pytorch_inference
// Copyright (c) 2017 Aman LaChapelle
// Full license at pytorch_inference/LICENSE.txt
//
#include "../include/layers.hpp"
#include "utils.hpp"
int main(){
std::vector<pytorch::tensor> tests = test_setup({1, 1, 1},
{2, 2, 2},
{45, 45, 45},
{50, 50, 50},
{1},
{2},
{45},
{50},
{"test_prod1.dat", "test_prod2.dat", "test_prod3.dat"},
"test_prod");
// tests has {input1, input2, input3, pytorch_output}
pytorch::Product p(pytorch::k, 3);
af::timer::start();
pytorch::tensor prod;
for (int j = 49; j >= 0; j--){
prod = p({tests[0], tests[1], tests[2]})[0];
prod.eval();
}
af::sync();
std::cout << "arrayfire forward took (s): " << af::timer::stop()/50 << "(avg)" << std::endl;
assert(almost_equal(prod, tests[3]));
}
|
bzcheeseman/pytorch-inference
|
test/test_product.cpp
|
C++
|
mit
| 1,213 |
package com.github.weeniearms.graffiti;
import com.github.weeniearms.graffiti.config.CacheConfiguration;
import com.github.weeniearms.graffiti.generator.GraphGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.Arrays;
@Service
public class GraphService {
private final GraphGenerator[] generators;
@Autowired
public GraphService(GraphGenerator[] generators) {
this.generators = generators;
}
@Cacheable(CacheConfiguration.GRAPH)
public byte[] generateGraph(String source, GraphGenerator.OutputFormat format) throws IOException {
GraphGenerator generator =
Arrays.stream(generators)
.filter(g -> g.isSourceSupported(source))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("No matching generator found for source"));
return generator.generateGraph(source, format);
}
}
|
weeniearms/graffiti
|
src/main/java/com/github/weeniearms/graffiti/GraphService.java
|
Java
|
mit
| 1,097 |
<?php
/**
* This file is part of the [n]core framework
*
* Copyright (c) 2014 Sascha Seewald / novael.de
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace nCore\Core\Router\Exception;
use nCore\Core\Exception\DefaultException;
/**
* Class RouterException
* @package nCore\Core\Router\Exception
*/
class RouterException extends DefaultException
{
/**
* @inheritdoc
*/
public function dispatchException()
{
$this->httpCode = 500;
}
}
|
sSeewald/nCore
|
src/nCore/Core/Router/Exception/RouterException.php
|
PHP
|
mit
| 572 |
'use strict';
// Projects controller
angular.module('about').controller('AboutUsController', ['$scope', '$stateParams', '$state', '$location', 'Authentication',
function($scope, $stateParams, $state, $location, Authentication) {
$scope.authentication = Authentication;
}
]);
|
spiridonov-oa/people-ma
|
public/modules/about/controllers/about.client.controller.js
|
JavaScript
|
mit
| 281 |
<?php
/**
* AbstractField class file
*/
namespace Graviton\DocumentBundle\DependencyInjection\Compiler\Utils;
/**
* Base document field
*
* @author List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://swisscom.ch
*/
class AbstractField
{
/**
* @var string
*/
private $fieldName;
/**
* @var string
*/
private $exposedName;
/**
* @var bool
*/
private $readOnly;
/**
* @var bool
*/
private $required;
/**
* @var bool
*/
private $searchable;
/**
* @var bool
*/
private $recordOriginException;
/**
* Constructor
*
* @param string $fieldName Field name
* @param string $exposedName Exposed name
* @param bool $readOnly Read only
* @param bool $required Is required
* @param bool $searchable Is searchable
* @param bool $recordOriginException Is an exception to record origin
*/
public function __construct(
$fieldName,
$exposedName,
$readOnly,
$required,
$searchable,
$recordOriginException
) {
$this->fieldName = $fieldName;
$this->exposedName = $exposedName;
$this->readOnly = $readOnly;
$this->required = $required;
$this->searchable = $searchable;
$this->recordOriginException = $recordOriginException;
}
/**
* Get field name
*
* @return string
*/
public function getFieldName()
{
return $this->fieldName;
}
/**
* Get exposed name
*
* @return string
*/
public function getExposedName()
{
return $this->exposedName;
}
/**
* Is read only
*
* @return bool
*/
public function isReadOnly()
{
return $this->readOnly;
}
/**
* Is required
*
* @return bool
*/
public function isRequired()
{
return $this->required;
}
/**
* Is searchable
*
* @return boolean
*/
public function isSearchable()
{
return $this->searchable;
}
/**
* @param boolean $searchable Is searchable
*
* @return void
*/
public function setSearchable($searchable)
{
$this->searchable = $searchable;
}
/**
* get RecordOriginException
*
* @return boolean RecordOriginException
*/
public function isRecordOriginException()
{
return $this->recordOriginException;
}
/**
* set RecordOriginException
*
* @param boolean $recordOriginException recordOriginException
*
* @return void
*/
public function setRecordOriginException($recordOriginException)
{
$this->recordOriginException = $recordOriginException;
}
}
|
libgraviton/graviton
|
src/Graviton/DocumentBundle/DependencyInjection/Compiler/Utils/AbstractField.php
|
PHP
|
mit
| 2,983 |
<?php
namespace Abe\FileUploadBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Abe\FileUploadBundle\Entity\Document;
use Abe\FileUploadBundle\Form\DocumentType;
/**
* user2 controller.
*
* @Route("/main/upload")
*/
class UploadController extends Controller
{
/**
* creates the form to uplaod a file with the Documetn entity entities.
*
* @Route("/new", name="main_upload_file")
* @Method("GET")
* @Template()
*/
public function uploadAction()
{
$entity = new Document();
$form = $this->createUploadForm($entity);
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* @Template()
* @Route("/", name="main_upload")
* @Method("POST")
*/
public function uploadFileAction(Request $request)
{
return $this->redirect($this->generateUrl('homepage'));
$document = new Document();
$form = $this->createUploadForm($document);
$form->handleRequest($request);
$test = $form->getErrors();
//if ($this->getRequest()->getMethod() === 'POST') {
// $form->bindRequest($this->getRequest());
if ($form->isSubmitted()) {
$fileinfomation = $form->getData();
exit(\Doctrine\Common\Util\Debug::dump($test));
$em = $this->getDoctrine()->getEntityManager();
$document->upload();
$em->persist($document);
$em->flush();
return $this->redirect($this->generateUrl('homepage'));
}
//}
return array(
'form' => $form->createView(),
'entity' =>$document,
);
}
/**
* Creates a form to create a Document entity.
*
* @param Document $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createUploadForm(Document $entity)
{
$form = $this->createForm(new DocumentType(), $entity, array(
'action' => $this->generateUrl('document_create'),
'method' => 'POST',
));
$form->add('submit', 'button', array('label' => 'Upload'));
return $form;
}
public function upload()
{
// the file property can be empty if the field is not required
if (null === $this->getFile()) {
return;
}
// use the original file name here but you should
// sanitize it at least to avoid any security issues
// move takes the target directory and then the
// target filename to move to
$this->getFile()->move(
$this->getUploadRootDir(),
$this->getFile()->getClientOriginalName()
);
// set the path property to the filename where you've saved the file
$this->path = $this->getFile()->getClientOriginalName();
// clean up the file property as you won't need it anymore
$this->file = null;
}
/**
* @Template()
* @Route("/", name="main_uploadfile")
* @Method("POST")
*/
public function uploadFileAction2(Request $request)
{
$document = new Document();
$test = $form->getErrors();
if(2) {
$fileinfomation = $form->getData();
$em = $this->getDoctrine()->getEntityManager();
$document->upload();
$em->persist($document);
$em->flush();
return $this->redirect($this->generateUrl('homepage'));
}
}
}
|
Dabea/BasicLogin
|
src/Abe/FileUploadBundle/Controller/UploadController.php
|
PHP
|
mit
| 3,780 |
import { Dimensions, PixelRatio } from 'react-native';
const Utils = {
ratio: PixelRatio.get(),
pixel: 1 / PixelRatio.get(),
size: {
width: Dimensions.get('window').width,
height: Dimensions.get('window').height,
},
post(url, data, callback) {
const fetchOptions = {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
};
fetch(url, fetchOptions)
.then(response => {
response.json();
})
.then(responseData => {
callback(responseData);
});
},
};
export default Utils;
|
zhiyuanMA/ReactNativeShowcase
|
components/utils.js
|
JavaScript
|
mit
| 765 |
using Humanizer.Localisation;
using Xunit;
using Xunit.Extensions;
namespace Humanizer.Tests.Localisation.ptBR
{
public class DateHumanizeTests : AmbientCulture
{
public DateHumanizeTests() : base("pt-BR") { }
[Theory]
[InlineData(-2, "2 segundos atrás")]
[InlineData(-1, "um segundo atrás")]
public void SecondsAgo(int seconds, string expected)
{
DateHumanize.Verify(expected, seconds, TimeUnit.Second, Tense.Past);
}
[Theory]
[InlineData(1, "em um segundo")]
[InlineData(2, "em 2 segundos")]
public void SecondsFromNow(int seconds, string expected)
{
DateHumanize.Verify(expected, seconds, TimeUnit.Second, Tense.Future);
}
[Theory]
[InlineData(-2, "2 minutos atrás")]
[InlineData(-1, "um minuto atrás")]
public void MinutesAgo(int minutes, string expected)
{
DateHumanize.Verify(expected, minutes, TimeUnit.Minute, Tense.Past);
}
[Theory]
[InlineData(1, "em um minuto")]
[InlineData(2, "em 2 minutos")]
public void MinutesFromNow(int minutes, string expected)
{
DateHumanize.Verify(expected, minutes, TimeUnit.Minute, Tense.Future);
}
[Theory]
[InlineData(-2, "2 horas atrás")]
[InlineData(-1, "uma hora atrás")]
public void HoursAgo(int hours, string expected)
{
DateHumanize.Verify(expected, hours, TimeUnit.Hour, Tense.Past);
}
[Theory]
[InlineData(1, "em uma hora")]
[InlineData(2, "em 2 horas")]
public void HoursFromNow(int hours, string expected)
{
DateHumanize.Verify(expected, hours, TimeUnit.Hour, Tense.Future);
}
[Theory]
[InlineData(-2, "2 dias atrás")]
[InlineData(-1, "ontem")]
public void DaysAgo(int days, string expected)
{
DateHumanize.Verify(expected, days, TimeUnit.Day, Tense.Past);
}
[Theory]
[InlineData(1, "amanhã")]
[InlineData(2, "em 2 dias")]
public void DaysFromNow(int days, string expected)
{
DateHumanize.Verify(expected, days, TimeUnit.Day, Tense.Future);
}
[Theory]
[InlineData(-2, "2 meses atrás")]
[InlineData(-1, "um mês atrás")]
public void MonthsAgo(int months, string expected)
{
DateHumanize.Verify(expected, months, TimeUnit.Month, Tense.Past);
}
[Theory]
[InlineData(1, "em um mês")]
[InlineData(2, "em 2 meses")]
public void MonthsFromNow(int months, string expected)
{
DateHumanize.Verify(expected, months, TimeUnit.Month, Tense.Future);
}
[Theory]
[InlineData(-2, "2 anos atrás")]
[InlineData(-1, "um ano atrás")]
public void YearsAgo(int years, string expected)
{
DateHumanize.Verify(expected, years, TimeUnit.Year, Tense.Past);
}
[Theory]
[InlineData(1, "em um ano")]
[InlineData(2, "em 2 anos")]
public void YearsFromNow(int years, string expected)
{
DateHumanize.Verify(expected, years, TimeUnit.Year, Tense.Future);
}
[Fact]
public void Now()
{
DateHumanize.Verify("agora", 0, TimeUnit.Day, Tense.Future);
}
}
}
|
hhariri/Humanizer
|
src/Humanizer.Tests/Localisation/pt-BR/DateHumanizeTests.cs
|
C#
|
mit
| 3,481 |
"""This module contains examples of the op() function
where:
op(f,x) returns a stream where x is a stream, and f
is an operator on lists, i.e., f is a function from
a list to a list. These lists are of lists of arbitrary
objects other than streams and agents.
Function f must be stateless, i.e., for any lists u, v:
f(u.extend(v)) = f(u).extend(f(v))
(Stateful functions are given in OpStateful.py with
examples in ExamplesOpWithState.py.)
Let f be a stateless operator on lists and let x be a stream.
If at some point, the value of stream x is a list u then at
that point, the value of stream op(f,x) is the list f(u).
If at a later point, the value of stream x is the list:
u.extend(v) then, at that point the value of stream op(f,x)
is f(u).extend(f(v)).
As a specific example, consider the following f():
def f(lst): return [w * w for w in lst]
If at some point in time, the value of x is [3, 7],
then at that point the value of op(f,x) is f([3, 7])
or [9, 49]. If at a later point, the value of x is
[3, 7, 0, 11, 5] then the value of op(f,x) at that point
is f([3, 7, 0, 11, 5]) or [9, 49, 0, 121, 25].
"""
if __name__ == '__main__':
if __package__ is None:
import sys
from os import path
sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) )
from Agent import *
from ListOperators import *
from PrintFunctions import print_streams_recent
def example_1():
print "example_1"
print "op(f, x): f is a function from a list to a list"
print "x is a stream \n"
# FUNCTIONS FROM LIST TO LIST
# This example uses the following list operators:
# functions from a list to a list.
# f, g, h, r
# Example A: function using list comprehension
def f(lst): return [w*w for w in lst]
# Example B: function using filter
threshold = 6
def predicate(w):
return w > threshold
def g(lst):
return filter(predicate, lst)
# Example C: function using map
# Raise each element of the list to the n-th power.
n = 3
def power(w):
return w**n
def h(lst):
return map(power, lst)
# Example D: function using another list comprehension
# Discard any element of x that is not a
# multiple of a parameter n, and divide the
# elements that are multiples of n by n.
n = 3
def r(lst):
result = []
for w in lst:
if w%n == 0: result.append(w/n)
return result
# EXAMPLES OF OPERATIONS ON STREAMS
# The input stream for these examples
x = Stream('x')
print 'x is the input stream.'
print 'a is a stream consisting of the squares of the input'
print 'b is the stream consisting of values that exceed 6'
print 'c is the stream consisting of the third powers of the input'
print 'd is the stream consisting of values that are multiples of 3 divided by 3'
print 'newa is the same as a. It is defined in a more succinct fashion.'
print 'newb has squares that exceed 6.'
print ''
# The output streams a, b, c, d obtained by
# applying the list operators f, g, h, r to
# stream x.
a = op(f, x)
b = op(g, x)
c = op(h, x)
d = op(r, x)
# You can also define a function only on streams.
# You can do this using functools in Python or
# by simple encapsulation as shown below.
def F(x): return op(f,x)
def G(x): return op(g,x)
newa = F(x)
newb = G(F(x))
# The advantage is that F is a function only
# of streams. So, function composition looks cleaner
# as in G(F(x))
# Name the output streams to label the output
# so that reading the output is easier.
a.set_name('a')
newa.set_name('newa')
b.set_name('b')
newb.set_name('newb')
c.set_name('c')
d.set_name('d')
# At this point x is the empty stream:
# its value is []
x.extend([3, 7])
# Now the value of x is [3, 7]
print "FIRST STEP"
print_streams_recent([x, a, b, c, d, newa, newb])
print ""
x.extend([0, 11, 15])
# Now the value of x is [3, 7, 0, 11, 15]
print "SECOND STEP"
print_streams_recent([x, a, b, c, d, newa, newb])
def main():
example_1()
if __name__ == '__main__':
main()
|
zatricion/Streams
|
ExamplesElementaryOperations/ExamplesOpNoState.py
|
Python
|
mit
| 4,241 |
<?php
/*
* This file is part of the Black package.
*
* (c) Alexandre Balmes <albalmes@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Black\Bundle\MenuBundle\Model;
/**
* Class MenuInterface
*
* @package Black\Bundle\MenuBundle\Model
* @author Alexandre Balmes <albalmes@gmail.com>
* @license http://opensource.org/licenses/mit-license.php MIT
*/
interface MenuInterface
{
/**
* @return mixed
*/
public function getId();
/**
* @return mixed
*/
public function getName();
/**
* @return mixed
*/
public function getSlug();
/**
* @return mixed
*/
public function getDescription();
/**
* @return mixed
*/
public function getItems();
}
|
pocky/MenuBundle
|
Model/MenuInterface.php
|
PHP
|
mit
| 845 |
<?php
/**
* Response Already Send Exception
*
* @author Tom Valk <tomvalk@lt-box.info>
* @copyright 2017 Tom Valk
*/
namespace Arvici\Exception;
class ResponseAlreadySendException extends ArviciException
{
/**
* ResponseAlreadySendException constructor.
* @param string $message
* @param int $code
* @param \Exception $previous
*/
public function __construct($message, $code = 0, \Exception $previous = null)
{
parent::__construct($message, $code, $previous);
}
public function __toString()
{
return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
}
}
|
arvici/framework
|
src/Arvici/Exception/ResponseAlreadySendException.php
|
PHP
|
mit
| 640 |
#!/usr/bin/env node
//
// cli.js
//
// Copyright (c) 2016-2017 Junpei Kawamoto
//
// This software is released under the MIT License.
//
// http://opensource.org/licenses/mit-license.php
//
const {
start,
crawl
} = require("../lib/crawler");
const argv = require("yargs")
.option("lang", {
describe: "Language to be used to scrape trand pages. Not used in crawl command."
})
.default("lang", "EN")
.option("dir", {
describe: "Path to the directory to store database files"
})
.demandOption(["dir"])
.command("*", "Start crawling", () => {}, (argv) => {
start(argv.lang, argv.dir);
})
.command("crawl", "Crawl comments form a video", () => {}, (argv) => {
crawl(argv.dir).catch((err) => {
console.error(err);
});
})
.help("h")
.alias("h", "help")
.argv;
|
itslab-kyushu/youtube-comment-crawler
|
bin/cli.js
|
JavaScript
|
mit
| 867 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CollegeFbsRankings.Domain.Games;
using CollegeFbsRankings.Domain.Rankings;
using CollegeFbsRankings.Domain.Teams;
namespace CollegeFbsRankings.Domain.Validations
{
public class ValidationService
{
public Validation<GameId> GameValidationFromRanking<TRankingValue>(
IEnumerable<CompletedGame> games,
Ranking<TeamId, TRankingValue> performance)
where TRankingValue : IRankingValue
{
return new Validation<GameId>(games.Select(game =>
{
var winningTeamData = performance[game.WinningTeamId];
var losingTeamData = performance[game.LosingTeamId];
foreach (var values in winningTeamData.Values.Zip(losingTeamData.Values, Tuple.Create))
{
if (values.Item1 > values.Item2)
return new KeyValuePair<GameId, eValidationResult>(game.Id, eValidationResult.Correct);
if (values.Item1 < values.Item2)
return new KeyValuePair<GameId, eValidationResult>(game.Id, eValidationResult.Incorrect);
}
return new KeyValuePair<GameId, eValidationResult>(game.Id, eValidationResult.Skipped);
}));
}
}
}
|
mikee385/CollegeFbsRankings
|
Domain/Validations/ValidationService.cs
|
C#
|
mit
| 1,400 |
<div class="container" >
<div class="row page-title">
<div class="col-xs-12 text-center">
<span>Consultation</span>
</div>
</div>
</div>
<script type="text/javascript">
/**
* Created by Kupletsky Sergey on 05.11.14.
*
* Material Design Responsive Table
* Tested on Win8.1 with browsers: Chrome 37, Firefox 32, Opera 25, IE 11, Safari 5.1.7
* You can use this table in Bootstrap (v3) projects. Material Design Responsive Table CSS-style will override basic bootstrap style.
* JS used only for table constructor: you don't need it in your project
*/
$(document).ready(function() {
var table = $('#table');
// Table bordered
$('#table-bordered').change(function() {
var value = $( this ).val();
table.removeClass('table-bordered').addClass(value);
});
// Table striped
$('#table-striped').change(function() {
var value = $( this ).val();
table.removeClass('table-striped').addClass(value);
});
// Table hover
$('#table-hover').change(function() {
var value = $( this ).val();
table.removeClass('table-hover').addClass(value);
});
// Table color
$('#table-color').change(function() {
var value = $(this).val();
table.removeClass(/^table-mc-/).addClass(value);
});
});
// jQuery’s hasClass and removeClass on steroids
// by Nikita Vasilyev
// https://github.com/NV/jquery-regexp-classes
(function(removeClass) {
jQuery.fn.removeClass = function( value ) {
if ( value && typeof value.test === "function" ) {
for ( var i = 0, l = this.length; i < l; i++ ) {
var elem = this[i];
if ( elem.nodeType === 1 && elem.className ) {
var classNames = elem.className.split( /\s+/ );
for ( var n = classNames.length; n--; ) {
if ( value.test(classNames[n]) ) {
classNames.splice(n, 1);
}
}
elem.className = jQuery.trim( classNames.join(" ") );
}
}
} else {
removeClass.call(this, value);
}
return this;
}
})(jQuery.fn.removeClass);
</script>
<style media="screen">
/* -- Material Design Table style -------------- */
.table {
width: 100%;
max-width: 100%;
margin-bottom: 2rem;
background-color: #fff;
}
.table > thead > tr,
.table > tbody > tr,
.table > tfoot > tr {
-webkit-transition: all 0.3s ease;
-o-transition: all 0.3s ease;
transition: all 0.3s ease;
}
.table > thead > tr > th,
.table > tbody > tr > th,
.table > tfoot > tr > th,
.table > thead > tr > td,
.table > tbody > tr > td,
.table > tfoot > tr > td {
text-align: left;
padding: 1.6rem;
vertical-align: top;
border-top: 0;
-webkit-transition: all 0.3s ease;
-o-transition: all 0.3s ease;
transition: all 0.3s ease;
}
.table > thead > tr > th {
font-weight: 400;
color: #757575;
vertical-align: bottom;
border-bottom: 1px solid rgba(0, 0, 0, 0.12);
}
.table > caption + thead > tr:first-child > th,
.table > colgroup + thead > tr:first-child > th,
.table > thead:first-child > tr:first-child > th,
.table > caption + thead > tr:first-child > td,
.table > colgroup + thead > tr:first-child > td,
.table > thead:first-child > tr:first-child > td {
border-top: 0;
}
.table > tbody + tbody {
border-top: 1px solid rgba(0, 0, 0, 0.12);
}
.table .table {
background-color: #fff;
}
.table .no-border {
border: 0;
}
.table-condensed > thead > tr > th,
.table-condensed > tbody > tr > th,
.table-condensed > tfoot > tr > th,
.table-condensed > thead > tr > td,
.table-condensed > tbody > tr > td,
.table-condensed > tfoot > tr > td {
padding: 0.8rem;
}
.table-bordered {
border: 0;
}
.table-bordered > thead > tr > th,
.table-bordered > tbody > tr > th,
.table-bordered > tfoot > tr > th,
.table-bordered > thead > tr > td,
.table-bordered > tbody > tr > td,
.table-bordered > tfoot > tr > td {
border: 0;
border-bottom: 1px solid #e0e0e0;
}
.table-bordered > thead > tr > th,
.table-bordered > thead > tr > td {
border-bottom-width: 2px;
}
.table-striped > tbody > tr:nth-child(odd) > td,
.table-striped > tbody > tr:nth-child(odd) > th {
background-color: #f5f5f5;
}
.table-hover > tbody > tr:hover > td,
.table-hover > tbody > tr:hover > th {
background-color: rgba(0, 0, 0, 0.12);
}
@media screen and (max-width: 768px) {
.table-responsive-vertical > .table {
margin-bottom: 0;
background-color: transparent;
}
.table-responsive-vertical > .table > thead,
.table-responsive-vertical > .table > tfoot {
display: none;
}
.table-responsive-vertical > .table > tbody {
display: block;
}
.table-responsive-vertical > .table > tbody > tr {
display: block;
border: 1px solid #e0e0e0;
border-radius: 2px;
margin-bottom: 1.6rem;
}
.table-responsive-vertical > .table > tbody > tr > td {
background-color: #fff;
display: block;
vertical-align: middle;
text-align: right;
}
.table-responsive-vertical > .table > tbody > tr > td[data-title]:before {
content: attr(data-title);
float: left;
font-size: inherit;
font-weight: 400;
color: #757575;
}
.table-responsive-vertical.shadow-z-1 {
-webkit-box-shadow: none;
-moz-box-shadow: none;
box-shadow: none;
}
.table-responsive-vertical.shadow-z-1 > .table > tbody > tr {
border: none;
-webkit-box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.12), 0 1px 2px 0 rgba(0, 0, 0, 0.24);
-moz-box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.12), 0 1px 2px 0 rgba(0, 0, 0, 0.24);
box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.12), 0 1px 2px 0 rgba(0, 0, 0, 0.24);
}
.table-responsive-vertical > .table-bordered {
border: 0;
}
.table-responsive-vertical > .table-bordered > tbody > tr > td {
border: 0;
border-bottom: 1px solid #e0e0e0;
}
.table-responsive-vertical > .table-bordered > tbody > tr > td:last-child {
border-bottom: 0;
}
.table-responsive-vertical > .table-striped > tbody > tr > td,
.table-responsive-vertical > .table-striped > tbody > tr:nth-child(odd) {
background-color: #fff;
}
.table-responsive-vertical > .table-striped > tbody > tr > td:nth-child(odd) {
background-color: #f5f5f5;
}
.table-responsive-vertical > .table-hover > tbody > tr:hover > td,
.table-responsive-vertical > .table-hover > tbody > tr:hover {
background-color: #fff;
}
.table-responsive-vertical > .table-hover > tbody > tr > td:hover {
background-color: rgba(0, 0, 0, 0.12);
}
}
.table-striped.table-mc-red > tbody > tr:nth-child(odd) > td,
.table-striped.table-mc-red > tbody > tr:nth-child(odd) > th {
background-color: #fde0dc;
}
.table-hover.table-mc-red > tbody > tr:hover > td,
.table-hover.table-mc-red > tbody > tr:hover > th {
background-color: #f9bdbb;
}
@media screen and (max-width: 767px) {
.table-responsive-vertical .table-striped.table-mc-red > tbody > tr > td,
.table-responsive-vertical .table-striped.table-mc-red > tbody > tr:nth-child(odd) {
background-color: #fff;
}
.table-responsive-vertical .table-striped.table-mc-red > tbody > tr > td:nth-child(odd) {
background-color: #fde0dc;
}
.table-responsive-vertical .table-hover.table-mc-red > tbody > tr:hover > td,
.table-responsive-vertical .table-hover.table-mc-red > tbody > tr:hover {
background-color: #fff;
}
.table-responsive-vertical .table-hover.table-mc-red > tbody > tr > td:hover {
background-color: #f9bdbb;
}
}
.table-striped.table-mc-pink > tbody > tr:nth-child(odd) > td,
.table-striped.table-mc-pink > tbody > tr:nth-child(odd) > th {
background-color: #fce4ec;
}
.table-hover.table-mc-pink > tbody > tr:hover > td,
.table-hover.table-mc-pink > tbody > tr:hover > th {
background-color: #f8bbd0;
}
@media screen and (max-width: 767px) {
.table-responsive-vertical .table-striped.table-mc-pink > tbody > tr > td,
.table-responsive-vertical .table-striped.table-mc-pink > tbody > tr:nth-child(odd) {
background-color: #fff;
}
.table-responsive-vertical .table-striped.table-mc-pink > tbody > tr > td:nth-child(odd) {
background-color: #fce4ec;
}
.table-responsive-vertical .table-hover.table-mc-pink > tbody > tr:hover > td,
.table-responsive-vertical .table-hover.table-mc-pink > tbody > tr:hover {
background-color: #fff;
}
.table-responsive-vertical .table-hover.table-mc-pink > tbody > tr > td:hover {
background-color: #f8bbd0;
}
}
.table-striped.table-mc-purple > tbody > tr:nth-child(odd) > td,
.table-striped.table-mc-purple > tbody > tr:nth-child(odd) > th {
background-color: #f3e5f5;
}
.table-hover.table-mc-purple > tbody > tr:hover > td,
.table-hover.table-mc-purple > tbody > tr:hover > th {
background-color: #e1bee7;
}
@media screen and (max-width: 767px) {
.table-responsive-vertical .table-striped.table-mc-purple > tbody > tr > td,
.table-responsive-vertical .table-striped.table-mc-purple > tbody > tr:nth-child(odd) {
background-color: #fff;
}
.table-responsive-vertical .table-striped.table-mc-purple > tbody > tr > td:nth-child(odd) {
background-color: #f3e5f5;
}
.table-responsive-vertical .table-hover.table-mc-purple > tbody > tr:hover > td,
.table-responsive-vertical .table-hover.table-mc-purple > tbody > tr:hover {
background-color: #fff;
}
.table-responsive-vertical .table-hover.table-mc-purple > tbody > tr > td:hover {
background-color: #e1bee7;
}
}
.table-striped.table-mc-deep-purple > tbody > tr:nth-child(odd) > td,
.table-striped.table-mc-deep-purple > tbody > tr:nth-child(odd) > th {
background-color: #ede7f6;
}
.table-hover.table-mc-deep-purple > tbody > tr:hover > td,
.table-hover.table-mc-deep-purple > tbody > tr:hover > th {
background-color: #d1c4e9;
}
@media screen and (max-width: 767px) {
.table-responsive-vertical .table-striped.table-mc-deep-purple > tbody > tr > td,
.table-responsive-vertical .table-striped.table-mc-deep-purple > tbody > tr:nth-child(odd) {
background-color: #fff;
}
.table-responsive-vertical .table-striped.table-mc-deep-purple > tbody > tr > td:nth-child(odd) {
background-color: #ede7f6;
}
.table-responsive-vertical .table-hover.table-mc-deep-purple > tbody > tr:hover > td,
.table-responsive-vertical .table-hover.table-mc-deep-purple > tbody > tr:hover {
background-color: #fff;
}
.table-responsive-vertical .table-hover.table-mc-deep-purple > tbody > tr > td:hover {
background-color: #d1c4e9;
}
}
.table-striped.table-mc-indigo > tbody > tr:nth-child(odd) > td,
.table-striped.table-mc-indigo > tbody > tr:nth-child(odd) > th {
background-color: #e8eaf6;
}
.table-hover.table-mc-indigo > tbody > tr:hover > td,
.table-hover.table-mc-indigo > tbody > tr:hover > th {
background-color: #c5cae9;
}
@media screen and (max-width: 767px) {
.table-responsive-vertical .table-striped.table-mc-indigo > tbody > tr > td,
.table-responsive-vertical .table-striped.table-mc-indigo > tbody > tr:nth-child(odd) {
background-color: #fff;
}
.table-responsive-vertical .table-striped.table-mc-indigo > tbody > tr > td:nth-child(odd) {
background-color: #e8eaf6;
}
.table-responsive-vertical .table-hover.table-mc-indigo > tbody > tr:hover > td,
.table-responsive-vertical .table-hover.table-mc-indigo > tbody > tr:hover {
background-color: #fff;
}
.table-responsive-vertical .table-hover.table-mc-indigo > tbody > tr > td:hover {
background-color: #c5cae9;
}
}
.table-striped.table-mc-blue > tbody > tr:nth-child(odd) > td,
.table-striped.table-mc-blue > tbody > tr:nth-child(odd) > th {
background-color: #e7e9fd;
}
.table-hover.table-mc-blue > tbody > tr:hover > td,
.table-hover.table-mc-blue > tbody > tr:hover > th {
background-color: #d0d9ff;
}
@media screen and (max-width: 767px) {
.table-responsive-vertical .table-striped.table-mc-blue > tbody > tr > td,
.table-responsive-vertical .table-striped.table-mc-blue > tbody > tr:nth-child(odd) {
background-color: #fff;
}
.table-responsive-vertical .table-striped.table-mc-blue > tbody > tr > td:nth-child(odd) {
background-color: #e7e9fd;
}
.table-responsive-vertical .table-hover.table-mc-blue > tbody > tr:hover > td,
.table-responsive-vertical .table-hover.table-mc-blue > tbody > tr:hover {
background-color: #fff;
}
.table-responsive-vertical .table-hover.table-mc-blue > tbody > tr > td:hover {
background-color: #d0d9ff;
}
}
.table-striped.table-mc-light-blue > tbody > tr:nth-child(odd) > td,
.table-striped.table-mc-light-blue > tbody > tr:nth-child(odd) > th {
background-color: #e1f5fe;
}
.table-hover.table-mc-light-blue > tbody > tr:hover > td,
.table-hover.table-mc-light-blue > tbody > tr:hover > th {
background-color: #b3e5fc;
}
@media screen and (max-width: 767px) {
.table-responsive-vertical .table-striped.table-mc-light-blue > tbody > tr > td,
.table-responsive-vertical .table-striped.table-mc-light-blue > tbody > tr:nth-child(odd) {
background-color: #fff;
}
.table-responsive-vertical .table-striped.table-mc-light-blue > tbody > tr > td:nth-child(odd) {
background-color: #e1f5fe;
}
.table-responsive-vertical .table-hover.table-mc-light-blue > tbody > tr:hover > td,
.table-responsive-vertical .table-hover.table-mc-light-blue > tbody > tr:hover {
background-color: #fff;
}
.table-responsive-vertical .table-hover.table-mc-light-blue > tbody > tr > td:hover {
background-color: #b3e5fc;
}
}
.table-striped.table-mc-cyan > tbody > tr:nth-child(odd) > td,
.table-striped.table-mc-cyan > tbody > tr:nth-child(odd) > th {
background-color: #e0f7fa;
}
.table-hover.table-mc-cyan > tbody > tr:hover > td,
.table-hover.table-mc-cyan > tbody > tr:hover > th {
background-color: #b2ebf2;
}
@media screen and (max-width: 767px) {
.table-responsive-vertical .table-striped.table-mc-cyan > tbody > tr > td,
.table-responsive-vertical .table-striped.table-mc-cyan > tbody > tr:nth-child(odd) {
background-color: #fff;
}
.table-responsive-vertical .table-striped.table-mc-cyan > tbody > tr > td:nth-child(odd) {
background-color: #e0f7fa;
}
.table-responsive-vertical .table-hover.table-mc-cyan > tbody > tr:hover > td,
.table-responsive-vertical .table-hover.table-mc-cyan > tbody > tr:hover {
background-color: #fff;
}
.table-responsive-vertical .table-hover.table-mc-cyan > tbody > tr > td:hover {
background-color: #b2ebf2;
}
}
.table-striped.table-mc-teal > tbody > tr:nth-child(odd) > td,
.table-striped.table-mc-teal > tbody > tr:nth-child(odd) > th {
background-color: #e0f2f1;
}
.table-hover.table-mc-teal > tbody > tr:hover > td,
.table-hover.table-mc-teal > tbody > tr:hover > th {
background-color: #b2dfdb;
}
@media screen and (max-width: 767px) {
.table-responsive-vertical .table-striped.table-mc-teal > tbody > tr > td,
.table-responsive-vertical .table-striped.table-mc-teal > tbody > tr:nth-child(odd) {
background-color: #fff;
}
.table-responsive-vertical .table-striped.table-mc-teal > tbody > tr > td:nth-child(odd) {
background-color: #e0f2f1;
}
.table-responsive-vertical .table-hover.table-mc-teal > tbody > tr:hover > td,
.table-responsive-vertical .table-hover.table-mc-teal > tbody > tr:hover {
background-color: #fff;
}
.table-responsive-vertical .table-hover.table-mc-teal > tbody > tr > td:hover {
background-color: #b2dfdb;
}
}
.table-striped.table-mc-green > tbody > tr:nth-child(odd) > td,
.table-striped.table-mc-green > tbody > tr:nth-child(odd) > th {
background-color: #d0f8ce;
}
.table-hover.table-mc-green > tbody > tr:hover > td,
.table-hover.table-mc-green > tbody > tr:hover > th {
background-color: #a3e9a4;
}
@media screen and (max-width: 767px) {
.table-responsive-vertical .table-striped.table-mc-green > tbody > tr > td,
.table-responsive-vertical .table-striped.table-mc-green > tbody > tr:nth-child(odd) {
background-color: #fff;
}
.table-responsive-vertical .table-striped.table-mc-green > tbody > tr > td:nth-child(odd) {
background-color: #d0f8ce;
}
.table-responsive-vertical .table-hover.table-mc-green > tbody > tr:hover > td,
.table-responsive-vertical .table-hover.table-mc-green > tbody > tr:hover {
background-color: #fff;
}
.table-responsive-vertical .table-hover.table-mc-green > tbody > tr > td:hover {
background-color: #a3e9a4;
}
}
.table-striped.table-mc-light-green > tbody > tr:nth-child(odd) > td,
.table-striped.table-mc-light-green > tbody > tr:nth-child(odd) > th {
background-color: #f1f8e9;
}
.table-hover.table-mc-light-green > tbody > tr:hover > td,
.table-hover.table-mc-light-green > tbody > tr:hover > th {
background-color: #dcedc8;
}
@media screen and (max-width: 767px) {
.table-responsive-vertical .table-striped.table-mc-light-green > tbody > tr > td,
.table-responsive-vertical .table-striped.table-mc-light-green > tbody > tr:nth-child(odd) {
background-color: #fff;
}
.table-responsive-vertical .table-striped.table-mc-light-green > tbody > tr > td:nth-child(odd) {
background-color: #f1f8e9;
}
.table-responsive-vertical .table-hover.table-mc-light-green > tbody > tr:hover > td,
.table-responsive-vertical .table-hover.table-mc-light-green > tbody > tr:hover {
background-color: #fff;
}
.table-responsive-vertical .table-hover.table-mc-light-green > tbody > tr > td:hover {
background-color: #dcedc8;
}
}
.table-striped.table-mc-lime > tbody > tr:nth-child(odd) > td,
.table-striped.table-mc-lime > tbody > tr:nth-child(odd) > th {
background-color: #f9fbe7;
}
.table-hover.table-mc-lime > tbody > tr:hover > td,
.table-hover.table-mc-lime > tbody > tr:hover > th {
background-color: #f0f4c3;
}
@media screen and (max-width: 767px) {
.table-responsive-vertical .table-striped.table-mc-lime > tbody > tr > td,
.table-responsive-vertical .table-striped.table-mc-lime > tbody > tr:nth-child(odd) {
background-color: #fff;
}
.table-responsive-vertical .table-striped.table-mc-lime > tbody > tr > td:nth-child(odd) {
background-color: #f9fbe7;
}
.table-responsive-vertical .table-hover.table-mc-lime > tbody > tr:hover > td,
.table-responsive-vertical .table-hover.table-mc-lime > tbody > tr:hover {
background-color: #fff;
}
.table-responsive-vertical .table-hover.table-mc-lime > tbody > tr > td:hover {
background-color: #f0f4c3;
}
}
.table-striped.table-mc-yellow > tbody > tr:nth-child(odd) > td,
.table-striped.table-mc-yellow > tbody > tr:nth-child(odd) > th {
background-color: #fffde7;
}
.table-hover.table-mc-yellow > tbody > tr:hover > td,
.table-hover.table-mc-yellow > tbody > tr:hover > th {
background-color: #fff9c4;
}
@media screen and (max-width: 767px) {
.table-responsive-vertical .table-striped.table-mc-yellow > tbody > tr > td,
.table-responsive-vertical .table-striped.table-mc-yellow > tbody > tr:nth-child(odd) {
background-color: #fff;
}
.table-responsive-vertical .table-striped.table-mc-yellow > tbody > tr > td:nth-child(odd) {
background-color: #fffde7;
}
.table-responsive-vertical .table-hover.table-mc-yellow > tbody > tr:hover > td,
.table-responsive-vertical .table-hover.table-mc-yellow > tbody > tr:hover {
background-color: #fff;
}
.table-responsive-vertical .table-hover.table-mc-yellow > tbody > tr > td:hover {
background-color: #fff9c4;
}
}
.table-striped.table-mc-amber > tbody > tr:nth-child(odd) > td,
.table-striped.table-mc-amber > tbody > tr:nth-child(odd) > th {
background-color: #fff8e1;
}
.table-hover.table-mc-amber > tbody > tr:hover > td,
.table-hover.table-mc-amber > tbody > tr:hover > th {
background-color: #ffecb3;
}
@media screen and (max-width: 767px) {
.table-responsive-vertical .table-striped.table-mc-amber > tbody > tr > td,
.table-responsive-vertical .table-striped.table-mc-amber > tbody > tr:nth-child(odd) {
background-color: #fff;
}
.table-responsive-vertical .table-striped.table-mc-amber > tbody > tr > td:nth-child(odd) {
background-color: #fff8e1;
}
.table-responsive-vertical .table-hover.table-mc-amber > tbody > tr:hover > td,
.table-responsive-vertical .table-hover.table-mc-amber > tbody > tr:hover {
background-color: #fff;
}
.table-responsive-vertical .table-hover.table-mc-amber > tbody > tr > td:hover {
background-color: #ffecb3;
}
}
.table-striped.table-mc-orange > tbody > tr:nth-child(odd) > td,
.table-striped.table-mc-orange > tbody > tr:nth-child(odd) > th {
background-color: #fff3e0;
}
.table-hover.table-mc-orange > tbody > tr:hover > td,
.table-hover.table-mc-orange > tbody > tr:hover > th {
background-color: #ffe0b2;
}
@media screen and (max-width: 767px) {
.table-responsive-vertical .table-striped.table-mc-orange > tbody > tr > td,
.table-responsive-vertical .table-striped.table-mc-orange > tbody > tr:nth-child(odd) {
background-color: #fff;
}
.table-responsive-vertical .table-striped.table-mc-orange > tbody > tr > td:nth-child(odd) {
background-color: #fff3e0;
}
.table-responsive-vertical .table-hover.table-mc-orange > tbody > tr:hover > td,
.table-responsive-vertical .table-hover.table-mc-orange > tbody > tr:hover {
background-color: #fff;
}
.table-responsive-vertical .table-hover.table-mc-orange > tbody > tr > td:hover {
background-color: #ffe0b2;
}
}
.table-striped.table-mc-deep-orange > tbody > tr:nth-child(odd) > td,
.table-striped.table-mc-deep-orange > tbody > tr:nth-child(odd) > th {
background-color: #fbe9e7;
}
.table-hover.table-mc-deep-orange > tbody > tr:hover > td,
.table-hover.table-mc-deep-orange > tbody > tr:hover > th {
background-color: #ffccbc;
}
@media screen and (max-width: 767px) {
.table-responsive-vertical .table-striped.table-mc-deep-orange > tbody > tr > td,
.table-responsive-vertical .table-striped.table-mc-deep-orange > tbody > tr:nth-child(odd) {
background-color: #fff;
}
.table-responsive-vertical .table-striped.table-mc-deep-orange > tbody > tr > td:nth-child(odd) {
background-color: #fbe9e7;
}
.table-responsive-vertical .table-hover.table-mc-deep-orange > tbody > tr:hover > td,
.table-responsive-vertical .table-hover.table-mc-deep-orange > tbody > tr:hover {
background-color: #fff;
}
.table-responsive-vertical .table-hover.table-mc-deep-orange > tbody > tr > td:hover {
background-color: #ffccbc;
}
}
.new{
color: #49c4d5;
background-color: white;
border: 1px solid #49c4d5;
font-weight: 400;
margin-left: 10px;
}
.page-link{
color: rgb(157, 157, 157) !important;
font-size: 10px;
}
</style>
<div class="container" ng-controller="consultation" ng-init="uid='<?=$uid?>';init()">
<div class="row" style="max-width:1000px; margin:auto; margin-bottom:70px;">
<div class="col-xs-12 ">
<table id="table" class="table table-hover table-mc-light-blue" >
<thead>
<tr>
<th class="hidden-xs">Num</th>
<th>Title</th>
<th class="hidden-xs">Author</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="i in consultList" ng-click="openConsult(i)" style="color:#9d9d9d">
<td data-title="Number" style="width:50px;" class="hidden-xs">{{$index+(start)+1}}</td>
<td data-title="Title" style="color:#525252">{{i.TITLE}} ({{i.count}}) <div class="label label-default new" ng-show="i.TIME|new">new</div></td>
<td data-title="Author" class="hidden-xs" style="width:150px;">
{{i.AUTHOR}}
</td>
<td data-title="Date" style="width:150px;">
{{i.TIME|Cdate}}
</td>
</tr>
</tbody>
</table>
</div>
<div class="col-xs-12" style="text-align:center">
<ul class="pagination">
<!-- <li class="page-item">
<a class="page-link" href="#" aria-label="Previous">
<span aria-hidden="true">«</span>
<span class="sr-only">Previous</span>
</a>
</li> -->
<li class="page-item" ng-repeat="i in consultRange">
<a class="page-link" ng-click="goConsult(i)">{{i}}</a>
</li>
<!-- <li class="page-item">
<a class="page-link" href="#" aria-label="Next">
<span aria-hidden="true">»</span>
<span class="sr-only">Next</span>
</a>
</li> -->
</ul>
</div>
<div class="col-xs-12">
<div onclick="$('#write_new').modal('show')" class="pull-right banner-button" >WRITE
</div>
</div>
</div>
<div class="modal fade" id="write_new" tabindex="-1" role="dialog" aria-labelledby="" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body" style="padding:0">
<div class="row" >
<div class="col-xs-12">
<div class="well" ng-init="consult={}" style="margin-bottom:0;">
<!-- <div class="text-center page-title">
<span >Consultation</span>
</div> -->
<div class="form-group has-feedback-none has-feedback-left-none">
<input type="text" class="placeholder form-control no-border" placeholder="Name" ng-model="consult.author" />
</div>
<div class="form-group has-feedback-none has-feedback-left-none">
<input type="text" class="placeholder form-control no-border" placeholder="Title" ng-model="consult.title" />
</div>
<div class="form-group has-feedback-none has-feedback-left-none">
<input type="password" class=" placeholder form-control no-border" placeholder="Password" ng-model="consult.password"/>
</div>
<div class="form-group has-feedback-none has-feedback-left-none">
<textarea style="resize:none;border:none;"class="placeholder form-control" rows="5" style="border:none; box-shadow:none;" placeholder="Message" ng-model="consult.body" ></textarea>
</div>
<div class="btn btnForm btn-block" ng-click="consultForm(consult)">SEND</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
|
r45r54r45/simplewe
|
application/views/consultation.php
|
PHP
|
mit
| 26,096 |
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("DecimalToHex")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DecimalToHex")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("3e808379-6e11-4c24-853e-7d2b4720cbb1")]
// 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")]
|
StoikoNeykov/Telerik
|
CSharp1/Loops/DecimalToHex/Properties/AssemblyInfo.cs
|
C#
|
mit
| 1,400 |
const AppError = require('../../../lib/errors/app')
const assert = require('assert')
function doSomethingBad () {
throw new AppError('app error message')
}
it('Error details', function () {
try {
doSomethingBad()
} catch (err) {
assert.strictEqual(
err.name,
'AppError',
"Name property set to error's name"
)
assert(
err instanceof AppError,
'Is an instance of its class'
)
assert(
err instanceof Error,
'Is instance of built-in Error'
)
assert(
require('util').isError(err),
'Should be recognized by Node.js util#isError'
)
assert(
err.stack,
'Should have recorded a stack'
)
assert.strictEqual(
err.toString(),
'AppError: app error message',
'toString should return the default error message formatting'
)
assert.strictEqual(
err.stack.split('\n')[0],
'AppError: app error message',
'Stack should start with the default error message formatting'
)
assert.strictEqual(
err.stack.split('\n')[1].indexOf('doSomethingBad'),
7,
'The first stack frame should be the function where the error was thrown'
)
}
})
|
notmessenger/poker-analysis
|
test/lib/errors/app.js
|
JavaScript
|
mit
| 1,211 |
require 'spec_helper'
describe Blogitr::Document do
def parse text, filter=:html
@doc = Blogitr::Document.new :text => text, :filter => filter
end
def should_parse_as headers, body, extended=nil
@doc.headers.should == headers
@doc.body.should == body
@doc.extended.should == extended
end
it "should raise an error if an unknown fitler is specified" do
lambda do
parse "foo *bar* \"baz\"", :unknown
end.should raise_error(Blogitr::UnknownFilterError)
end
it "should parse documents with a YAML header" do
parse <<EOD
title: My Doc
subtitle: An Essay
foo
bar
EOD
should_parse_as({ 'title' => "My Doc", 'subtitle' => 'An Essay' },
"foo\n\nbar\n")
end
it "should parse documents without a YAML header" do
parse "foo\nbar\nbaz"
should_parse_as({}, "foo\nbar\nbaz")
end
it "should parse documents with a YAML header but no body" do
parse "title: My Doc"
should_parse_as({ 'title' => "My Doc" }, '')
end
it "should separate extended content from the main body" do
parse <<EOD
foo
<!--more-->
bar
EOD
should_parse_as({}, "foo", "bar\n")
end
it "should expand macros" do
input = "title: Foo\n\n<macro:example foo=\"bar\">baz</macro:example>"
parse input
should_parse_as({'title' => "Foo"},
"Options: {\"foo\"=>\"bar\"}\nBody: baz")
end
it "should provide access to raw body and extended content" do
parse "*foo*\n<!--more-->\n_bar_", :textile
@doc.raw_body.should == "*foo*"
@doc.raw_extended.should == "_bar_"
end
describe "with a :textile filter" do
it "should filter content" do
parse "foo *bar*\n<!--more-->\n\"baz\"", :textile
should_parse_as({}, "<p>foo <strong>bar</strong></p>",
"<p>“baz”</p>")
end
it "should protect expanded macros from filtering" do
text = "\n<macro:example>*foo*</macro:example>"
parse text, :textile
should_parse_as({}, "Options: {}\nBody: *foo*")
end
end
describe "with a :markdown filter" do
it "should filter content" do
parse "foo *bar* \"baz\"", :markdown
should_parse_as({}, "<p>foo <em>bar</em> “baz”</p>\n")
end
it "should protect expanded macros from filtering" do
text = "\n<macro:example>*foo*</macro:example>"
parse text, :markdown
should_parse_as({},
"<div class=\"raw\">Options: {}\nBody: *foo*</div>\n\n")
end
end
describe "#to_s" do
def should_serialize_as headers, body, extended, serialized
opts = { :headers => headers, :raw_body => body,
:raw_extended => extended, :filter => :html }
Blogitr::Document.new(opts).to_s.should == serialized
end
it "should serialize documents with headers" do
should_serialize_as({'title' => 'Foo'}, "_Bar_.", nil,
"title: Foo\n\n_Bar_.")
end
it "should serialize documents without headers" do
should_serialize_as({}, "_Bar_.", nil, "\n_Bar_.")
end
it "should serialize extended content using \\<!--more-->" do
should_serialize_as({}, "Bar.", "_Baz_.", "\nBar.\n<!--more-->\n_Baz_.")
end
end
end
|
emk/blogitr
|
spec/document_spec.rb
|
Ruby
|
mit
| 3,231 |
<?php
namespace Grupo3TallerUNLP\ConfiguracionBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class ConfiguracionControllerTest extends WebTestCase
{
/*
public function testCompleteScenario()
{
// Create a new client to browse the application
$client = static::createClient();
// Create a new entry in the database
$crawler = $client->request('GET', '/configuracion/');
$this->assertEquals(200, $client->getResponse()->getStatusCode(), "Unexpected HTTP status code for GET /configuracion/");
$crawler = $client->click($crawler->selectLink('Create a new entry')->link());
// Fill in the form and submit it
$form = $crawler->selectButton('Create')->form(array(
'grupo3tallerunlp_configuracionbundle_configuracion[field_name]' => 'Test',
// ... other fields to fill
));
$client->submit($form);
$crawler = $client->followRedirect();
// Check data in the show view
$this->assertGreaterThan(0, $crawler->filter('td:contains("Test")')->count(), 'Missing element td:contains("Test")');
// Edit the entity
$crawler = $client->click($crawler->selectLink('Edit')->link());
$form = $crawler->selectButton('Update')->form(array(
'grupo3tallerunlp_configuracionbundle_configuracion[field_name]' => 'Foo',
// ... other fields to fill
));
$client->submit($form);
$crawler = $client->followRedirect();
// Check the element contains an attribute with value equals "Foo"
$this->assertGreaterThan(0, $crawler->filter('[value="Foo"]')->count(), 'Missing element [value="Foo"]');
// Delete the entity
$client->submit($crawler->selectButton('Delete')->form());
$crawler = $client->followRedirect();
// Check the entity has been delete on the list
$this->assertNotRegExp('/Foo/', $client->getResponse()->getContent());
}
*/
}
|
Grupo3-TallerUNLP/InfoSquid
|
src/Grupo3TallerUNLP/ConfiguracionBundle/Tests/Controller/ConfiguracionControllerTest.php
|
PHP
|
mit
| 2,024 |
// This file is required by karma.conf.js and loads recursively all the .spec and framework files
import 'zone.js/testing';
import { getTestBed } from '@angular/core/testing';
import {
BrowserDynamicTestingModule,
platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';
declare const require: any;
// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
BrowserDynamicTestingModule,
platformBrowserDynamicTesting()
);
// Then we find all the tests.
const context = require.context('./', true, /\.spec\.ts$/);
// And load the modules.
context.keys().map(context);
|
alxhub/angular
|
aio/src/test.ts
|
TypeScript
|
mit
| 640 |
/**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /*
@author Axel Anceau - 2014
Package api contains general tools
*/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/
package api
import (
"fmt"
"github.com/revel/revel"
"runtime/debug"
)
/**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /*
PanicFilter renders a panic as JSON
@see revel/panic.go
*/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/ /**/
func PanicFilter(c *revel.Controller, fc []revel.Filter) {
defer func() {
if err := recover(); err != nil && err != "HttpException" {
error := revel.NewErrorFromPanic(err)
if error == nil {
revel.ERROR.Print(err, "\n", string(debug.Stack()))
c.Response.Out.WriteHeader(500)
c.Response.Out.Write(debug.Stack())
return
}
revel.ERROR.Print(err, "\n", error.Stack)
c.Result = HttpException(c, 500, fmt.Sprint(err))
}
}()
fc[0](c, fc[1:])
}
|
Peekmo/RPGit
|
api/filters.go
|
GO
|
mit
| 953 |
<?php
namespace SCL\ZF2\Currency\Form\Fieldset;
use Zend\Form\Fieldset;
class TaxedPrice extends Fieldset
{
const AMOUNT_LABEL = 'Amount';
const TAX_LABEL = 'Tax';
public function init()
{
$this->add([
'name' => 'amount',
'type' => 'text',
'options' => [
'label' => self::AMOUNT_LABEL,
]
]);
$this->add([
'name' => 'tax',
'type' => 'text',
'options' => [
'label' => self::TAX_LABEL,
]
]);
}
}
|
SCLInternet/SclZfCurrency
|
src/SCL/ZF2/Currency/Form/Fieldset/TaxedPrice.php
|
PHP
|
mit
| 581 |
var indexController = require('./controllers/cIndex');
var usuarioController = require('./controllers/cUsuario');
var clientesController = require('./controllers/cCliente');
var adminController = require('./controllers/cAdmin');
var umedController = require('./controllers/cUmed');
var matepController = require('./controllers/cMatep');
var empleController = require('./controllers/cEmple');
var accesosController = require('./controllers/cAccesos');
var cargoController = require('./controllers/cCargos');
var reactoController = require('./controllers/cReacto');
var lineasController = require('./controllers/cLineas');
var prodController = require('./controllers/cProd');
var envasesController = require('./controllers/cEnvases');
var tanquesController = require('./controllers/cTanques');
var ubicaController = require('./controllers/cUbica');
var recetaController = require('./controllers/cReceta');
var remitosController = require('./controllers/cRemitos');
var progController = require('./controllers/cProgramacion');
var FormEnReactorController = require('./controllers/cFormEnReactor');
var labController = require('./controllers/cLab');
var formController = require('./controllers/cFormulados');
var mEventos = require('./models/mEventos');
var consuController = require('./controllers/cConsumibles');
var produccionController = require('./controllers/cProduccion');
var fraccionadoController = require('./controllers/cFraccionado');
var aprobacionController = require('./controllers/cAprobacion');
var navesController = require('./controllers/cNaves');
var mapaController = require('./controllers/cMapa');
function logout (req, res) {
fecha = new Date();
day = fecha.getDate();
month = fecha.getMonth();
if (day<10)
day = "0" + day;
if (month<10)
month = "0" + month;
fecha = fecha.getFullYear() + "/"+month+"/"+day+" "+fecha.getHours()+":"+fecha.getMinutes()
mEventos.add(req.session.user.unica, fecha, "Logout", "", function(){
});
req.session = null;
return res.redirect('/');
}
// Verifica que este logueado
function auth (req, res, next) {
if (req.session.auth) {
return next();
} else {
console.log("dentro del else del auth ")
return res.redirect('/')
}
}
module.exports = function(app) {
app.get('/', adminController.getLogin);
app.get('/login', adminController.getLogin)
app.post('/login', adminController.postLogin);
app.get('/logout', logout);
app.get('/inicio', auth, indexController.getInicio);
app.get('/error', indexController.getError);
//ayuda
app.get('/ayuda', indexController.getAyuda);
app.get('/ayudaver/:id', indexController.AyudaVer);
//novedades
app.get('/listanovedades', indexController.getNovedades);
//usuarios
app.get('/usuarioslista', auth, usuarioController.getUsuarios);
app.get('/usuariosalta', auth, usuarioController.getUsuariosAlta);
app.post('/usuariosalta', auth, usuarioController.putUsuario);
app.get('/usuariosmodificar/:id', auth, usuarioController.getUsuarioModificar);
app.post('/usuariosmodificar', auth, usuarioController.postUsuarioModificar);
app.get('/usuariosborrar/:id', auth, usuarioController.getDelUsuario);
//configurar accesos
app.get('/accesoslista/:id', auth, accesosController.getAccesos);
app.post('/accesoslista', auth, accesosController.postAccesos);
//clientes
app.get('/clienteslista', auth, clientesController.getClientes);
app.get('/clientesalta', auth, clientesController.getClientesAlta);
app.post('/clientesalta', auth, clientesController.putCliente);
app.get('/clientesmodificar/:id', auth, clientesController.getClienteModificar);
app.post('/clientesmodificar', auth, clientesController.postClienteModificar);
app.get('/clientesborrar/:id', auth, clientesController.getDelCliente);
app.get('/:cliente/materiasprimas', auth, clientesController.getMatep);
//unidades de medida "umed"
app.get('/umedlista', auth, umedController.getAllUmed);
app.get('/umedalta', auth, umedController.getAlta);
app.post('/umedalta', auth, umedController.postAlta);
app.get('/umedmodificar/:id', auth, umedController.getModificar);
app.post('/umedactualizar', auth, umedController.postModificar);
app.get('/umedborrar/:id', auth, umedController.getDelUmed);
//materias primas por cliente
app.get('/mateplista/:cdcliente', auth, matepController.getAllMatepPorCliente);
app.get('/matepalta/:cdcliente', auth, matepController.getAlta);
app.post('/matepalta', auth, matepController.postAlta);
app.get('/matepmodificar/:id', auth, matepController.getModificar);
app.post('/matepmodificar', auth, matepController.postModificar);
app.get('/matepborrar/:id', auth, matepController.getDelMatep);
//cantidad maxima en tanque por matep
app.get('/formenreactor/:id', auth, FormEnReactorController.getFormEnReactor);
app.get('/formenreactoralta/:idform', auth, FormEnReactorController.getAlta);
app.post('/formenreactoralta', auth, FormEnReactorController.postAlta);
app.get('/formenreactormodificar/:id', auth, FormEnReactorController.getModificar);
app.post('/formenreactormodificar', auth, FormEnReactorController.postModificar);
app.get('/formenreactorborrar/:id', auth, FormEnReactorController.del);
//producto por clientereactor
app.get('/prodlista/:cdcliente', auth, prodController.getAllProdPorCliente);
app.get('/prodalta/:cdcliente', auth, prodController.getAlta);
app.post('/prodalta', auth, prodController.postAlta);
app.get('/prodmodificar/:id', auth, prodController.getModificar);
app.post('/prodmodificar', auth, prodController.postModificar);
app.get('/prodborrar/:id', auth, prodController.getDelProd);
app.get('/:idprod/ablote', auth, prodController.getAbLote);
//empleados
app.get('/emplelista', auth, empleController.getEmpleados);
app.get('/emplealta', auth, empleController.getAlta);
app.post('/emplealta', auth, empleController.postAlta);
app.get('/emplemodificar/:codigo', auth, empleController.getModificar);
app.post('/emplemodificar', auth, empleController.postModificar);
app.get('/empleborrar/:codigo', auth, empleController.getDelEmple);
//cargos de empleados
app.get('/cargoslista', auth, cargoController.getAllCargos);
app.get('/cargosalta', auth, cargoController.getAlta);
app.post('/cargosalta', auth, cargoController.postAlta);
app.get('/cargosmodificar/:id', auth, cargoController.getModificar);
app.post('/cargosmodificar', auth, cargoController.postModificar);
app.get('/cargosborrar/:id', auth, cargoController.getDelCargo);
//reactores
app.get('/reactolista', auth, reactoController.getAll);
app.get('/reactoalta', auth, reactoController.getAlta);
app.post('/reactoalta', auth, reactoController.postAlta);
app.get('/reactomodificar/:id', auth, reactoController.getModificar);
app.post('/reactomodificar', auth, reactoController.postModificar);
app.get('/reactoborrar/:id', auth, reactoController.getDel);
//lineas
app.get('/lineaslista', auth, lineasController.getAll);
app.get('/lineasalta', auth, lineasController.getAlta);
app.post('/lineasalta', auth, lineasController.postAlta);
app.get('/lineasmodificar/:id', auth, lineasController.getModificar);
app.post('/lineasmodificar', auth, lineasController.postModificar);
app.get('/lineasborrar/:id', auth, lineasController.getDel);
//envases
app.get('/envaseslista', auth, envasesController.getAll);
app.get('/envasesalta', auth, envasesController.getAlta);
app.post('/envasesalta', auth, envasesController.postAlta);
app.get('/envasesmodificar/:id', auth, envasesController.getModificar);
app.post('/envasesmodificar', auth, envasesController.postModificar);
app.get('/envasesborrar/:id', auth, envasesController.getDel);
app.get('/capacidadenvase/:id', auth, envasesController.getCapacidad);
//tanques
app.get('/tanqueslista', auth, tanquesController.getAll);
app.get('/tanquesalta', auth, tanquesController.getAlta);
app.post('/tanquesalta', auth, tanquesController.postAlta);
app.get('/tanquesmodificar/:id', auth, tanquesController.getModificar);
app.post('/tanquesmodificar', auth, tanquesController.postModificar);
app.get('/tanquesborrar/:id', auth, tanquesController.getDel);
//ubicaciones "ubica"
app.get('/ubicalista', auth, ubicaController.getAll);
app.get('/ubicaalta', auth, ubicaController.getAlta);
app.post('/ubicaalta', auth, ubicaController.postAlta);
app.get('/ubicamodificar/:id', auth, ubicaController.getModificar);
app.post('/ubicamodificar', auth, ubicaController.postModificar);
app.get('/ubicaborrar/:id', auth, ubicaController.getDel);
//recetas
app.get('/recetalista/:id', auth, recetaController.getRecetaPorFormulado);
app.get('/recetaalta/:id', auth, recetaController.getAlta);
app.post('/recetaalta', auth, recetaController.postAlta);
app.get('/recetaborrar/:id', auth, recetaController.getDel);
app.get('/recetamodificar/:id', auth, recetaController.getModificar);
app.post('/recetamodificar', auth, recetaController.postModificar);
//remitos
app.get('/remitoslista', auth, remitosController.getAll);
app.get('/remitosalta', auth, remitosController.getAlta);
app.post('/remitosalta', auth, remitosController.postAlta);
app.get('/remitosmodificar/:id', auth, remitosController.getModificar);
app.post('/remitosmodificar', auth, remitosController.postModificar);
app.get('/remitosborrar/:id', auth, remitosController.getDel);
app.get('/buscarremito/:finicio/:ffin', auth, remitosController.getRemitos);
//programacion
app.get('/prog1lista', auth, progController.getAll);
app.get('/prog1alta', auth, progController.getAlta);
app.post('/prog1alta', auth, progController.postAlta);
app.get('/prog2lista', auth, progController.getLista);
app.get('/prog1alta2/:idprog', auth, progController.getAlta2);
app.post('/prog1alta2', auth, progController.postAlta2);
app.get('/prog1/:lote/:anio/:clienteid/:prodid', auth, progController.getCodigo);
app.get('/prog1borrar/:id', auth, progController.getDel);
app.get('/refrescaremito/:idcliente/:idmatep', auth, progController.getRemitos);
app.get('/traerpa/:idform', auth, progController.getPA);
app.get('/buscarprogramaciones/:fecha', auth, progController.getProgramaciones);
app.get('/produccionborrarprogram/:id', auth, progController.getDelProgram);
//laboratorio
app.get('/lab/:idremito', auth, labController.getLab);
app.post('/lab', auth, labController.postLab);
//formulados
app.get('/formuladoalta/:cdcliente', auth, formController.getAlta);
app.post('/formuladoalta', auth, formController.postAlta);
app.get('/formuladolista/:cdcliente', auth, formController.getAllFormuladoPorCliente);
app.get('/formuladomodificar/:id', auth, formController.getModificar);
app.post('/formuladomodificar', auth, formController.postModificar);
app.get('/formuladoborrar/:id', auth, formController.getDelFormulado);
app.get('/:id/formulados', auth, formController.getForms);
app.get('/:idform/ablotee', auth, formController.getAbLote);
//consumibles
app.get('/consumibleslista/:idprod', auth, consuController.getAll);
app.get('/consumiblesalta/:idprod', auth, consuController.getAlta);
app.post('/consumiblesalta', auth, consuController.postAlta);
app.get('/consumiblesborrar/:id', auth, consuController.getDel);
//produccion
app.get('/produccionlista', auth, produccionController.getLista);
app.get('/buscarprogramaciones2/:fi/:ff', auth, produccionController.getProgramaciones);
app.get('/produccionver/:id', auth, produccionController.getVerFormulado);
app.post('/produccionver', auth, produccionController.postDatosFormulado);
app.get('/produccionimprimir/:id', auth, produccionController.getImprimir);
//borrar
//fraccionado
app.get('/fraccionadolista', auth, fraccionadoController.getLista);
app.get('/fraccionadoalta/:id', auth, fraccionadoController.getAlta);
app.post('/fraccionadoalta', auth, fraccionadoController.postAlta);
app.get('/fraccionadomodificar/:id', auth, fraccionadoController.getModificar);
app.post('/fraccionadomodificar', auth, fraccionadoController.postModificar);
//borrar?
//aprobacion
app.get('/aprobacionlista', auth, aprobacionController.getLista);
app.get('/aprobacionver/:id', auth, aprobacionController.getVer);
app.post('/aprobacionver', auth, aprobacionController.postVer);
app.get('/aprobacionimprimir/:id', auth, aprobacionController.getImprimir);
//naves
app.get('/naveslista', auth, navesController.getLista);
//mapa
app.get('/mapaver', auth, mapaController.getMapa);
};
|
IsaacMiguel/ProchemBio
|
routes.js
|
JavaScript
|
mit
| 12,314 |
<?php
/**
* Created by PhpStorm.
* User: tfg
* Date: 25/08/15
* Time: 20:03
*/
namespace AppBundle\Behat;
use Sylius\Bundle\ResourceBundle\Behat\DefaultContext;
class BrowserContext extends DefaultContext
{
/**
* @Given estoy autenticado como :username con :password
*/
public function iAmAuthenticated($username, $password)
{
$this->getSession()->visit($this->generateUrl('fos_user_security_login', [], true));
$this->fillField('_username', $username);
$this->fillField('_password', $password);
$this->pressButton('_submit');
}
/**
* @Then /^presiono "([^"]*)" con clase "([^"]*)"$/
*
* @param string $text
* @param string $class
*/
public function iFollowLinkWithClass($text, $class)
{
$link = $this->getSession()->getPage()->find(
'xpath', sprintf("//*[@class='%s' and contains(., '%s')]", $class, $text)
);
if (!$link) {
throw new ExpectationException(sprintf('Unable to follow the link with class: %s and text: %s', $class, $text), $this->getSession());
}
$link->click();
}
}
|
sergiormb/ritsiga
|
src/AppBundle/Behat/BrowserContext.php
|
PHP
|
mit
| 1,153 |
## Close
### What is the value of the first triangle number to have over five hundred divisors?
print max([len(m) for m in map(lambda k: [n for n in range(1,(k+1)) if k%n == 0], [sum(range(n)) for n in range(1,1000)])])
|
jacksarick/My-Code
|
Python/python challenges/euler/012_divisable_tri_nums.py
|
Python
|
mit
| 219 |
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("Autos4Sale.Data.Models")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Autos4Sale.Data.Models")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[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("280798cb-7923-404f-90bb-e890b732d781")]
// 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")]
|
shopOFF/Autos4Sale
|
Autos4Sale/Data/Autos4Sale.Data.Models/Properties/AssemblyInfo.cs
|
C#
|
mit
| 1,415 |
from errors import *
from manager import SchemaManager
|
Livefyre/pseudonym
|
pseudonym/__init__.py
|
Python
|
mit
| 55 |
<?php
namespace Syrma\WebContainer;
/**
*
*/
interface ServerInterface
{
/**
* Start the server.
*
* @param ServerContextInterface $context
* @param RequestHandlerInterface $requestHandler
*/
public function start(ServerContextInterface $context, RequestHandlerInterface $requestHandler);
/**
* Stop the server.
*/
public function stop();
/**
* The server is avaiable.
*
* Here check requirements
*
* @return bool
*/
public static function isAvaiable();
}
|
syrma-php/web-container
|
src/Syrma/WebContainer/ServerInterface.php
|
PHP
|
mit
| 552 |
module Mailchimp
class API
include HTTParty
format :plain
default_timeout 30
attr_accessor :api_key, :timeout, :throws_exceptions
def initialize(api_key = nil, extra_params = {})
@api_key = api_key || ENV['MAILCHIMP_API_KEY'] || self.class.api_key
@default_params = {:apikey => @api_key}.merge(extra_params)
@throws_exceptions = false
end
def api_key=(value)
@api_key = value
@default_params = @default_params.merge({:apikey => @api_key})
end
def base_api_url
"https://#{dc_from_api_key}api.mailchimp.com/1.3/?method="
end
def valid_api_key?(*args)
"Everything's Chimpy!" == call("ping")
end
protected
def call(method, params = {})
api_url = base_api_url + method
params = @default_params.merge(params)
timeout = params.delete(:timeout) || @timeout
response = self.class.post(api_url, :body => CGI::escape(params.to_json), :timeout => timeout)
begin
response = JSON.parse(response.body)
rescue
response = JSON.parse('['+response.body+']').first
end
if @throws_exceptions && response.is_a?(Hash) && response["error"]
raise "Error from MailChimp API: #{response["error"]} (code #{response["code"]})"
end
response
end
def method_missing(method, *args)
method = method.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase } #Thanks for the gsub, Rails
method = method[0].chr.downcase + method[1..-1].gsub(/aim$/i, 'AIM')
call(method, *args)
end
class << self
attr_accessor :api_key
def method_missing(sym, *args, &block)
new(self.api_key).send(sym, *args, &block)
end
end
def dc_from_api_key
(@api_key.nil? || @api_key.length == 0 || @api_key !~ /-/) ? '' : "#{@api_key.split("-").last}."
end
end
end
|
herimedia/mailchimp-gem
|
lib/mailchimp/api.rb
|
Ruby
|
mit
| 1,894 |
/*
Print.cpp - Base class that provides print() and println()
Copyright (c) 2008 David A. Mellis. All right reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Modified 23 November 2006 by David A. Mellis
Modified 20 Aug 2014 by MediaTek Inc.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include "Arduino.h"
#include "Print.h"
// Public Methods //////////////////////////////////////////////////////////////
/* default implementation: may be overridden */
size_t Print::write(const uint8_t *buffer, size_t size)
{
size_t n = 0;
while (size--) {
n += write(*buffer++);
}
return n;
}
size_t Print::print(const __FlashStringHelper *ifsh)
{
return print(reinterpret_cast<const char *>(ifsh));
}
size_t Print::print(const String &s)
{
return write(s.c_str(), s.length());
}
size_t Print::print(const char str[])
{
return write(str);
}
size_t Print::print(char c)
{
return write(c);
}
size_t Print::print(unsigned char b, int base)
{
return print((unsigned long) b, base);
}
size_t Print::print(int n, int base)
{
return print((long) n, base);
}
size_t Print::print(unsigned int n, int base)
{
return print((unsigned long) n, base);
}
size_t Print::print(long n, int base)
{
if (base == 0) {
return write(n);
} else if (base == 10) {
if (n < 0) {
int t = print('-');
n = -n;
return printNumber(n, 10) + t;
}
return printNumber(n, 10);
} else {
return printNumber(n, base);
}
}
size_t Print::print(unsigned long n, int base)
{
if (base == 0) return write(n);
else return printNumber(n, base);
}
size_t Print::print(double n, int digits)
{
return printFloat(n, digits);
}
size_t Print::println(const __FlashStringHelper *ifsh)
{
size_t n = print(ifsh);
n += println();
return n;
}
size_t Print::print(const Printable& x)
{
return x.printTo(*this);
}
size_t Print::println(void)
{
size_t n = print('\r');
n += print('\n');
return n;
}
size_t Print::println(const String &s)
{
size_t n = print(s);
n += println();
return n;
}
size_t Print::println(const char c[])
{
size_t n = print(c);
n += println();
return n;
}
size_t Print::println(char c)
{
size_t n = print(c);
n += println();
return n;
}
size_t Print::println(unsigned char b, int base)
{
size_t n = print(b, base);
n += println();
return n;
}
size_t Print::println(int num, int base)
{
size_t n = print(num, base);
n += println();
return n;
}
size_t Print::println(unsigned int num, int base)
{
size_t n = print(num, base);
n += println();
return n;
}
size_t Print::println(long num, int base)
{
size_t n = print(num, base);
n += println();
return n;
}
size_t Print::println(unsigned long num, int base)
{
size_t n = print(num, base);
n += println();
return n;
}
size_t Print::println(double num, int digits)
{
size_t n = print(num, digits);
n += println();
return n;
}
size_t Print::println(const Printable& x)
{
size_t n = print(x);
n += println();
return n;
}
#include <stdarg.h>
size_t Print::printf(const char *fmt, ...)
{
va_list args;
char buf[256] = {0};
va_start(args, fmt);
vsprintf(buf, fmt, args);
va_end(args);
return write(buf, strlen(buf));
}
// Private Methods /////////////////////////////////////////////////////////////
size_t Print::printNumber(unsigned long n, uint8_t base) {
char buf[8 * sizeof(long) + 1]; // Assumes 8-bit chars plus zero byte.
char *str = &buf[sizeof(buf) - 1];
*str = '\0';
// prevent crash if called with base == 1
if (base < 2) base = 10;
do {
unsigned long m = n;
n /= base;
char c = m - base * n;
*--str = c < 10 ? c + '0' : c + 'A' - 10;
} while(n);
return write(str);
}
size_t Print::printFloat(double number, uint8_t digits)
{
size_t n = 0;
if (isnan(number)) return print("nan");
if (isinf(number)) return print("inf");
if (number > 4294967040.0) return print ("ovf"); // constant determined empirically
if (number <-4294967040.0) return print ("ovf"); // constant determined empirically
// Handle negative numbers
if (number < 0.0)
{
n += print('-');
number = -number;
}
// Round correctly so that print(1.999, 2) prints as "2.00"
double rounding = 0.5;
for (uint8_t i=0; i<digits; ++i)
rounding /= 10.0;
number += rounding;
// Extract the integer part of the number and print it
unsigned long int_part = (unsigned long)number;
double remainder = number - (double)int_part;
n += print(int_part);
// Print the decimal point, but only if there are digits beyond
if (digits > 0) {
n += print(".");
}
// Extract digits from the remainder one at a time
while (digits-- > 0)
{
remainder *= 10.0;
int toPrint = int(remainder);
n += print(toPrint);
remainder -= toPrint;
}
return n;
}
|
gokr/ardunimo
|
wrapper/src/cores/arduino/Print.cpp
|
C++
|
mit
| 5,552 |
import { Injectable } from '@angular/core';
/**
* Created by AAAA on 3/21/2017.
*/
//http://stackoverflow.com/questions/9671995/javascript-custom-event-listener
//http://www.typescriptlang.org/play/
class MyEvent{
private context:Object;
private cbs: Function[] = [];
constructor(context: Object){
this.context = context;
}
public addListener(cb: Function){
this.cbs.push(cb);
}
public removeListener(cb: Function){
let i = this.cbs.indexOf(cb);
if (i >-1) {
this.cbs.splice(i, 1);
}
}
public removeAllListeners(){
this.cbs=[];
}
public trigger(...args){
this.cbs.forEach(cb => cb.apply(this.context, args))
};
}
class EventContainer{
private events: MyEvent[]= [];
public createEvent(context:Object):MyEvent{
let myEvent = new MyEvent(context);
this.events.push(myEvent);
return myEvent;
}
public removeEvent(myEvent:MyEvent):void{
let i = this.events.indexOf(myEvent);
if (i >-1) {
this.events.splice(i, 1);
}
};
public trigger(...args):void{
this.events.forEach(event => event.trigger(args));
};
}
class LoginEvent extends EventContainer{}
class LogoutEvent extends EventContainer{}
@Injectable()
export class EventsService {
private _loginEvent:LoginEvent;
private _logoutEvent:LogoutEvent;
constructor() {}
get loginEvent():LoginEvent{
if(!this._loginEvent) {
this._loginEvent = new LoginEvent();
}
return this._loginEvent;
}
get logoutEvent():LogoutEvent{
if(!this._logoutEvent) {
this._logoutEvent = new LogoutEvent();
}
return this._logoutEvent;
}
}
|
caohonghiep/lkth
|
src/app/services/events.service.ts
|
TypeScript
|
mit
| 1,639 |
import random
from datetime import datetime
from multiprocessing import Pool
import numpy as np
from scipy.optimize import minimize
def worker_func(args):
self = args[0]
m = args[1]
k = args[2]
r = args[3]
return (self.eval_func(m, k, r) -
self.eval_func(m, k, self.rt) -
self.temporal_diff_sum(m, k)) ** 2
def optimized_func_i_der(args):
"""
The derivative of the optimized function with respect to the
ith component of the vector r
"""
self = args[0]
r = args[1]
i = args[2]
result = 0
M = len(self.data)
for m in range(M):
Nm = self.data[m].shape[0] - 1
for k in range(Nm + 1):
result += ((self.eval_func(m, k, r) -
self.eval_func(m, k, self.rt) -
self.temporal_diff_sum(m, k)) * 2 *
self.eval_func_der(m, k, r, i))
return result
def worker_func_der(args):
self = args[0]
m = args[1]
k = args[2]
r = args[3]
i = args[4]
return ((self.eval_func(m, k, r) -
self.eval_func(m, k, self.rt) -
self.temporal_diff_sum(m, k)) * 2 *
self.eval_func_der(m, k, r, i))
class Agent:
num_features = 22
def __init__(self):
self.lf = 0.2 # Learning factor lambda
self.data = [] # The features' values for all the games
self.rewards = [] # Reward values for moving from 1 state to the next
self.rt = np.array([])
self.max_iter = 50
def set_learning_factor(self, learning_factor):
assert(learning_factor >= 0 and learning_factor <= 1)
self.lf = learning_factor
def set_rt(self, rt):
assert(len(rt) == self.num_features)
self.rt = rt
def set_iter(self, max_iter):
self.max_iter = max_iter
def set_data(self, data):
self.data = []
self.rewards = []
for game in data:
game = np.vstack((game, np.zeros(self.num_features + 1)))
self.data.append(game[:, :-1])
self.rewards.append(game[:, -1:])
def eval_func(self, m, k, r):
"""
The evaluation function value for the set of weights (vector) r
at the mth game and kth board state """
return np.dot(r, self.data[m][k])
def eval_func_der(self, m, k, r, i):
"""
Find the derivative of the evaluation function with respect
to the ith component of the vector r
"""
return self.data[m][k][i]
def get_reward(self, m, s):
"""
Get reward for moving from state s to state (s + 1)
"""
return self.rewards[m][s + 1][0]
def temporal_diff(self, m, s):
"""
The temporal diffence value for state s to state (s+1) in the mth game
"""
return (self.get_reward(m, s) + self.eval_func(m, s + 1, self.rt) -
self.eval_func(m, s, self.rt))
def temporal_diff_sum(self, m, k):
Nm = self.data[m].shape[0] - 1
result = 0
for s in range(k, Nm):
result += self.lf**(s - k) * self.temporal_diff(m, s)
return result
def optimized_func(self, r):
result = 0
M = len(self.data)
pool = Pool(processes=4)
for m in range(M):
Nm = self.data[m].shape[0] - 1
k_args = range(Nm + 1)
self_args = [self] * len(k_args)
m_args = [m] * len(k_args)
r_args = [r] * len(k_args)
result += sum(pool.map(worker_func,
zip(self_args, m_args, k_args, r_args)))
return result
def optimized_func_i_der(self, r, i):
"""
The derivative of the optimized function with respect to the
ith component of the vector r
"""
result = 0
M = len(self.data)
for m in range(M):
Nm = self.data[m].shape[0] - 1
for k in range(Nm + 1):
result += ((self.eval_func(m, k, r) -
self.eval_func(m, k, self.rt) -
self.temporal_diff_sum(m, k)) * 2 *
self.eval_func_der(m, k, r, i))
return result
def optimized_func_der(self, r):
p = Pool(processes=4)
self_args = [self] * len(r)
i_args = range(len(r))
r_args = [r] * len(r)
return np.array(p.map(optimized_func_i_der,
zip(self_args, r_args, i_args)))
def callback(self, r):
print("Iteration %d completed at %s" %
(self.cur_iter, datetime.now().strftime("%d/%m/%Y %H:%M:%S")))
self.cur_iter += 1
def compute_next_rt(self):
print("Start computing at %s" %
(datetime.now().strftime("%d/%m/%Y %H:%M:%S")))
self.cur_iter = 1
r0 = np.array([random.randint(-10, 10)
for i in range(self.num_features)])
res = minimize(self.optimized_func, r0, method='BFGS',
jac=self.optimized_func_der,
options={'maxiter': self.max_iter, 'disp': True},
callback=self.callback)
return res.x
|
ndt93/tetris
|
scripts/agent3.py
|
Python
|
mit
| 5,234 |
RSpec.describe Porch::ProcStepDecorator do
describe ".decorates?" do
it "returns true if the step is a proc" do
expect(described_class).to be_decorates Proc.new {}
end
it "returns true if the step is a lambda" do
expect(described_class).to be_decorates lambda {}
end
it "returns false if the step is a class" do
expect(described_class).to_not be_decorates Object
end
end
describe "#execute" do
let(:context) { Hash.new }
let(:organizer) { double(:organizer) }
let(:step) { Proc.new {} }
subject { described_class.new step, organizer }
it "calls the proc with the context" do
expect(step).to receive(:call).with(context)
subject.execute context
end
end
end
|
jwright/porch
|
spec/porch/step_decorators/proc_step_decorator_spec.rb
|
Ruby
|
mit
| 747 |
# -*- coding: utf-8 -*-
""""
ProjectName: pydemi
Repo: https://github.com/chrisenytc/pydemi
Copyright (c) 2014 Christopher EnyTC
Licensed under the MIT license.
"""
# Dependencies
import uuid
from api import app
from hashlib import sha1
from flask import request
from flask import jsonify as JSON
from api.models.user import User
from cors import cors
@app.route('/signup', methods=['POST'])
@cors(origin='*', methods=['POST'])
def signup():
# Create new user
new_user = User()
new_user.name = request.form['name']
new_user.email = request.form['email']
new_user.password = sha1(request.form['password']).hexdigest()
new_user.token = str(uuid.uuid4())
new_user.save()
return JSON(message='User created successfully')
@app.route('/signin', methods=['POST'])
@cors(origin='*', methods=['POST'])
def signin():
# Retorna a user data
user_info = User.objects(email=request.form['email'], password=sha1(
request.form['password']).hexdigest())
if user_info.count():
return JSON(token=user_info.get().token, roles=user_info.get().roles)
else:
return JSON(message='User not found')
|
chrisenytc/pydemi
|
api/controllers/users.py
|
Python
|
mit
| 1,151 |
using System.Web;
using System.Web.Optimization;
namespace WebAPI.Boilerplate.Api
{
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
}
}
}
|
Manoj-Bisht/WebAPI-Boilerplate
|
WebAPI.Boilerplate.Api/App_Start/BundleConfig.cs
|
C#
|
mit
| 1,123 |
package redes3.proyecto.nagiosalert;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class InfoServiceActivity extends Activity {
String nombre;
int status;
String duracion;
String revision;
String info;
ImageView image ;
TextView tvNombre ;
TextView tvStatus ;
TextView tvDuracion ;
TextView tvRevision ;
TextView tvInfo ;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info_service);
nombre = new String();
status = 0 ;
duracion = new String();
revision = new String();
info = new String();
image = (ImageView) findViewById(R.id.image);
tvNombre = (TextView)this.findViewById(R.id.tvNombreServicio);
tvStatus = (TextView)this.findViewById(R.id.status);
tvDuracion = (TextView)this.findViewById(R.id.duracion);
tvRevision = (TextView)this.findViewById(R.id.revision);
tvInfo = (TextView)this.findViewById(R.id.info);
Bundle extras = getIntent().getExtras();
nombre = extras.getString("nombre");
status = extras.getInt("status");
duracion = extras.getString("duracion");
revision = extras.getString("revision");
info = extras.getString("info");
tvNombre.setText(nombre);
tvDuracion.setText("Duracion : \n"+duracion);
tvRevision.setText("Revision : \n"+revision);
tvInfo.setText("Descripción : \n"+info);
if(status== 0){
tvStatus.setText("Estado : \nOk");
image.setImageResource(R.drawable.fine);
}else if(status== 1){
tvStatus.setText("Estado : \nFail");
image.setImageResource(R.drawable.fail);
}if(status== 2){
tvStatus.setText("Estado : \nWarning");
image.setImageResource(R.drawable.warning);
}if(status== 3){
tvStatus.setText("Estado : \nUnknown");
image.setImageResource(R.drawable.unknown);
}
}
}
|
caat91/NagiosAlert
|
NagiosAlert-App/src/redes3/proyecto/nagiosalert/InfoServiceActivity.java
|
Java
|
mit
| 2,141 |
#include "MultiSelection.h"
#include "ofxCogEngine.h"
#include "EnumConverter.h"
#include "Node.h"
namespace Cog {
void MultiSelection::Load(Setting& setting) {
string group = setting.GetItemVal("selection_group");
if (group.empty()) CogLogError("MultiSelection", "Error while loading MultiSelection behavior: expected parameter selection_group");
this->selectionGroup = StrId(group);
// load all attributes
string defaultImg = setting.GetItemVal("default_img");
string selectedImg = setting.GetItemVal("selected_img");
if (!defaultImg.empty() && !selectedImg.empty()) {
this->defaultImg = CogGet2DImage(defaultImg);
this->selectedImg = CogGet2DImage(selectedImg);
}
else {
string defaultColorStr = setting.GetItemVal("default_color");
string selectedColorStr = setting.GetItemVal("selected_color");
if (!defaultColorStr.empty() && !selectedColorStr.empty()) {
this->defaultColor = EnumConverter::StrToColor(defaultColorStr);
this->selectedColor = EnumConverter::StrToColor(selectedColorStr);
}
}
}
void MultiSelection::OnInit() {
SubscribeForMessages(ACT_OBJECT_HIT_ENDED, ACT_STATE_CHANGED);
}
void MultiSelection::OnStart() {
CheckState();
owner->SetGroup(selectionGroup);
}
void MultiSelection::OnMessage(Msg& msg) {
if (msg.HasAction(ACT_OBJECT_HIT_ENDED) && msg.GetContextNode()->IsInGroup(selectionGroup)) {
// check if the object has been clicked (user could hit a different area and release touch over the button)
auto evt = msg.GetDataPtr<InputEvent>();
if (evt->input->handlerNodeId == msg.GetContextNode()->GetId()) {
ProcessHit(msg, false);
}
}
else if (msg.HasAction(ACT_STATE_CHANGED) && msg.GetContextNode()->IsInGroup(selectionGroup)) {
ProcessHit(msg, true); // set directly, because STATE_CHANGED event has been already invoked
}
}
void MultiSelection::ProcessHit(Msg& msg, bool setDirectly) {
if (msg.GetContextNode()->GetId() == owner->GetId()) {
// selected actual node
if (!owner->HasState(selectedState)) {
if (setDirectly) owner->GetStates().SetState(selectedState);
else owner->SetState(selectedState);
SendMessage(ACT_OBJECT_SELECTED);
CheckState();
}
else {
CheckState();
}
}
else {
if (owner->HasState(selectedState)) {
if (setDirectly) owner->GetStates().ResetState(selectedState);
else owner->ResetState(selectedState);
CheckState();
}
}
}
void MultiSelection::CheckState() {
if (owner->HasState(selectedState)) {
if (selectedImg) {
owner->GetMesh<Image>()->SetImage(selectedImg);
}
else {
owner->GetMesh()->SetColor(selectedColor);
}
}
else if (!owner->HasState(selectedState)) {
if (defaultImg) {
owner->GetMesh<Image>()->SetImage(defaultImg);
}
else {
owner->GetMesh()->SetColor(defaultColor);
}
}
}
}// namespace
|
dormantor/ofxCogEngine
|
COGengine/src/Behaviors/MultiSelection.cpp
|
C++
|
mit
| 2,863 |
// The MIT License (MIT)
//
// Copyright (c) 2016 Tim Jones
//
// 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 io.github.jonestimd.finance.file;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import io.github.jonestimd.finance.domain.transaction.Transaction;
import io.github.jonestimd.finance.swing.transaction.TransactionTableModel;
import static io.github.jonestimd.util.JavaPredicates.*;
public class Reconciler {
private final TransactionTableModel tableModel;
private final List<Transaction> uncleared;
public Reconciler(TransactionTableModel tableModel) {
this.tableModel = tableModel;
this.uncleared = tableModel.getBeans().stream()
.filter(not(Transaction::isCleared)).filter(not(Transaction::isNew))
.collect(Collectors.toList());
}
public void reconcile(Collection<Transaction> transactions) {
transactions.forEach(this::reconcile);
}
private void reconcile(Transaction transaction) {
Transaction toClear = select(transaction);
if (toClear.isNew()) {
toClear.setCleared(true);
tableModel.queueAdd(tableModel.getBeanCount()-1, toClear);
}
else {
tableModel.setValueAt(true, tableModel.rowIndexOf(toClear), tableModel.getClearedColumn());
}
}
private Transaction select(Transaction transaction) {
return uncleared.stream().filter(sameProperties(transaction)).min(nearestDate(transaction)).orElse(transaction);
}
private Predicate<Transaction> sameProperties(Transaction transaction) {
return t2 -> transaction.getAmount().compareTo(t2.getAmount()) == 0
&& transaction.getAssetQuantity().compareTo(t2.getAssetQuantity()) == 0
&& Objects.equals(transaction.getPayee(), t2.getPayee())
&& Objects.equals(transaction.getSecurity(), t2.getSecurity());
}
private Comparator<Transaction> nearestDate(Transaction transaction) {
return Comparator.comparingInt(t -> transaction.getDate().compareTo(t.getDate()));
}
}
|
jonestimd/finances
|
src/main/java/io/github/jonestimd/finance/file/Reconciler.java
|
Java
|
mit
| 3,250 |
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class AddTemplatesToEvents extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('events', function (Blueprint $table) {
$table->string('template')->default('show');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('events', function ($table) {
$table->dropColumn('template');
});
}
}
|
ayimdomnic/Qicksite
|
src/PublishedAssets/Migrations/2016_03_20_186046_add_templates_to_events.php
|
PHP
|
mit
| 605 |
package plugin_test
import (
"path/filepath"
"code.cloudfoundry.org/cli/utils/testhelpers/pluginbuilder"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
)
func TestPlugin(t *testing.T) {
RegisterFailHandler(Fail)
pluginbuilder.BuildTestBinary(filepath.Join("..", "fixtures", "plugins"), "test_1")
RunSpecs(t, "Plugin Suite")
}
|
jabley/cf-metrics
|
vendor/src/code.cloudfoundry.org/cli/plugin/plugin_suite_test.go
|
GO
|
mit
| 355 |
var express = require('express'),
compression = require('compression'),
path = require('path'),
favicon = require('serve-favicon'),
logger = require('morgan'),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser'),
session = require('express-session'),
session = require('express-session'),
flash = require('connect-flash'),
moment = require('moment'),
mongoose = require('mongoose'),
MongoStore = require('connect-mongo')(session),
Pclog = require('./models/pclog.js'),
configDB = require('./config/database.js');
mongoose.Promise = global.Promise = require('bluebird');
mongoose.connect(configDB.uri);
var routes = require('./routes/index'),
reports = require('./routes/reports'),
statistics = require('./routes/statistics'),
charts = require('./routes/charts'),
logs = require('./routes/logs'),
organization = require('./routes/organization'),
users = require('./routes/users');
var app = express();
//var rootFolder = __dirname;
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(compression());
// uncomment after placing your favicon in /public
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
secret: 'safe_session_cat',
resave: true,
rolling: true,
saveUninitialized: false,
cookie: {secure: false, maxAge: 900000},
store: new MongoStore({ url: configDB.uri })
}));
app.use(flash());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', function(req,res,next){
app.locals.currentUrl = req.path;
app.locals.moment = moment;
res.locals.messages = require('express-messages')(req, res);
if(req.session & req.session.user){
app.locals.user = req.session.user;
}
console.log(app.locals.user);
next();
});
app.use('/', routes);
app.use('/reports', reports);
app.use('/statistics', statistics);
app.use('/charts', charts);
app.use('/logs', logs);
app.use('/organization', organization);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Page Not Found.');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
// if (app.get('env') === 'development') {
// app.use(function(err, req, res, next) {
// res.status(err.status || 500);
// res.render('error', {
// message: err.message,
// error: err
// });
// });
// }
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
if(err.status){
res.status(err.status);
}else{
err.status = 500;
err.message = "Internal Server Error."
res.status(500);
}
res.render('404', {error: err});
});
module.exports = app;
|
EdmonJiang/FA_Inventory
|
app.js
|
JavaScript
|
mit
| 2,979 |
/**
* CircularLinkedList implementation
* @author Tyler Smith
* @version 1.0
*/
public class CircularLinkedList<T> implements LinkedListInterface<T> {
private Node<T> head = null, tail = head;
private int size = 0;
@Override
public void addAtIndex(int index, T data) {
if (index < 0 || index > this.size()) {
throw new IndexOutOfBoundsException();
}
if (index == 0) {
this.addToFront(data);
} else if (index == this.size()) {
this.addToBack(data);
} else {
Node<T> current = head;
if (index == 1) {
current.setNext(new Node<T>(data, current.getNext()));
} else {
for (int i = 0; i < index - 1; i++) {
current = current.getNext();
}
Node<T> temp = current;
current = new Node<T>(data, temp);
}
size++;
}
}
@Override
public T get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
Node<T> current = head;
for (int i = 0; i < index; i++) {
current = current.getNext();
}
return current.getData();
}
@Override
public T removeAtIndex(int index) {
if (index < 0 || index >= this.size()) {
throw new IndexOutOfBoundsException();
}
if (index == 0) {
T data = head.getData();
head = head.getNext();
tail.setNext(head);
size--;
return data;
} else {
Node<T> before = tail;
Node<T> current = head;
for (int i = 0; i < index; i++) {
before = current;
current = current.getNext();
}
T data = current.getData();
before.setNext(current.getNext());
size--;
return data;
}
}
@Override
public void addToFront(T t) {
if (this.isEmpty()) {
head = new Node<T>(t, tail);
tail = head;
tail.setNext(head);
size++;
return;
}
Node<T> node = new Node<T>(t, head);
head = node;
tail.setNext(head);
size++;
}
@Override
public void addToBack(T t) {
if (this.isEmpty()) {
tail = new Node<T>(t);
head = tail;
tail.setNext(head);
head.setNext(tail);
size++;
} else {
Node<T> temp = tail;
tail = new Node<T>(t, head);
temp.setNext(tail);
size++;
}
}
@Override
public T removeFromFront() {
if (this.isEmpty()) {
return null;
}
Node<T> ret = head;
head = head.getNext();
tail.setNext(head);
size--;
return ret.getData();
}
@Override
public T removeFromBack() {
if (this.isEmpty()) {
return null;
}
Node<T> iterate = head;
while (iterate.getNext() != tail) {
iterate = iterate.getNext();
}
iterate.setNext(head);
Node<T> ret = tail;
tail = iterate;
size--;
return ret.getData();
}
@SuppressWarnings("unchecked")
@Override
public T[] toList() {
Object[] list = new Object[this.size()];
int i = 0;
Node<T> current = head;
while (i < this.size()) {
list[i] = current.getData();
current = current.getNext();
i++;
}
return ((T[]) list);
}
@Override
public boolean isEmpty() {
return (this.size() == 0);
}
@Override
public int size() {
return size;
}
@Override
public void clear() {
head = null;
tail = null;
size = 0;
}
/**
* Reference to the head node of the linked list.
* Normally, you would not do this, but we need it
* for grading your work.
*
* @return Node representing the head of the linked list
*/
public Node<T> getHead() {
return head;
}
/**
* Reference to the tail node of the linked list.
* Normally, you would not do this, but we need it
* for grading your work.
*
* @return Node representing the tail of the linked list
*/
public Node<T> getTail() {
return tail;
}
/**
* This method is for your testing purposes.
* You may choose to implement it if you wish.
*/
@Override
public String toString() {
return "";
}
}
|
tsmith328/Homework
|
Java/CS 1332/Homework 01/CircularLinkedList.java
|
Java
|
mit
| 4,722 |
import { Component, OnInit } from '@angular/core';
// import { TreeModule, TreeNode } from "primeng/primeng";
import { BlogPostService } from '../shared/blog-post.service';
import { BlogPostDetails } from '../shared/blog-post.model';
@Component({
selector: 'ejc-blog-archive',
templateUrl: './blog-archive.component.html',
styleUrls: ['./blog-archive.component.scss']
})
export class BlogArchiveComponent implements OnInit {
constructor(
// private postService: BlogPostService
) { }
ngOnInit() {
}
// // it would be best if the data in the blog post details file was already organized into tree nodes
// private buildTreeNodes(): TreeNode[] {}
}
|
ejchristie/ejchristie.github.io
|
src/app/blog/blog-archive/blog-archive.component.ts
|
TypeScript
|
mit
| 676 |
require 'active_record'
module ActiveRecord
class Migration
def migrate_with_multidb(direction)
if defined? self.class::DATABASE_NAME
ActiveRecord::Base.establish_connection(self.class::DATABASE_NAME.to_sym)
migrate_without_multidb(direction)
ActiveRecord::Base.establish_connection(Rails.env.to_sym)
else
migrate_without_multidb(direction)
end
end
alias_method_chain :migrate, :multidb
end
end
|
sinsoku/banana
|
lib/banana/migration.rb
|
Ruby
|
mit
| 462 |
const os = require("os");
const fs = require("fs");
const config = {
}
let libs;
switch (os.platform()) {
case "darwin": {
libs = [
"out/Debug_x64/libpvpkcs11.dylib",
"out/Debug/libpvpkcs11.dylib",
"out/Release_x64/libpvpkcs11.dylib",
"out/Release/libpvpkcs11.dylib",
];
break;
}
case "win32": {
libs = [
"out/Debug_x64/pvpkcs11.dll",
"out/Debug/pvpkcs11.dll",
"out/Release_x64/pvpkcs11.dll",
"out/Release/pvpkcs11.dll",
];
break;
}
default:
throw new Error("Cannot get pvpkcs11 compiled library. Unsupported OS");
}
config.lib = libs.find(o => fs.existsSync(o));
if (!config.lib) {
throw new Error("config.lib is empty");
}
module.exports = config;
|
PeculiarVentures/pvpkcs11
|
test/config.js
|
JavaScript
|
mit
| 742 |
class RenameMembers < ActiveRecord::Migration[5.1]
def change
rename_table :members, :memberships
end
end
|
miljinx/helpdo-api
|
db/migrate/20170613234831_rename_members.rb
|
Ruby
|
mit
| 114 |
<?php
# MantisBT - a php based bugtracking system
# MantisBT 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 2 of the License, or
# (at your option) any later version.
#
# MantisBT 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 MantisBT. If not, see <http://www.gnu.org/licenses/>.
/**
* @package MantisBT
* @copyright Copyright (C) 2000 - 2002 Kenzaburo Ito - kenito@300baud.org
* @copyright Copyright (C) 2002 - 2011 MantisBT Team - mantisbt-dev@lists.sourceforge.net
* @link http://www.mantisbt.org
*/
/**
* MantisBT Core API's
*/
require_once( 'core.php' );
require_once( 'email_api.php' );
form_security_validate( 'signup' );
$f_username = strip_tags( gpc_get_string( 'username' ) );
$f_email = strip_tags( gpc_get_string( 'email' ) );
$f_captcha = gpc_get_string( 'captcha', '' );
$f_public_key = gpc_get_int( 'public_key', '' );
$f_username = trim( $f_username );
$f_email = email_append_domain( trim( $f_email ) );
$f_captcha = utf8_strtolower( trim( $f_captcha ) );
# force logout on the current user if already authenticated
if( auth_is_user_authenticated() ) {
auth_logout();
}
# Check to see if signup is allowed
if ( OFF == config_get_global( 'allow_signup' ) ) {
print_header_redirect( 'login_page.php' );
exit;
}
if( ON == config_get( 'signup_use_captcha' ) && get_gd_version() > 0 &&
helper_call_custom_function( 'auth_can_change_password', array() ) ) {
# captcha image requires GD library and related option to ON
$t_key = utf8_strtolower( utf8_substr( md5( config_get( 'password_confirm_hash_magic_string' ) . $f_public_key ), 1, 5) );
if ( $t_key != $f_captcha ) {
trigger_error( ERROR_SIGNUP_NOT_MATCHING_CAPTCHA, ERROR );
}
}
email_ensure_not_disposable( $f_email );
# notify the selected group a new user has signed-up
if( user_signup( $f_username, $f_email ) ) {
email_notify_new_account( $f_username, $f_email );
}
form_security_purge( 'signup' );
html_page_top1();
html_page_top2a();
?>
<br />
<div align="center">
<table class="width50" cellspacing="1">
<tr>
<td class="center">
<b><?php echo lang_get( 'signup_done_title' ) ?></b><br />
<?php echo "[$f_username - $f_email] " ?>
</td>
</tr>
<tr>
<td>
<br />
<?php echo lang_get( 'password_emailed_msg' ) ?>
<br /><br />
<?php echo lang_get( 'no_reponse_msg') ?>
<br /><br />
</td>
</tr>
</table>
<br />
<?php print_bracket_link( 'login_page.php', lang_get( 'proceed' ) ); ?>
</div>
<?php
html_page_bottom1a( __FILE__ );
|
eazulay/mantis
|
signup.php
|
PHP
|
mit
| 2,896 |
team_mapping = {
"SY": "Sydney",
"WB": "Western Bulldogs",
"WC": "West Coast",
"HW": "Hawthorn",
"GE": "Geelong",
"FR": "Fremantle",
"RI": "Richmond",
"CW": "Collingwood",
"CA": "Carlton",
"GW": "Greater Western Sydney",
"AD": "Adelaide",
"GC": "Gold Coast",
"ES": "Essendon",
"ME": "Melbourne",
"NM": "North Melbourne",
"PA": "Port Adelaide",
"BL": "Brisbane Lions",
"SK": "St Kilda"
}
def get_team_name(code):
return team_mapping[code]
def get_team_code(full_name):
for code, name in team_mapping.items():
if name == full_name:
return code
return full_name
def get_match_description(response):
match_container = response.xpath("//td[@colspan = '5' and @align = 'center']")[0]
match_details = match_container.xpath(".//text()").extract()
return {
"round": match_details[1],
"venue": match_details[3],
"date": match_details[6],
"attendance": match_details[8],
"homeTeam": response.xpath("(//a[contains(@href, 'teams/')])[1]/text()").extract_first(),
"awayTeam": response.xpath("(//a[contains(@href, 'teams/')])[2]/text()").extract_first(),
"homeScore": int(response.xpath("//table[1]/tr[2]/td[5]/b/text()").extract_first()),
"awayScore": int(response.xpath("//table[1]/tr[3]/td[5]/b/text()").extract_first())
}
def get_match_urls(response):
for match in response.xpath("//a[contains(@href, 'stats/games/')]/@href").extract():
yield response.urljoin(match)
|
bairdj/beveridge
|
src/scrapy/afltables/afltables/common.py
|
Python
|
mit
| 1,563 |
from keras.applications import imagenet_utils
from keras.applications import mobilenet
def dummyPreprocessInput(image):
image -= 127.5
return image
def getPreprocessFunction(preprocessType):
if preprocessType == "dummy":
return dummyPreprocessInput
elif preprocessType == "mobilenet":
return mobilenet.preprocess_input
elif preprocessType == "imagenet":
return imagenet_utils.preprocess_input
else:
raise Exception(preprocessType + " not supported")
|
SlipknotTN/Dogs-Vs-Cats-Playground
|
deep_learning/keras/lib/preprocess/preprocess.py
|
Python
|
mit
| 511 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace TheS.Runtime
{
internal class CallbackException : FatalException
{
public CallbackException()
{
}
public CallbackException(string message, Exception innerException) : base(message, innerException)
{
// This can't throw something like ArgumentException because that would be worse than
// throwing the callback exception that was requested.
Fx.Assert(innerException != null, "CallbackException requires an inner exception.");
Fx.Assert(!Fx.IsFatal(innerException), "CallbackException can't be used to wrap fatal exceptions.");
}
}
}
|
teerachail/SoapWithAttachments
|
JavaWsBinding/TheS.ServiceModel/_Runtime/CallbackException.cs
|
C#
|
mit
| 874 |
<?php
namespace App\Http\Controllers;
use App\Jobs\GetInstance;
use App\Models\Build;
use App\Models\Commit;
use App\Models\Repository;
use App\RepositoryProviders\GitHub;
use Illuminate\Support\Facades\DB;
class DashboardController extends Controller
{
public function index()
{
$repositories = Repository::all();
$commits = Commit::select('branch', DB::raw('max(created_at) as created_at'))
->orderBy('created_at', 'desc')
->groupBy('branch')
->get();
$masterInfo = Commit::getBranchInfo('master');
$branches = [];
foreach ($commits as $commit) {
$info = Commit::getBranchInfo($commit->branch);
$branches[] = [
'branch' => $commit->branch,
'status' => $info['status'],
'label' => $info['label'],
'last_commit_id' => $info['last_commit_id'],
];
}
return view('dashboard', compact('repositories', 'branches', 'masterInfo'));
}
public function build(Commit $commit, $attempt = null)
{
$count = Build::where(['commit_id' => $commit->id])->count();
$query = Build::where(['commit_id' => $commit->id])
->orderBy('attempt', 'desc');
if ($attempt) {
$query->where(['attempt' => $attempt]);
}
$build = $query->first();
$logs = json_decode($build->log, true);
$next = $build->attempt < $count ? "/build/$build->id/" . ($build->attempt + 1) : null;
return view('build', compact('build', 'commit', 'attempt', 'logs', 'count', 'next'));
}
public function rebuild(Build $build)
{
$rebuild = new Build();
$rebuild->commit_id = $build->commit_id;
$rebuild->attempt = $build->attempt + 1;
$rebuild->status = 'QUEUED';
$rebuild->save();
$github = new GitHub(
$rebuild->commit->repository->name,
$rebuild->commit->commit_id,
env('PROJECT_URL') . '/build/' . $rebuild->commit_id
);
$github->notifyPendingBuild();
dispatch(new GetInstance($rebuild->id));
return redirect("/build/$rebuild->commit_id");
}
}
|
michaelst/ci
|
app/Http/Controllers/DashboardController.php
|
PHP
|
mit
| 2,283 |
/*
* @Author: justinwebb
* @Date: 2015-09-24 21:08:23
* @Last Modified by: justinwebb
* @Last Modified time: 2015-09-24 22:19:45
*/
(function (window) {
'use strict';
window.JWLB = window.JWLB || {};
window.JWLB.View = window.JWLB.View || {};
//--------------------------------------------------------------------
// Event handling
//--------------------------------------------------------------------
var wallOnClick = function (event) {
if (event.target.tagName.toLowerCase() === 'img') {
var id = event.target.parentNode.dataset.id;
var selectedPhoto = this.photos.filter(function (photo) {
if (photo.id === id) {
photo.portrait.id = id;
return photo;
}
})[0];
this.sendEvent('gallery', selectedPhoto.portrait);
}
};
//--------------------------------------------------------------------
// View overrides
//--------------------------------------------------------------------
var addUIListeners = function () {
this.ui.wall.addEventListener('click', wallOnClick.bind(this));
};
var initUI = function () {
var isUIValid = false;
var comp = document.querySelector(this.selector);
this.ui.wall = comp;
if (this.ui.wall) {
this.reset();
isUIValid = true;
}
return isUIValid;
};
//--------------------------------------------------------------------
// Constructor
//--------------------------------------------------------------------
var Gallery = function (domId) {
// Overriden View class methods
this.initUI = initUI;
this.addUIListeners = addUIListeners;
this.name = 'Gallery';
// Instance properties
this.photos = [];
// Initialize View
JWLB.View.call(this, domId);
};
//--------------------------------------------------------------------
// Inheritance
//--------------------------------------------------------------------
Gallery.prototype = Object.create(JWLB.View.prototype);
Gallery.prototype.constructor = Gallery;
//--------------------------------------------------------------------
// Instance methods
//--------------------------------------------------------------------
Gallery.prototype.addThumb = function (data, id) {
// Store image data for future reference
var photo = {
id: id,
thumb: null,
portrait: data.size[0]
};
data.size.forEach(function (elem) {
if (elem.label === 'Square') {
photo.thumb = elem;
}
if (elem.height > photo.portrait.height) {
photo.portrait = elem;
}
});
this.photos.push(photo);
// Build thumbnail UI
var node = document.createElement('div');
node.setAttribute('data-id', id);
node.setAttribute('class', 'thumb');
var img = document.createElement('img');
img.setAttribute('src', photo.thumb.source);
img.setAttribute('title', 'id: '+ id);
node.appendChild(img);
this.ui.wall.querySelector('article[name=foobar]').appendChild(node);
};
Gallery.prototype.reset = function () {
if (this.ui.wall.children.length > 0) {
var article = this.ui.wall.children.item(0)
article.parentElement.removeChild(article);
}
var article = document.createElement('article');
article.setAttribute('name', 'foobar');
this.ui.wall.appendChild(article);
};
window.JWLB.View.Gallery = Gallery;
})(window);
|
JustinWebb/lightbox-demo
|
app/js/helpers/view/gallery.js
|
JavaScript
|
mit
| 3,410 |
<?php
session_start();
require_once('../php/conexion.php');
$conect = connect::conn();
$user = $_SESSION['usuario'];
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$sql = "insert into cotidiano (dir_origen,dir_destino,semana,hora,usuario,estado) values (?,?,?,?,?,?);";
$favo = sqlsrv_query($conect,$sql,array($_POST['Dir_o'],$_POST['Dir_d'],$_POST['semana'],$_POST['reloj'],$user['usuario'],1));
if($favo){
echo 'Inserccion correcta';
}
else{
if( ($errors = sqlsrv_errors() ) != null) {
foreach( $errors as $error ) {
echo "SQLSTATE: ".$error[ 'SQLSTATE']."<br />";
echo "code: ".$error[ 'code']."<br />";
echo "message: ".$error[ 'message']."<br />";
}
}
}
}else{
print "aqui la estabas cagando";
}
?>
|
smukideejeah/GaysonTaxi
|
cpanel/nuevoCotidiano.php
|
PHP
|
mit
| 822 |
using System;
using NetOffice;
using NetOffice.Attributes;
namespace NetOffice.MSProjectApi.Enums
{
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
///<remarks> MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff863548(v=office.14).aspx </remarks>
[SupportByVersion("MSProject", 11,12,14)]
[EntityType(EntityType.IsEnum)]
public enum PjMonthLabel
{
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>57</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelMonth_mm = 57,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>86</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelMonth_mm_yy = 86,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>85</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelMonth_mm_yyy = 85,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>11</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelMonth_m = 11,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>10</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelMonth_mmm = 10,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>8</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelMonth_mmm_yyy = 8,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>9</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelMonth_mmmm = 9,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>7</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelMonth_mmmm_yyyy = 7,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>59</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelMonthFromEnd_mm = 59,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>58</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelMonthFromEnd_Mmm = 58,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>45</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelMonthFromEnd_Month_mm = 45,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>61</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelMonthFromStart_mm = 61,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>60</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelMonthFromStart_Mmm = 60,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>44</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelMonthFromStart_Month_mm = 44,
/// <summary>
/// SupportByVersion MSProject 11, 12, 14
/// </summary>
/// <remarks>35</remarks>
[SupportByVersion("MSProject", 11,12,14)]
pjMonthLabelNoDateFormat = 35
}
}
|
NetOfficeFw/NetOffice
|
Source/MSProject/Enums/PjMonthLabel.cs
|
C#
|
mit
| 3,276 |
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("CircleAreaAndCircumference")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CircleAreaAndCircumference")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[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("24a850d9-a2e2-4979-a7f8-47602b439978")]
// 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")]
|
frostblooded/TelerikHomework
|
C# Part 1/ConsoleInputOutput/CircleAreaAndCircumference/Properties/AssemblyInfo.cs
|
C#
|
mit
| 1,428 |
//#define USE_TOUCH_SCRIPT
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
/*
* ドラッグ操作でのカメラの移動コントロールクラス
* マウス&タッチ対応
*/
namespace GarageKit
{
[RequireComponent(typeof(Camera))]
public class FlyThroughCamera : MonoBehaviour
{
public static bool winTouch = false;
public static bool updateEnable = true;
// フライスルーのコントロールタイプ
public enum FLYTHROUGH_CONTROLL_TYPE
{
DRAG = 0,
DRAG_HOLD
}
public FLYTHROUGH_CONTROLL_TYPE controllType;
// 移動軸の方向
public enum FLYTHROUGH_MOVE_TYPE
{
XZ = 0,
XY
}
public FLYTHROUGH_MOVE_TYPE moveType;
public Collider groundCollider;
public Collider limitAreaCollider;
public bool useLimitArea = false;
public float moveBias = 1.0f;
public float moveSmoothTime = 0.1f;
public bool dragInvertX = false;
public bool dragInvertY = false;
public float rotateBias = 1.0f;
public float rotateSmoothTime = 0.1f;
public bool rotateInvert = false;
public OrbitCamera combinationOrbitCamera;
private GameObject flyThroughRoot;
public GameObject FlyThroughRoot { get{ return flyThroughRoot; } }
private GameObject shiftTransformRoot;
public Transform ShiftTransform { get{ return shiftTransformRoot.transform; } }
private bool inputLock;
public bool IsInputLock { get{ return inputLock; } }
private object lockObject;
private Vector3 defaultPos;
private Quaternion defaultRot;
private bool isFirstTouch;
private Vector3 oldScrTouchPos;
private Vector3 dragDelta;
private Vector3 velocitySmoothPos;
private Vector3 dampDragDelta = Vector3.zero;
private Vector3 pushMoveDelta = Vector3.zero;
private float velocitySmoothRot;
private float dampRotateDelta = 0.0f;
private float pushRotateDelta = 0.0f;
public Vector3 currentPos { get{ return flyThroughRoot.transform.position; } }
public Quaternion currentRot { get{ return flyThroughRoot.transform.rotation; } }
void Awake()
{
}
void Start()
{
// 設定ファイルより入力タイプを取得
if(!ApplicationSetting.Instance.GetBool("UseMouse"))
winTouch = true;
inputLock = false;
// 地面上視点位置に回転ルートを設定する
Ray ray = new Ray(this.transform.position, this.transform.forward);
RaycastHit hitInfo;
if(groundCollider.Raycast(ray, out hitInfo, float.PositiveInfinity))
{
flyThroughRoot = new GameObject(this.gameObject.name + " FlyThrough Root");
flyThroughRoot.transform.SetParent(this.gameObject.transform.parent, false);
flyThroughRoot.transform.position = hitInfo.point;
flyThroughRoot.transform.rotation = Quaternion.identity;
shiftTransformRoot = new GameObject(this.gameObject.name + " ShiftTransform Root");
shiftTransformRoot.transform.SetParent(flyThroughRoot.transform, true);
shiftTransformRoot.transform.localPosition = Vector3.zero;
shiftTransformRoot.transform.localRotation = Quaternion.identity;
this.gameObject.transform.SetParent(shiftTransformRoot.transform, true);
}
else
{
Debug.LogWarning("FlyThroughCamera :: not set the ground collider !!");
return;
}
// 初期値を保存
defaultPos = flyThroughRoot.transform.position;
defaultRot = flyThroughRoot.transform.rotation;
ResetInput();
}
void Update()
{
if(!inputLock && ButtonObjectEvent.PressBtnsTotal == 0)
GetInput();
else
ResetInput();
UpdateFlyThrough();
UpdateOrbitCombination();
}
private void ResetInput()
{
isFirstTouch = true;
oldScrTouchPos = Vector3.zero;
dragDelta = Vector3.zero;
}
private void GetInput()
{
// for Touch
if(Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer)
{
if(Input.touchCount == 1)
{
// ドラッグ量を計算
Vector3 currentScrTouchPos = Input.GetTouch(0).position;
if(isFirstTouch)
{
oldScrTouchPos = currentScrTouchPos;
isFirstTouch = false;
return;
}
dragDelta = currentScrTouchPos - oldScrTouchPos;
if(controllType == FLYTHROUGH_CONTROLL_TYPE.DRAG)
oldScrTouchPos = currentScrTouchPos;
}
else
ResetInput();
}
#if UNITY_STANDALONE_WIN
else if(Application.platform == RuntimePlatform.WindowsPlayer && winTouch)
{
#if !USE_TOUCH_SCRIPT
if(Input.touchCount == 1)
{
// ドラッグ量を計算
Vector3 currentScrTouchPos = Input.touches[0].position;
#else
if(TouchScript.TouchManager.Instance.PressedPointersCount == 1)
{
// ドラッグ量を計算
Vector3 currentScrTouchPos = TouchScript.TouchManager.Instance.PressedPointers[0].Position;
#endif
if(isFirstTouch)
{
oldScrTouchPos = currentScrTouchPos;
isFirstTouch = false;
return;
}
dragDelta = currentScrTouchPos - oldScrTouchPos;
if(controllType == FLYTHROUGH_CONTROLL_TYPE.DRAG)
oldScrTouchPos = currentScrTouchPos;
}
else
ResetInput();
}
#endif
// for Mouse
else
{
if(Input.GetMouseButton(0))
{
// ドラッグ量を計算
Vector3 currentScrTouchPos = Input.mousePosition;
if(isFirstTouch)
{
oldScrTouchPos = currentScrTouchPos;
isFirstTouch = false;
return;
}
dragDelta = currentScrTouchPos - oldScrTouchPos;
if(controllType == FLYTHROUGH_CONTROLL_TYPE.DRAG)
oldScrTouchPos = currentScrTouchPos;
}
else
ResetInput();
}
}
/// <summary>
/// Input更新のLock
/// </summary>
public void LockInput(object sender)
{
if(!inputLock)
{
lockObject = sender;
inputLock = true;
}
}
/// <summary>
/// Input更新のUnLock
/// </summary>
public void UnlockInput(object sender)
{
if(inputLock && lockObject == sender)
inputLock = false;
}
/// <summary>
/// フライスルーを更新
/// </summary>
private void UpdateFlyThrough()
{
if(!FlyThroughCamera.updateEnable || flyThroughRoot == null)
return;
// 位置
float dragX = dragDelta.x * (dragInvertX ? -1.0f : 1.0f);
float dragY = dragDelta.y * (dragInvertY ? -1.0f : 1.0f);
if(moveType == FLYTHROUGH_MOVE_TYPE.XZ)
dampDragDelta = Vector3.SmoothDamp(dampDragDelta, new Vector3(dragX, 0.0f, dragY) * moveBias + pushMoveDelta, ref velocitySmoothPos, moveSmoothTime);
else if(moveType == FLYTHROUGH_MOVE_TYPE.XY)
dampDragDelta = Vector3.SmoothDamp(dampDragDelta, new Vector3(dragX, dragY, 0.0f) * moveBias + pushMoveDelta, ref velocitySmoothPos, moveSmoothTime);
flyThroughRoot.transform.Translate(dampDragDelta, Space.Self);
pushMoveDelta = Vector3.zero;
if(useLimitArea)
{
// 移動範囲限界を設定
if(limitAreaCollider != null)
{
Vector3 movingLimitMin = limitAreaCollider.bounds.min + limitAreaCollider.bounds.center - limitAreaCollider.gameObject.transform.position;
Vector3 movingLimitMax = limitAreaCollider.bounds.max + limitAreaCollider.bounds.center - limitAreaCollider.gameObject.transform.position;
if(moveType == FLYTHROUGH_MOVE_TYPE.XZ)
{
float limitX = Mathf.Max(Mathf.Min(flyThroughRoot.transform.position.x, movingLimitMax.x), movingLimitMin.x);
float limitZ = Mathf.Max(Mathf.Min(flyThroughRoot.transform.position.z, movingLimitMax.z), movingLimitMin.z);
flyThroughRoot.transform.position = new Vector3(limitX, flyThroughRoot.transform.position.y, limitZ);
}
else if(moveType == FLYTHROUGH_MOVE_TYPE.XY)
{
float limitX = Mathf.Max(Mathf.Min(flyThroughRoot.transform.position.x, movingLimitMax.x), movingLimitMin.x);
float limitY = Mathf.Max(Mathf.Min(flyThroughRoot.transform.position.y, movingLimitMax.y), movingLimitMin.y);
flyThroughRoot.transform.position = new Vector3(limitX, limitY, flyThroughRoot.transform.position.z);
}
}
}
// 方向
dampRotateDelta = Mathf.SmoothDamp(dampRotateDelta, pushRotateDelta * rotateBias, ref velocitySmoothRot, rotateSmoothTime);
if(moveType == FLYTHROUGH_MOVE_TYPE.XZ)
flyThroughRoot.transform.Rotate(Vector3.up, dampRotateDelta, Space.Self);
else if(moveType == FLYTHROUGH_MOVE_TYPE.XY)
flyThroughRoot.transform.Rotate(Vector3.forward, dampRotateDelta, Space.Self);
pushRotateDelta = 0.0f;
}
private void UpdateOrbitCombination()
{
// 連携機能
if(combinationOrbitCamera != null && combinationOrbitCamera.OrbitRoot != null)
{
Vector3 lookPoint = combinationOrbitCamera.OrbitRoot.transform.position;
Transform orbitParent = combinationOrbitCamera.OrbitRoot.transform.parent;
combinationOrbitCamera.OrbitRoot.transform.parent = null;
flyThroughRoot.transform.LookAt(lookPoint, Vector3.up);
flyThroughRoot.transform.rotation = Quaternion.Euler(
0.0f, flyThroughRoot.transform.rotation.eulerAngles.y + 180.0f, 0.0f);
combinationOrbitCamera.OrbitRoot.transform.parent = orbitParent;
}
}
/// <summary>
/// 目標位置にカメラを移動させる
/// </summary>
public void MoveToFlyThrough(Vector3 targetPosition, float time = 1.0f)
{
dampDragDelta = Vector3.zero;
flyThroughRoot.transform.DOMove(targetPosition, time)
.SetEase(Ease.OutCubic)
.Play();
}
/// <summary>
/// 指定値でカメラを移動させる
/// </summary>
public void TranslateToFlyThrough(Vector3 move)
{
dampDragDelta = Vector3.zero;
flyThroughRoot.transform.Translate(move, Space.Self);
}
/// <summary>
/// 目標方向にカメラを回転させる
/// </summary>
public void RotateToFlyThrough(float targetAngle, float time = 1.0f)
{
dampRotateDelta = 0.0f;
Vector3 targetEulerAngles = flyThroughRoot.transform.rotation.eulerAngles;
targetEulerAngles.y = targetAngle;
flyThroughRoot.transform.DORotate(targetEulerAngles, time)
.SetEase(Ease.OutCubic)
.Play();
}
/// <summary>
/// 外部トリガーで移動させる
/// </summary>
public void PushMove(Vector3 move)
{
pushMoveDelta = move;
}
/// <summary>
/// 外部トリガーでカメラ方向を回転させる
/// </summary>
public void PushRotate(float rotate)
{
pushRotateDelta = rotate;
}
/// <summary>
/// フライスルーを初期化
/// </summary>
public void ResetFlyThrough()
{
ResetInput();
MoveToFlyThrough(defaultPos);
RotateToFlyThrough(defaultRot.eulerAngles.y);
}
}
}
|
sharkattack51/GarageKit_for_Unity
|
UnityProject/Assets/__ProjectName__/Scripts/Utils/CameraContorol/FlyThroughCamera.cs
|
C#
|
mit
| 13,347 |
"use strict";
const readdir = require("../../");
const dir = require("../utils/dir");
const { expect } = require("chai");
const through2 = require("through2");
const fs = require("fs");
let nodeVersion = parseFloat(process.version.substr(1));
describe("Stream API", () => {
it("should be able to pipe to other streams as a Buffer", done => {
let allData = [];
readdir.stream("test/dir")
.pipe(through2((data, enc, next) => {
try {
// By default, the data is streamed as a Buffer
expect(data).to.be.an.instanceOf(Buffer);
// Buffer.toString() returns the file name
allData.push(data.toString());
next(null, data);
}
catch (e) {
next(e);
}
}))
.on("finish", () => {
try {
expect(allData).to.have.same.members(dir.shallow.data);
done();
}
catch (e) {
done(e);
}
})
.on("error", err => {
done(err);
});
});
it('should be able to pipe to other streams in "object mode"', done => {
let allData = [];
readdir.stream("test/dir")
.pipe(through2({ objectMode: true }, (data, enc, next) => {
try {
// In "object mode", the data is a string
expect(data).to.be.a("string");
allData.push(data);
next(null, data);
}
catch (e) {
next(e);
}
}))
.on("finish", () => {
try {
expect(allData).to.have.same.members(dir.shallow.data);
done();
}
catch (e) {
done(e);
}
})
.on("error", err => {
done(err);
});
});
it('should be able to pipe fs.Stats to other streams in "object mode"', done => {
let allData = [];
readdir.stream("test/dir", { stats: true })
.pipe(through2({ objectMode: true }, (data, enc, next) => {
try {
// The data is an fs.Stats object
expect(data).to.be.an("object");
expect(data).to.be.an.instanceOf(fs.Stats);
allData.push(data.path);
next(null, data);
}
catch (e) {
next(e);
}
}))
.on("finish", () => {
try {
expect(allData).to.have.same.members(dir.shallow.data);
done();
}
catch (e) {
done(e);
}
})
.on("error", done);
});
it("should be able to pause & resume the stream", done => {
let allData = [];
let stream = readdir.stream("test/dir")
.on("data", data => {
allData.push(data);
// The stream should not be paused
expect(stream.isPaused()).to.equal(false);
if (allData.length === 3) {
// Pause for one second
stream.pause();
setTimeout(() => {
try {
// The stream should still be paused
expect(stream.isPaused()).to.equal(true);
// The array should still only contain 3 items
expect(allData).to.have.lengthOf(3);
// Read the rest of the stream
stream.resume();
}
catch (e) {
done(e);
}
}, 1000);
}
})
.on("end", () => {
expect(allData).to.have.same.members(dir.shallow.data);
done();
})
.on("error", done);
});
it('should be able to use "readable" and "read"', done => {
let allData = [];
let nullCount = 0;
let stream = readdir.stream("test/dir")
.on("readable", () => {
// Manually read the next chunk of data
let data = stream.read();
while (true) { // eslint-disable-line
if (data === null) {
// The stream is done
nullCount++;
break;
}
else {
// The data should be a string (the file name)
expect(data).to.be.a("string").with.length.of.at.least(1);
allData.push(data);
data = stream.read();
}
}
})
.on("end", () => {
if (nodeVersion >= 12) {
// In Node >= 12, the "readable" event fires twice,
// and stream.read() returns null twice
expect(nullCount).to.equal(2);
}
else if (nodeVersion >= 10) {
// In Node >= 10, the "readable" event only fires once,
// and stream.read() only returns null once
expect(nullCount).to.equal(1);
}
else {
// In Node < 10, the "readable" event fires 13 times (once per file),
// and stream.read() returns null each time
expect(nullCount).to.equal(13);
}
expect(allData).to.have.same.members(dir.shallow.data);
done();
})
.on("error", done);
});
it('should be able to subscribe to custom events instead of "data"', done => {
let allFiles = [];
let allSubdirs = [];
let stream = readdir.stream("test/dir");
// Calling "resume" is required, since we're not handling the "data" event
stream.resume();
stream
.on("file", filename => {
expect(filename).to.be.a("string").with.length.of.at.least(1);
allFiles.push(filename);
})
.on("directory", subdir => {
expect(subdir).to.be.a("string").with.length.of.at.least(1);
allSubdirs.push(subdir);
})
.on("end", () => {
expect(allFiles).to.have.same.members(dir.shallow.files);
expect(allSubdirs).to.have.same.members(dir.shallow.dirs);
done();
})
.on("error", done);
});
it('should handle errors that occur in the "data" event listener', done => {
testErrorHandling("data", dir.shallow.data, 7, done);
});
it('should handle errors that occur in the "file" event listener', done => {
testErrorHandling("file", dir.shallow.files, 3, done);
});
it('should handle errors that occur in the "directory" event listener', done => {
testErrorHandling("directory", dir.shallow.dirs, 2, done);
});
it('should handle errors that occur in the "symlink" event listener', done => {
testErrorHandling("symlink", dir.shallow.symlinks, 5, done);
});
function testErrorHandling (eventName, expected, expectedErrors, done) {
let errors = [], data = [];
let stream = readdir.stream("test/dir");
// Capture all errors
stream.on("error", error => {
errors.push(error);
});
stream.on(eventName, path => {
data.push(path);
if (path.indexOf(".txt") >= 0 || path.indexOf("dir-") >= 0) {
throw new Error("Epic Fail!!!");
}
else {
return true;
}
});
stream.on("end", () => {
try {
// Make sure the correct number of errors were thrown
expect(errors).to.have.lengthOf(expectedErrors);
for (let error of errors) {
expect(error.message).to.equal("Epic Fail!!!");
}
// All of the events should have still been emitted, despite the errors
expect(data).to.have.same.members(expected);
done();
}
catch (e) {
done(e);
}
});
stream.resume();
}
});
|
BigstickCarpet/readdir-enhanced
|
test/specs/stream.spec.js
|
JavaScript
|
mit
| 7,232 |
<?php
/*
* This file is part of PHPExifTool.
*
* (c) 2012 Romain Neutron <imprec@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPExiftool\Driver\Tag\Font;
use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;
/**
* @ExclusionPolicy("all")
*/
class PreferredSubfamily extends AbstractTag
{
protected $Id = 17;
protected $Name = 'PreferredSubfamily';
protected $FullName = 'Font::Name';
protected $GroupName = 'Font';
protected $g0 = 'Font';
protected $g1 = 'Font';
protected $g2 = 'Document';
protected $Type = '?';
protected $Writable = false;
protected $Description = 'Preferred Subfamily';
}
|
romainneutron/PHPExiftool
|
lib/PHPExiftool/Driver/Tag/Font/PreferredSubfamily.php
|
PHP
|
mit
| 792 |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.synapse.v2019_06_01_preview;
import java.util.Collection;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.microsoft.rest.ExpandableStringEnum;
/**
* Defines values for IntegrationRuntimeState.
*/
public final class IntegrationRuntimeState extends ExpandableStringEnum<IntegrationRuntimeState> {
/** Static value Initial for IntegrationRuntimeState. */
public static final IntegrationRuntimeState INITIAL = fromString("Initial");
/** Static value Stopped for IntegrationRuntimeState. */
public static final IntegrationRuntimeState STOPPED = fromString("Stopped");
/** Static value Started for IntegrationRuntimeState. */
public static final IntegrationRuntimeState STARTED = fromString("Started");
/** Static value Starting for IntegrationRuntimeState. */
public static final IntegrationRuntimeState STARTING = fromString("Starting");
/** Static value Stopping for IntegrationRuntimeState. */
public static final IntegrationRuntimeState STOPPING = fromString("Stopping");
/** Static value NeedRegistration for IntegrationRuntimeState. */
public static final IntegrationRuntimeState NEED_REGISTRATION = fromString("NeedRegistration");
/** Static value Online for IntegrationRuntimeState. */
public static final IntegrationRuntimeState ONLINE = fromString("Online");
/** Static value Limited for IntegrationRuntimeState. */
public static final IntegrationRuntimeState LIMITED = fromString("Limited");
/** Static value Offline for IntegrationRuntimeState. */
public static final IntegrationRuntimeState OFFLINE = fromString("Offline");
/** Static value AccessDenied for IntegrationRuntimeState. */
public static final IntegrationRuntimeState ACCESS_DENIED = fromString("AccessDenied");
/**
* Creates or finds a IntegrationRuntimeState from its string representation.
* @param name a name to look for
* @return the corresponding IntegrationRuntimeState
*/
@JsonCreator
public static IntegrationRuntimeState fromString(String name) {
return fromString(name, IntegrationRuntimeState.class);
}
/**
* @return known IntegrationRuntimeState values
*/
public static Collection<IntegrationRuntimeState> values() {
return values(IntegrationRuntimeState.class);
}
}
|
selvasingh/azure-sdk-for-java
|
sdk/synapse/mgmt-v2019_06_01_preview/src/main/java/com/microsoft/azure/management/synapse/v2019_06_01_preview/IntegrationRuntimeState.java
|
Java
|
mit
| 2,607 |
// Copyright 2015 Peter Beverloo. All rights reserved.
// Use of this source code is governed by the MIT license, a copy of which can
// be found in the LICENSE file.
// Base class for a module. Stores the environment and handles magic such as route annotations.
export class Module {
constructor(env) {
this.env_ = env;
let decoratedRoutes = Object.getPrototypeOf(this).decoratedRoutes_;
if (!decoratedRoutes)
return;
decoratedRoutes.forEach(route => {
env.dispatcher.addRoute(route.method, route.route_path, ::this[route.handler]);
});
}
};
// Annotation that can be used on modules to indicate that the annotated method is the request
// handler for a |method| (GET, POST) request for |route_path|.
export function route(method, route_path) {
return (target, handler) => {
if (!target.hasOwnProperty('decoratedRoutes_'))
target.decoratedRoutes_ = [];
target.decoratedRoutes_.push({ method, route_path, handler });
};
}
|
beverloo/node-home-server
|
src/module.js
|
JavaScript
|
mit
| 981 |
package com.timotheteus.raincontrol.handlers;
import com.timotheteus.raincontrol.tileentities.IGUITile;
import com.timotheteus.raincontrol.tileentities.TileEntityInventoryBase;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.network.IGuiHandler;
import net.minecraftforge.fml.network.FMLPlayMessages;
import net.minecraftforge.fml.network.NetworkHooks;
import javax.annotation.Nullable;
public class GuiHandler implements IGuiHandler {
public static GuiScreen openGui(FMLPlayMessages.OpenContainer openContainer) {
BlockPos pos = openContainer.getAdditionalData().readBlockPos();
// new GUIChest(type, (IInventory) Minecraft.getInstance().player.inventory, (IInventory) Minecraft.getInstance().world.getTileEntity(pos));
TileEntityInventoryBase te = (TileEntityInventoryBase) Minecraft.getInstance().world.getTileEntity(pos);
if (te != null) {
return te.createGui(Minecraft.getInstance().player);
}
return null;
}
//TODO can remove these, I think
@Nullable
@Override
public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
BlockPos pos = new BlockPos(x, y, z);
TileEntity te = world.getTileEntity(pos);
if (te instanceof IGUITile) {
return ((IGUITile) te).createContainer(player);
}
return null;
}
@Nullable
@Override
public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
BlockPos pos = new BlockPos(x, y, z);
TileEntity te = world.getTileEntity(pos);
if (te instanceof IGUITile) {
return ((IGUITile) te).createGui(player);
}
return null;
}
}
|
kristofersokk/RainControl
|
src/main/java/com/timotheteus/raincontrol/handlers/GuiHandler.java
|
Java
|
mit
| 2,028 |
version https://git-lfs.github.com/spec/v1
oid sha256:be847f24aac166b803f1ff5ccc7e4d7bc3fb5d960543e35f779068a754294c94
size 1312
|
yogeshsaroya/new-cdnjs
|
ajax/libs/extjs/4.2.1/src/app/domain/Direct.js
|
JavaScript
|
mit
| 129 |
<?php
namespace Matthimatiker\CommandLockingBundle\Locking;
use Symfony\Component\Filesystem\LockHandler;
/**
* Uses files to create locks.
*
* @see \Symfony\Component\Filesystem\LockHandler
* @see http://symfony.com/doc/current/components/filesystem/lock_handler.html
*/
class FileLockManager implements LockManagerInterface
{
/**
* The directory that contains the lock files.
*
* @var string
*/
private $lockDirectory = null;
/**
* Contains the locks that are currently active.
*
* The name of the lock is used as key.
*
* @var array<string, LockHandler>
*/
private $activeLocksByName = array();
/**
* @param string $lockDirectory Path to the directory that contains the locks.
*/
public function __construct($lockDirectory)
{
$this->lockDirectory = $lockDirectory;
}
/**
* Obtains a lock for the provided name.
*
* The lock must be released before it can be obtained again.
*
* @param string $name
* @return boolean True if the lock was obtained, false otherwise.
*/
public function lock($name)
{
if ($this->isLocked($name)) {
return false;
}
$lock = new LockHandler($name . '.lock', $this->lockDirectory);
if ($lock->lock()) {
// Obtained lock.
$this->activeLocksByName[$name] = $lock;
return true;
}
return false;
}
/**
* Releases the lock with the provided name.
*
* If the lock does not exist, then this method will do nothing.
*
* @param string $name
*/
public function release($name)
{
if (!$this->isLocked($name)) {
return;
}
/* @var $lock LockHandler */
$lock = $this->activeLocksByName[$name];
$lock->release();
unset($this->activeLocksByName[$name]);
}
/**
* Checks if a lock with the given name is active.
*
* @param string $name
* @return boolean
*/
private function isLocked($name)
{
return isset($this->activeLocksByName[$name]);
}
}
|
Matthimatiker/CommandLockingBundle
|
Locking/FileLockManager.php
|
PHP
|
mit
| 2,166 |
// Core is a collection of helpers
// Nothing specific to the emultor application
"use strict";
// all code is defined in this namespace
window.te = window.te || {};
// te.provide creates a namespace if not previously defined.
// Levels are seperated by a `.` Each level is a generic JS object.
// Example:
// te.provide("my.name.space");
// my.name.foo = function(){};
// my.name.space.bar = function(){};
te.provide = function(ns /*string*/ , root) {
var parts = ns.split('.');
var lastLevel = root || window;
for (var i = 0; i < parts.length; i++) {
var p = parts[i];
if (!lastLevel[p]) {
lastLevel = lastLevel[p] = {};
} else if (typeof lastLevel[p] !== 'object') {
throw new Error('Error creating namespace.');
} else {
lastLevel = lastLevel[p];
}
}
};
// A simple UID generator. Returned UIDs are guaranteed to be unique to the page load
te.Uid = (function() {
var id = 1;
function next() {
return id++;
}
return {
next: next
};
})();
// defaultOptionParse is a helper for functions that expect an options
// var passed in. This merges the passed in options with a set of defaults.
// Example:
// foo function(options) {
// tf.defaultOptionParse(options, {bar:true, fizz:"xyz"});
// }
te.defaultOptionParse = function(src, defaults) {
src = src || {};
var keys = Object.keys(defaults);
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
if (src[k] === undefined) {
src[k] = defaults[k];
}
}
return src;
};
// Simple string replacement, eg:
// tf.sprintf('{0} and {1}', 'foo', 'bar'); // outputs: foo and bar
te.sprintf = function(str) {
for (var i = 1; i < arguments.length; i++) {
var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
str = str.replace(re, arguments[i]);
}
return str;
};
|
tyleregeto/8bit-emulator
|
src/core.js
|
JavaScript
|
mit
| 1,772 |
import Ember from 'ember';
let __TRANSLATION_MAP__ = {};
export default Ember.Service.extend({ map: __TRANSLATION_MAP__ });
|
alexBaizeau/ember-fingerprint-translations
|
app/services/translation-map.js
|
JavaScript
|
mit
| 126 |
import React from 'react';
<<<<<<< HEAD
import { Switch, Route } from 'react-router-dom';
import Home from './Home';
import About from './About';
import Blog from './Blog';
import Resume from './Resume';
import Error404 from './Error404';
=======
// import GithubForm from './forms/github/GithubForm';
import GithubRecent from './forms/github/RecentList';
import './Content.css';
>>>>>>> 23d814bedfd5c07e05ea49d9a90053074a4c829a
class Content extends React.Component {
render() {
return (
<div className="app-content">
<<<<<<< HEAD
<Switch>
<Route exact path="/" component={Home} />
{/* <Route exact path="/about" component={About} /> */}
<Route component={Error404} />
</Switch>
=======
<div className="content-description">
<br />College Student. Love Coding. Interested in Web and Machine Learning.
</div>
<hr />
<div className="content-list">
<div className="list-projects">
<h3>Recent Projects</h3>
{/* <GithubRecent userName="slkjse9" standardDate={5259492000} /> */}
<GithubRecent userName="hejuby" standardDate={3.154e+10} />
{/* <h2>Activity</h2> */}
<h3>Experience</h3>
<h3>Education</h3>
<ul>
<li><h4>Computer Science</h4>Colorado State University, Fort Collins (2017 -)</li>
</ul>
<br />
</div>
</div>
{/* <div className="content-home-github-recent-title">
<h2>Recent Works</h2>
<h3>updated in 2 months</h3>
</div> */}
{/* <h3>Recent</h3>
<GithubForm contentType="recent"/> */}
{/* <h3>Lifetime</h3>
{/* <GithubForm contentType="life"/> */}
{/* <div className="content-home-blog-recent-title">
<h2>Recent Posts</h2>
<h3>written in 2 months</h3>
</div>
<BlogRecent /> */}
>>>>>>> 23d814bedfd5c07e05ea49d9a90053074a4c829a
</div>
);
}
}
export default Content;
|
slkjse9/slkjse9.github.io
|
src/components/Content.js
|
JavaScript
|
mit
| 2,049 |
package cmd
import (
"github.com/fatih/color"
out "github.com/plouc/go-gitlab-client/cli/output"
"github.com/spf13/cobra"
)
func init() {
getCmd.AddCommand(getProjectVarCmd)
}
var getProjectVarCmd = &cobra.Command{
Use: resourceCmd("project-var", "project-var"),
Aliases: []string{"pv"},
Short: "Get the details of a project's specific variable",
RunE: func(cmd *cobra.Command, args []string) error {
ids, err := config.aliasIdsOrArgs(currentAlias, "project-var", args)
if err != nil {
return err
}
color.Yellow("Fetching project variable (id: %s, key: %s)…", ids["project_id"], ids["var_key"])
loader.Start()
variable, meta, err := client.ProjectVariable(ids["project_id"], ids["var_key"])
loader.Stop()
if err != nil {
return err
}
out.Variable(output, outputFormat, variable)
printMeta(meta, false)
return nil
},
}
|
plouc/go-gitlab-client
|
cli/cmd/get_project_var_cmd.go
|
GO
|
mit
| 873 |