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 |
|---|---|---|---|---|---|
<?php
return [
'@class' => 'Grav\\Common\\File\\CompiledYamlFile',
'filename' => '/Users/kenrickkelly/Sites/hokui/user/plugins/admin/languages/tlh.yaml',
'modified' => 1527231007,
'data' => [
'PLUGIN_ADMIN' => [
'LOGIN_BTN_FORGOT' => 'lIj',
'BACK' => 'chap',
'NORMAL' => 'motlh',
'YES' => 'HIja\'',
'NO' => 'Qo\'',
'DISABLED' => 'Qotlh'
]
]
];
| h0kui/hokui | cache/compiled/files/02efd2c2255a28026bd81d6a8068c728.yaml.php | PHP | mit | 452 |
import React from 'react';
import ReactDOM from 'react-dom';
import _ from 'underscore';
import babel from 'babel-core/browser';
import esprima from 'esprima';
import escodegen from 'escodegen';
import estraverse from 'estraverse';
import Codemirror from 'react-codemirror';
import classNames from 'classnames';
import { iff, default as globalUtils } from 'app/utils/globalUtils';
import './styles/app.less';
import 'react-codemirror/node_modules/codemirror/lib/codemirror.css';
import 'react-codemirror/node_modules/codemirror/theme/material.css';
import 'app/modules/JsxMode';
const localStorage = window.localStorage;
const TAB_SOURCE = 'SOURCE';
const TAB_TRANSCODE = 'TRANSCODE';
const LiveDemoApp = React.createClass({
getInitialState() {
return {
sourceCode: '',
transCode: '',
transError: '',
tab: TAB_SOURCE,
func: function() { }
};
},
componentWillMount() {
this._setSource(localStorage.getItem('sourceCode') || '');
},
componentDidMount() {
this._renderPreview();
},
componentDidUpdate() {
this._renderPreview();
},
render() {
const {
sourceCode,
transCode,
tab,
transError
} = this.state;
const showSource = (tab === TAB_SOURCE);
const cmOptions = {
lineNumbers: true,
readOnly: !showSource,
mode: 'jsx',
theme: 'material',
tabSize: 2,
smartIndent: true,
indentWithTabs: false
};
const srcTabClassName = classNames({
'otsLiveDemoApp-tab': true,
'otsLiveDemoApp-active': showSource
});
const transTabClassName = classNames({
'otsLiveDemoApp-tab': true,
'otsLiveDemoApp-active': !showSource
});
console.log((transCode || transError));
return (
<div className='otsLiveDemoApp'>
<div className='otsLiveDemoApp-tabs'>
<button className={srcTabClassName} onClick={this._onSrcClick}>Source</button>
<button className={transTabClassName} onClick={this._onTransClick}>Transcode</button>
</div>
<div className='otsLiveDemoApp-src'>
<Codemirror
value={showSource ? sourceCode : (transCode || transError)}
onChange={this._onChangeEditor}
options={cmOptions}
/>
</div>
</div>
);
},
_onChangeEditor(value) {
const { tab } = this.state;
if (tab === TAB_SOURCE) {
this._setSource(value);
}
},
_onSrcClick() {
this.setState({
tab: TAB_SOURCE
});
},
_onTransClick() {
this.setState({
tab: TAB_TRANSCODE
});
},
_setSource(sourceCode) {
localStorage.setItem('sourceCode', sourceCode);
const dependencies = [];
let transCode;
let transError;
try {
const es5trans = babel.transform(sourceCode);
let uniqueId = 0;
estraverse.replace(es5trans.ast.program, {
enter(node, parent) {
if (
node.type === 'CallExpression' &&
node.callee.type === 'Identifier' &&
node.callee.name === 'require' &&
node.arguments.length === 1 &&
node.arguments[0].type === 'Literal'
) {
const dep = {
identifier: '__DEPENDENCY_'+ (uniqueId++) ,
depName: node.arguments[0].value
};
dependencies.push(dep);
return {
name: dep.identifier,
type: 'Identifier'
};
}
else if (
node.type === 'AssignmentExpression' &&
node.left.type === 'MemberExpression' &&
node.left.object.type === 'Identifier' &&
node.left.object.name === 'module' &&
node.left.property.type === 'Identifier' &&
node.left.property.name === 'exports'
) {
return {
type: 'ReturnStatement',
argument: node.right
}
}
}
});
transCode = escodegen.generate(es5trans.ast.program);
}
catch (e) {
const msg = 'Error transpiling source code: ';
transError = msg + e.toString();
globalUtils.error(msg, e);
}
this.setState({
sourceCode,
transCode,
transError
});
if (transCode) {
try {
const fnConstArgs = [{ what: 'aaa'}].concat(dependencies.map((dep) => {
return dep.identifier;
}));
fnConstArgs.push('exports');
fnConstArgs.push(transCode);
this.setState({
func: new (Function.prototype.bind.apply(Function, fnConstArgs))
});
}
catch(e) {
console.error('Runtime Error', e);
}
}
},
_renderPreview() {
const { func } = this.state;
const { Component, error } = (() => {
try {
return {
Component: func(React, {})
};
}
catch(e) {
return {
error: e
};
}
})();
try {
if (Component) {
ReactDOM.render(<Component />, document.getElementById('preview'));
}
else if (error) {
ReactDOM.render(<div className='otsLiveDemoApp-error'>{error.toString()}</div>, document.getElementById('preview'));
}
}
catch (e) {
globalUtils.error('Fatal error rendering preview: ', e);
}
}
});
ReactDOM.render(<LiveDemoApp />, document.getElementById('editor'));
// const newProgram = {
// type: 'Program',
// body: [
// {
// type: 'CallExpression',
// callee: {
// type: 'FunctionExpression',
// id: null,
// params: dependencies.map((dep) => {
// return {
// type: 'Identifier',
// name: dep.identifier
// }
// }),
// body: {
// type: 'BlockStatement',
// body: es5trans.ast.program.body
// }
// },
// arguments: []
// }
// ]
// }; | frank-weindel/react-live-demo | app/index.js | JavaScript | mit | 5,927 |
import React from "react"
import { injectIntl } from "react-intl"
import { NavLink } from "react-router-dom"
import PropTypes from "prop-types"
import Styles from "./Navigation.css"
function Navigation({ intl }) {
return (
<ul className={Styles.list}>
<li><NavLink exact to="/" activeClassName={Styles.activeLink}>Home</NavLink></li>
<li><NavLink to="/redux" activeClassName={Styles.activeLink}>Redux</NavLink></li>
<li><NavLink to="/localization" activeClassName={Styles.activeLink}>Localization</NavLink></li>
<li><NavLink to="/markdown" activeClassName={Styles.activeLink}>Markdown</NavLink></li>
<li><NavLink to="/missing" activeClassName={Styles.activeLink}>Missing</NavLink></li>
</ul>
)
}
Navigation.propTypes = {
intl: PropTypes.object
}
export default injectIntl(Navigation)
| sebastian-software/edgeapp | src/components/Navigation.js | JavaScript | mit | 832 |
package main
import (
"bufio"
"os"
"fmt"
)
func main() {
counts := make(map[string]int)
fileReader, err := os.Open("words.txt")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer fileReader.Close()
scanner := bufio.NewScanner(fileReader)
// Set the split function for the scanning operation.
scanner.Split(bufio.ScanWords)
for scanner.Scan() {
word := scanner.Text()
counts[word]++
}
if err := scanner.Err(); err != nil {
fmt.Fprintf(os.Stderr, "wordfreq: %v\n", err)
os.Exit(1)
}
fmt.Printf("word\t freq\n")
for c, n := range counts {
fmt.Printf("%q\t %d\n", c, n)
}
} | farmatholin/gopl-exercises | ch4/ex4_9/ex4_9.go | GO | mit | 608 |
<?php
defined("_VALID_ACCESS") || die('Direct access forbidden');
$recordsets = Utils_RecordBrowserCommon::list_installed_recordsets();
$checkpoint = Patch::checkpoint('recordset');
$processed = $checkpoint->get('processed', array());
foreach ($recordsets as $tab => $caption) {
if (isset($processed[$tab])) {
continue;
}
$processed[$tab] = true;
Patch::require_time(3);
$tab = $tab . "_field";
$columns = DB::MetaColumnNames($tab);
if (!isset($columns['HELP'])) {
PatchUtil::db_add_column($tab, 'help', 'X');
}
$checkpoint->set('processed', $processed);
}
| georgehristov/EPESI | modules/Utils/RecordBrowser/patches/add_help_to_fields.php | PHP | mit | 611 |
const Marionette = require('backbone.marionette');
const MeterValuesView = require('./MeterValuesView.js');
module.exports = class EnergyMetersView extends Marionette.View {
template = Templates['capabilities/energy/meters'];
className() { return 'energy-meters'; }
regions() {
return {
metersByPeriod: '.metersByPeriod'
};
}
modelEvents() {
return {change: 'render'};
}
onRender() {
const metersView = new Marionette.CollectionView({
collection: this.model.metersByPeriod(),
childView: MeterValuesView
});
this.showChildView('metersByPeriod', metersView);
}
}
| monitron/jarvis-ha | lib/web/scripts/capabilities/energy/EnergyMetersView.js | JavaScript | mit | 625 |
const _ = require('lodash');
const en = {
modifiers: require('../../res/en').modifiers
};
const Types = require('../../lib/types');
const optional = {
optional: true
};
const repeatable = {
repeatable: true
};
const nullableNumber = {
type: Types.NameExpression,
name: 'number',
nullable: true
};
const nullableNumberOptional = _.extend({}, nullableNumber, optional);
const nullableNumberOptionalRepeatable = _.extend({}, nullableNumber, optional, repeatable);
const nullableNumberRepeatable = _.extend({}, nullableNumber, repeatable);
const nonNullableObject = {
type: Types.NameExpression,
name: 'Object',
nullable: false
};
const nonNullableObjectOptional = _.extend({}, nonNullableObject, optional);
const nonNullableObjectOptionalRepeatable = _.extend({}, nonNullableObject, optional, repeatable);
const nonNullableObjectRepeatable = _.extend({}, nonNullableObject, repeatable);
module.exports = [
{
description: 'nullable number',
expression: '?number',
parsed: nullableNumber,
described: {
en: {
simple: 'nullable number',
extended: {
description: 'number',
modifiers: {
nullable: en.modifiers.extended.nullable
},
returns: ''
}
}
}
},
{
description: 'postfix nullable number',
expression: 'number?',
newExpression: '?number',
parsed: nullableNumber,
described: {
en: {
simple: 'nullable number',
extended: {
description: 'number',
modifiers: {
nullable: en.modifiers.extended.nullable
},
returns: ''
}
}
}
},
{
description: 'non-nullable object',
expression: '!Object',
parsed: nonNullableObject,
described: {
en: {
simple: 'non-null Object',
extended: {
description: 'Object',
modifiers: {
nullable: en.modifiers.extended.nonNullable
},
returns: ''
}
}
}
},
{
description: 'postfix non-nullable object',
expression: 'Object!',
newExpression: '!Object',
parsed: nonNullableObject,
described: {
en: {
simple: 'non-null Object',
extended: {
description: 'Object',
modifiers: {
nullable: en.modifiers.extended.nonNullable
},
returns: ''
}
}
}
},
{
description: 'repeatable nullable number',
expression: '...?number',
parsed: nullableNumberRepeatable,
described: {
en: {
simple: 'nullable repeatable number',
extended: {
description: 'number',
modifiers: {
nullable: en.modifiers.extended.nullable,
repeatable: en.modifiers.extended.repeatable
},
returns: ''
}
}
}
},
{
description: 'postfix repeatable nullable number',
expression: '...number?',
newExpression: '...?number',
parsed: nullableNumberRepeatable,
described: {
en: {
simple: 'nullable repeatable number',
extended: {
description: 'number',
modifiers: {
nullable: en.modifiers.extended.nullable,
repeatable: en.modifiers.extended.repeatable
},
returns: ''
}
}
}
},
{
description: 'repeatable non-nullable object',
expression: '...!Object',
parsed: nonNullableObjectRepeatable,
described: {
en: {
simple: 'non-null repeatable Object',
extended: {
description: 'Object',
modifiers: {
nullable: en.modifiers.extended.nonNullable,
repeatable: en.modifiers.extended.repeatable
},
returns: ''
}
}
}
},
{
description: 'postfix repeatable non-nullable object',
expression: '...Object!',
newExpression: '...!Object',
parsed: nonNullableObjectRepeatable,
described: {
en: {
simple: 'non-null repeatable Object',
extended: {
description: 'Object',
modifiers: {
nullable: en.modifiers.extended.nonNullable,
repeatable: en.modifiers.extended.repeatable
},
returns: ''
}
}
}
},
{
description: 'postfix optional nullable number',
expression: 'number=?',
newExpression: '?number=',
parsed: nullableNumberOptional,
described: {
en: {
simple: 'optional nullable number',
extended: {
description: 'number',
modifiers: {
nullable: en.modifiers.extended.nullable,
optional: en.modifiers.extended.optional
},
returns: ''
}
}
}
},
{
description: 'postfix nullable optional number',
expression: 'number?=',
newExpression: '?number=',
parsed: nullableNumberOptional,
described: {
en: {
simple: 'optional nullable number',
extended: {
description: 'number',
modifiers: {
nullable: en.modifiers.extended.nullable,
optional: en.modifiers.extended.optional
},
returns: ''
}
}
}
},
{
description: 'postfix repeatable nullable optional number',
expression: '...number?=',
newExpression: '...?number=',
parsed: nullableNumberOptionalRepeatable,
described: {
en: {
simple: 'optional nullable repeatable number',
extended: {
description: 'number',
modifiers: {
nullable: en.modifiers.extended.nullable,
optional: en.modifiers.extended.optional,
repeatable: en.modifiers.extended.repeatable
},
returns: ''
}
}
}
},
{
description: 'postfix optional non-nullable object',
expression: 'Object=!',
newExpression: '!Object=',
parsed: nonNullableObjectOptional,
described: {
en: {
simple: 'optional non-null Object',
extended: {
description: 'Object',
modifiers: {
nullable: en.modifiers.extended.nonNullable,
optional: en.modifiers.extended.optional
},
returns: ''
}
}
}
},
{
description: 'postfix non-nullable optional object',
expression: 'Object!=',
newExpression: '!Object=',
parsed: nonNullableObjectOptional,
described: {
en: {
simple: 'optional non-null Object',
extended: {
description: 'Object',
modifiers: {
nullable: en.modifiers.extended.nonNullable,
optional: en.modifiers.extended.optional
},
returns: ''
}
}
}
},
{
description: 'postfix repeatable non-nullable optional object',
expression: '...Object!=',
newExpression: '...!Object=',
parsed: nonNullableObjectOptionalRepeatable,
described: {
en: {
simple: 'optional non-null repeatable Object',
extended: {
description: 'Object',
modifiers: {
nullable: en.modifiers.extended.nonNullable,
optional: en.modifiers.extended.optional,
repeatable: en.modifiers.extended.repeatable
},
returns: ''
}
}
}
}
];
| hegemonic/catharsis | test/specs/nullable.js | JavaScript | mit | 9,138 |
class ACLHelperMethod < ApplicationController
access_control :helper => :foo? do
allow :owner, :of => :foo
end
def allow
@foo = Foo.first
render inline: "<div><%= foo? ? 'OK' : 'AccessDenied' %></div>"
end
end
| be9/acl9 | test/dummy/app/controllers/acl_helper_method.rb | Ruby | mit | 232 |
<?php
namespace App\Application\Controllers\Traits;
trait HelpersTrait{
protected function checkIfArray($request){
return is_array($request) ? $request : [$request];
}
protected function createLog($action , $status , $messages = ''){
$data = [
'action' => $action,
'model' => $this->model->getTable(),
'status' => $status,
'user_id' => auth()->user()->id,
'messages' => $messages
];
$this->log->create($data);
}
} | issabdo/DIVCODING | app/Application/Controllers/Traits/HelpersTrait.php | PHP | mit | 527 |
angular.module('Reader.services.options', [])
.factory('options', function($rootScope, $q) {
var controllerObj = {};
options.onChange(function (changes) {
$rootScope.$apply(function () {
for (var property in changes) {
controllerObj[property] = changes[property].newValue;
}
});
});
return {
get: function (callback) {
options.get(function (values) {
$rootScope.$apply(function () {
angular.copy(values, controllerObj);
if (callback instanceof Function) {
callback(controllerObj);
}
});
});
return controllerObj;
},
set: function (values) {
options.set(values);
},
enableSync: options.enableSync,
isSyncEnabled: options.isSyncEnabled
};
}); | Janpot/google-reader-notifier | app/js/services/options.js | JavaScript | mit | 858 |
class UsersController < ApplicationController
def index
end
def show
@user = User.find(params[:id])
end
def edit
@user = User.find(params[:id])
end
def update
@user = User.find(params[:id])
if @user.update_attributes(user_params)
@user.geocode
else
render 'edit'
end
end
private
def user_params
params.require(:user).permit(:city, :zip, :name)
end
end
| reginad1/skipdamenu | app/controllers/users_controller.rb | Ruby | mit | 409 |
import Ember from 'ember';
import DS from 'ember-data';
import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin';
export default DS.RESTAdapter.extend(DataAdapterMixin, {
authorizer: 'authorizer:dspace',
initENVProperties: Ember.on('init', function() {
let ENV = this.container.lookupFactory('config:environment');
if (Ember.isPresent(ENV.namespace)) {
this.set('namespace', ENV.namespace);
}
if (Ember.isPresent(ENV.host)) {
this.set('host', ENV.host);
}
}),
//coalesceFindRequests: true, -> commented out, because it only works for some endpoints (e.g. items) and not others (e.g. communities)
ajax(url, type, hash) {
if (Ember.isEmpty(hash)) {
hash = {};
}
if (Ember.isEmpty(hash.data)) {
hash.data = {};
}
if (type === "GET") {
hash.data.expand = 'all'; //add ?expand=all to all GET calls
}
return this._super(url, type, hash);
}
});
| atmire/dsember-core | addon/adapters/application.js | JavaScript | mit | 949 |
function alertThanks (post) {
alert("Thanks for submitting a post!");
return post;
}
Telescope.callbacks.add("postSubmitClient", alertThanks);
| mxchelle/PhillyAIMSApp | packages/custom/lib/callbacks.js | JavaScript | mit | 148 |
"use strict";
var async = require('async');
var fs = require('fs');
var util = require('util');
var prompt = require('prompt');
var httpRequest = require('emsoap').subsystems.httpRequest;
var common = require('./common');
var mms = require('./mms');
var mmscmd = require('./mmscmd');
var deploy = require('./deploy');
var session; // MMS session
var modelFile = "sfmodel.json";
var externalSystemType = 'NODEX';
var externalSystem;
var accessAddress;
var credentials;
var mappedObjects;
var verboseLoggingForExternalSystem;
function afterAuth(cb) {
// munge mappedObjects as required
for (var name in mappedObjects) {
var map = mappedObjects[name];
if (!map.typeBindingProperties) {
map.typeBindingProperties = {};
for (var propName in map) {
switch(propName) {
case "target":
case "properties":
;
default:
map.typeBindingProperties[name] = map[name];
}
}
}
}
// invoke op to create model
session.directive(
{
op : "INVOKE",
targetType: "CdmExternalSystem",
name: "invokeExternal",
params: {
externalSystem: externalSystem,
opName : "createSfModel",
params : {
sfVersion : credentials.sfVersion,
externalSystem : externalSystem,
typeDescs : mappedObjects
}
}
},
function (err, result) {
if (err) {
return cb(err);
}
fs.writeFileSync(modelFile, JSON.stringify(result.results, null, 2));
mmscmd.execFile(modelFile,session, deploy.outputWriter, cb);
}
);
}
exports.deployModel = function deployModel(externalSystemName,mmsSession,cb) {
session = mmsSession;
externalSystem = externalSystemName;
var text;
if(!session.creds.externalCredentials) {
console.log("Profile must include externalCredentials");
process.exit(1);
}
credentials = session.creds.externalCredentials[externalSystemName];
if(!credentials) {
console.log("Profile does not provide externalCredentials for " + externalSystemName);
process.exit(1);
}
if(!credentials.oauthKey || !credentials.oauthSecret) {
console.log("externalSystemName for " + externalSystemName + " must contain the oAuth key and secret.");
}
accessAddress = credentials.host;
try {
text = fs.readFileSync("salesforce.json");
} catch(err) {
console.log('Error reading file salesforce.json:' + err);
process.exit(1);
}
try {
mappedObjects = JSON.parse(text);
} catch(err) {
console.log('Error parsing JSON in salesforce.json:' + err);
process.exit(1);
}
if(mappedObjects._verbose_logging_) {
verboseLoggingForExternalSystem = mappedObjects._verbose_logging_;
}
delete mappedObjects._verbose_logging_;
createExternalSystem(function(err) {
if (err) {
return cb(err);
}
var addr = common.global.session.creds.server + "/oauth/" + externalSystem + "/authenticate";
if (common.global.argv.nonInteractive) {
console.log("Note: what follows will fail unless Emotive has been authorized at " + addr);
afterAuth(cb);
}
else {
console.log("Please navigate to " + addr.underline + " with your browser");
prompt.start();
prompt.colors = false;
prompt.message = 'Press Enter when done';
prompt.delimiter = '';
var props = {
properties: {
q: {
description : ":"
}
}
}
prompt.get(props, function (err, result) {
if (err) {
return cb(err);
}
afterAuth(cb);
});
}
});
}
function createExternalSystem(cb) {
if (!session.creds.username)
{
console.log("session.creds.username was null");
process.exit(1);
}
if(verboseLoggingForExternalSystem) console.log('VERBOSE LOGGING IS ON FOR ' + externalSystem);
session.directive({
op: 'INVOKE',
targetType: 'CdmExternalSystem',
name: "updateOAuthExternalSystem",
params: {
name: externalSystem,
typeName: externalSystemType,
"oauthCredentials" : {
"oauthType": "salesforce",
"oauthKey": credentials.oauthKey,
"oauthSecret": credentials.oauthSecret
},
properties: {
proxyConfiguration: {verbose: verboseLoggingForExternalSystem, sfVersion: credentials.sfVersion},
globalPackageName : "sfProxy"
}
}
},
cb);
}
| emote/tools | lib/sfsetup.js | JavaScript | mit | 5,142 |
#!/usr/bin/env python
# coding:utf-8
"""
Database operation module. This module is independent with web module.
"""
import time, logging
import db
class Field(object):
_count = 0
def __init__(self, **kw):
self.name = kw.get('name', None)
self.ddl = kw.get('ddl', '')
self._default = kw.get('default', None)
self.comment = kw.get('comment', '')
self.nullable = kw.get('nullable', False)
self.updatable = kw.get('updatable', True)
self.insertable = kw.get('insertable', True)
self.unique_key = kw.get('unique_key', False)
self.non_unique_key = kw.get('key', False)
self.primary_key = kw.get('primary_key', False)
self._order = Field._count
Field._count += 1
@property
def default(self):
d = self._default
return d() if callable(d) else d
def __str__(self):
s = ['<%s:%s,%s,default(%s),' % (self.__class__.__name__, self.name, self.ddl, self._default)]
self.nullable and s.append('N')
self.updatable and s.append('U')
self.insertable and s.append('I')
s.append('>')
return ''.join(s)
class StringField(Field):
def __init__(self, **kw):
if not 'default' in kw:
kw['default'] = ''
if not 'ddl' in kw:
kw['ddl'] = 'varchar(255)'
super(StringField, self).__init__(**kw)
class IntegerField(Field):
def __init__(self, **kw):
if not 'default' in kw:
kw['default'] = 0
if not 'ddl' in kw:
kw['ddl'] = 'bigint'
super(IntegerField, self).__init__(**kw)
class FloatField(Field):
def __init__(self, **kw):
if not 'default' in kw:
kw['default'] = 0.0
if not 'ddl' in kw:
kw['ddl'] = 'real'
super(FloatField, self).__init__(**kw)
class BooleanField(Field):
def __init__(self, **kw):
if not 'default' in kw:
kw['default'] = False
if not 'ddl' in kw:
kw['ddl'] = 'bool'
super(BooleanField, self).__init__(**kw)
class TextField(Field):
def __init__(self, **kw):
if not 'default' in kw:
kw['default'] = ''
if not 'ddl' in kw:
kw['ddl'] = 'text'
super(TextField, self).__init__(**kw)
class BlobField(Field):
def __init__(self, **kw):
if not 'default' in kw:
kw['default'] = ''
if not 'ddl' in kw:
kw['ddl'] = 'blob'
super(BlobField, self).__init__(**kw)
class VersionField(Field):
def __init__(self, name=None):
super(VersionField, self).__init__(name=name, default=0, ddl='bigint')
class DateTimeField(Field):
def __init__(self, **kw):
if 'ddl' not in kw:
kw['ddl'] = 'datetime'
super(DateTimeField, self).__init__(**kw)
class DateField(Field):
def __init__(self, **kw):
if 'ddl' not in kw:
kw['ddl'] = 'date'
super(DateField, self).__init__(**kw)
class EnumField(Field):
def __init__(self, **kw):
if 'ddl' not in kw:
kw['ddl'] = 'enum'
super(EnumField, self).__init__(**kw)
_triggers = frozenset(['pre_insert', 'pre_update', 'pre_delete'])
def _gen_sql(table_name, mappings):
pk, unique_keys, keys = None, [], []
sql = ['-- generating SQL for %s:' % table_name, 'create table `%s` (' % table_name]
for f in sorted(mappings.values(), lambda x, y: cmp(x._order, y._order)):
if not hasattr(f, 'ddl'):
raise StandardError('no ddl in field "%s".' % f)
ddl = f.ddl
nullable = f.nullable
has_comment = not (f.comment == '')
has_default = f._default is not None
left = nullable and ' `%s` %s' % (f.name, ddl) or ' `%s` %s not null' % (f.name, ddl)
mid = has_default and ' default \'%s\'' % f._default or None
right = has_comment and ' comment \'%s\',' % f.comment or ','
line = mid and '%s%s%s' % (left, mid, right) or '%s%s' % (left, right)
if f.primary_key:
pk = f.name
line = ' `%s` %s not null auto_increment,' % (f.name, ddl)
elif f.unique_key:
unique_keys.append(f.name)
elif f.non_unique_key:
keys.append(f.name)
sql.append(line)
for uk in unique_keys:
sql.append(' unique key(`%s`),' % uk)
for k in keys:
sql.append(' key(`%s`),' % k)
sql.append(' primary key(`%s`)' % pk)
sql.append(')ENGINE=InnoDB DEFAULT CHARSET=utf8;')
return '\n'.join(sql)
class ModelMetaclass(type):
"""
Metaclass for model objects.
"""
def __new__(cls, name, bases, attrs):
# skip base Model class:
if name == 'Model':
return type.__new__(cls, name, bases, attrs)
# store all subclasses info:
if not hasattr(cls, 'subclasses'):
cls.subclasses = {}
if not name in cls.subclasses:
cls.subclasses[name] = name
else:
logging.warning('Redefine class: %s', name)
logging.info('Scan ORMapping %s...', name)
mappings = dict()
primary_key = None
for k, v in attrs.iteritems():
if isinstance(v, Field):
if not v.name:
v.name = k
logging.debug('Found mapping: %s => %s' % (k, v))
# check duplicate primary key:
if v.primary_key:
if primary_key:
raise TypeError('Cannot define more than 1 primary key in class: %s' % name)
if v.updatable:
# logging.warning('NOTE: change primary key to non-updatable.')
v.updatable = False
if v.nullable:
# logging.warning('NOTE: change primary key to non-nullable.')
v.nullable = False
primary_key = v
mappings[k] = v
# check exist of primary key:
if not primary_key:
raise TypeError('Primary key not defined in class: %s' % name)
for k in mappings.iterkeys():
attrs.pop(k)
if '__table__' not in attrs:
attrs['__table__'] = name.lower()
attrs['__mappings__'] = mappings
attrs['__primary_key__'] = primary_key
attrs['__sql__'] = lambda self: _gen_sql(attrs['__table__'], mappings)
for trigger in _triggers:
if trigger not in attrs:
attrs[trigger] = None
return type.__new__(cls, name, bases, attrs)
class Model(dict):
"""
Base class for ORM.
>>> class User(Model):
... id = IntegerField(primary_key=True)
... name = StringField()
... email = StringField(updatable=False)
... passwd = StringField(default=lambda: '******')
... last_modified = FloatField()
... def pre_insert(self):
... self.last_modified = time.time()
>>> u = User(id=10190, name='Michael', email='orm@db.org')
>>> r = u.insert()
>>> u.email
'orm@db.org'
>>> u.passwd
'******'
>>> u.last_modified > (time.time() - 2)
True
>>> f = User.get(10190)
>>> f.name
u'Michael'
>>> f.email
u'orm@db.org'
>>> f.email = 'changed@db.org'
>>> r = f.update() # change email but email is non-updatable!
>>> len(User.find_all())
1
>>> g = User.get(10190)
>>> g.email
u'orm@db.org'
>>> r = g.mark_deleted()
>>> len(db.select('select * from user where id=10190'))
0
>>> import json
>>> print User().__sql__()
-- generating SQL for user:
create table `user` (
`id` bigint not null,
`name` varchar(255) not null,
`email` varchar(255) not null,
`passwd` varchar(255) not null,
`last_modified` real not null,
primary key(`id`)
);
"""
__metaclass__ = ModelMetaclass
def __init__(self, **kw):
super(Model, self).__init__(**kw)
def __getattr__(self, key):
try:
return self[key]
except KeyError:
raise AttributeError(r"'Dict' object has no attribute '%s'" % key)
def __setattr__(self, key, value):
self[key] = value
@classmethod
def get(cls, key_name, key_value):
"""
Get by primary/unique key.
"""
d = db.select_one('select * from %s where %s=?' % (cls.__table__, key_name), key_value)
if not d:
# TODO: change to logging?
raise AttributeError("Can't find in [%s] where %s=[%s]" % (cls.__table__, key_name, key_value))
return cls(**d) if d else None
@classmethod
def find_first(cls, where, *args):
"""
Find by where clause and return one result. If multiple results found,
only the first one returned. If no result found, return None.
"""
d = db.select_one('select * from %s %s' % (cls.__table__, where), *args)
return cls(**d) if d else None
@classmethod
def find_all(cls, *args):
"""
Find all and return list.
"""
L = db.select('select * from `%s`' % cls.__table__)
return [cls(**d) for d in L]
@classmethod
def find_by(cls, cols, where, *args):
"""
Find by where clause and return list.
"""
L = db.select('select %s from `%s` %s' % (cols, cls.__table__, where), *args)
if cols.find(',') == -1 and cols.strip() != '*':
return [d[0] for d in L]
return [cls(**d) for d in L]
@classmethod
def count_all(cls):
"""
Find by 'select count(pk) from table' and return integer.
"""
return db.select_int('select count(`%s`) from `%s`' % (cls.__primary_key__.name, cls.__table__))
@classmethod
def count_by(cls, where, *args):
"""
Find by 'select count(pk) from table where ... ' and return int.
"""
return db.select_int('select count(`%s`) from `%s` %s' % (cls.__primary_key__.name, cls.__table__, where), *args)
def update(self):
self.pre_update and self.pre_update()
L = []
args = []
for k, v in self.__mappings__.iteritems():
if v.updatable:
if hasattr(self, k):
arg = getattr(self, k)
else:
arg = v.default
setattr(self, k, arg)
L.append('`%s`=?' % k)
args.append(arg)
pk = self.__primary_key__.name
args.append(getattr(self, pk))
db.update('update `%s` set %s where %s=?' % (self.__table__, ','.join(L), pk), *args)
return self
def delete(self):
self.pre_delete and self.pre_delete()
pk = self.__primary_key__.name
args = (getattr(self, pk), )
db.update('delete from `%s` where `%s`=?' % (self.__table__, pk), *args)
return self
def insert(self):
self.pre_insert and self.pre_insert()
params = {}
for k, v in self.__mappings__.iteritems():
if v.insertable:
if not hasattr(self, k):
setattr(self, k, v.default)
params[v.name] = getattr(self, k)
try:
db.insert('%s' % self.__table__, **params)
except Exception as e:
logging.info(e.args)
print "MySQL Model.insert() error: args=", e.args
# TODO !!! generalize ORM return package
# return {'status': 'Failure', 'msg': e.args, 'data': self}
raise
return self
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
db.create_engine('www-data', 'www-data', 'test')
db.update('drop table if exists user')
db.update('create table user (id int primary key, name text, email text, passwd text, last_modified real)')
import doctest
doctest.testmod()
| boisde/Greed_Island | business_logic/order_collector/transwarp/orm.py | Python | mit | 11,968 |
package cn.libery.calendar.MaterialCalendar;
import android.content.Context;
import java.util.Collection;
import java.util.HashSet;
import cn.libery.calendar.MaterialCalendar.spans.DotSpan;
/**
* Decorate several days with a dot
*/
public class EventDecorator implements DayViewDecorator {
private int color;
private HashSet<CalendarDay> dates;
public EventDecorator(int color, Collection<CalendarDay> dates) {
this.color = color;
this.dates = new HashSet<>(dates);
}
@Override
public boolean shouldDecorate(CalendarDay day) {
return dates.contains(day);
}
@Override
public void decorate(DayViewFacade view, Context context) {
view.addSpan(new DotSpan(4, color));
}
}
| Thewhitelight/Calendar | app/src/main/java/cn/libery/calendar/MaterialCalendar/EventDecorator.java | Java | mit | 752 |
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
// import Layout from '../../components/Layout';
const title = 'Admin Page';
const isAdmin = false;
export default {
path: '/admin',
children : [
require('./dashboard').default,
require('./library').default,
require('./setting').default,
// require('./editor').default,
require('./news').default,
require('./monngon').default,
require('./product').default,
require('./seo').default,
],
async action({store, next}) {
let user = store.getState().user
const route = await next();
// Provide default values for title, description etc.
route.title = `${route.title || 'Amdmin Page'}`;
return route;
},
};
| luanlv/comhoavang | src/routes/admin/index.js | JavaScript | mit | 959 |
using System;
using System.Collections.Generic;
namespace HarmonyLib
{
/// <summary>Specifies the type of method</summary>
///
public enum MethodType
{
/// <summary>This is a normal method</summary>
Normal,
/// <summary>This is a getter</summary>
Getter,
/// <summary>This is a setter</summary>
Setter,
/// <summary>This is a constructor</summary>
Constructor,
/// <summary>This is a static constructor</summary>
StaticConstructor,
/// <summary>This targets the MoveNext method of the enumerator result</summary>
Enumerator
}
/// <summary>Specifies the type of argument</summary>
///
public enum ArgumentType
{
/// <summary>This is a normal argument</summary>
Normal,
/// <summary>This is a reference argument (ref)</summary>
Ref,
/// <summary>This is an out argument (out)</summary>
Out,
/// <summary>This is a pointer argument (&)</summary>
Pointer
}
/// <summary>Specifies the type of patch</summary>
///
public enum HarmonyPatchType
{
/// <summary>Any patch</summary>
All,
/// <summary>A prefix patch</summary>
Prefix,
/// <summary>A postfix patch</summary>
Postfix,
/// <summary>A transpiler</summary>
Transpiler,
/// <summary>A finalizer</summary>
Finalizer,
/// <summary>A reverse patch</summary>
ReversePatch
}
/// <summary>Specifies the type of reverse patch</summary>
///
public enum HarmonyReversePatchType
{
/// <summary>Use the unmodified original method (directly from IL)</summary>
Original,
/// <summary>Use the original as it is right now including previous patches but excluding future ones</summary>
Snapshot
}
/// <summary>Specifies the type of method call dispatching mechanics</summary>
///
public enum MethodDispatchType
{
/// <summary>Call the method using dynamic dispatching if method is virtual (including overriden)</summary>
/// <remarks>
/// <para>
/// This is the built-in form of late binding (a.k.a. dynamic binding) and is the default dispatching mechanic in C#.
/// This directly corresponds with the <see cref="System.Reflection.Emit.OpCodes.Callvirt"/> instruction.
/// </para>
/// <para>
/// For virtual (including overriden) methods, the instance type's most-derived/overriden implementation of the method is called.
/// For non-virtual (including static) methods, same behavior as <see cref="Call"/>: the exact specified method implementation is called.
/// </para>
/// <para>
/// Note: This is not a fully dynamic dispatch, since non-virtual (including static) methods are still called non-virtually.
/// A fully dynamic dispatch in C# involves using
/// the <see href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/reference-types#the-dynamic-type"><c>dynamic</c> type</see>
/// (actually a fully dynamic binding, since even the name and overload resolution happens at runtime), which <see cref="MethodDispatchType"/> does not support.
/// </para>
/// </remarks>
VirtualCall,
/// <summary>Call the method using static dispatching, regardless of whether method is virtual (including overriden) or non-virtual (including static)</summary>
/// <remarks>
/// <para>
/// a.k.a. non-virtual dispatching, early binding, or static binding.
/// This directly corresponds with the <see cref="System.Reflection.Emit.OpCodes.Call"/> instruction.
/// </para>
/// <para>
/// For both virtual (including overriden) and non-virtual (including static) methods, the exact specified method implementation is called, without virtual/override mechanics.
/// </para>
/// </remarks>
Call
}
/// <summary>The base class for all Harmony annotations (not meant to be used directly)</summary>
///
public class HarmonyAttribute : Attribute
{
/// <summary>The common information for all attributes</summary>
public HarmonyMethod info = new HarmonyMethod();
}
/// <summary>Annotation to define your Harmony patch methods</summary>
///
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Delegate | AttributeTargets.Method, AllowMultiple = true)]
public class HarmonyPatch : HarmonyAttribute
{
/// <summary>An empty annotation can be used together with TargetMethod(s)</summary>
///
public HarmonyPatch()
{
}
/// <summary>An annotation that specifies a class to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
///
public HarmonyPatch(Type declaringType)
{
info.declaringType = declaringType;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="argumentTypes">The argument types of the method or constructor to patch</param>
///
public HarmonyPatch(Type declaringType, Type[] argumentTypes)
{
info.declaringType = declaringType;
info.argumentTypes = argumentTypes;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
///
public HarmonyPatch(Type declaringType, string methodName)
{
info.declaringType = declaringType;
info.methodName = methodName;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
///
public HarmonyPatch(Type declaringType, string methodName, params Type[] argumentTypes)
{
info.declaringType = declaringType;
info.methodName = methodName;
info.argumentTypes = argumentTypes;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
/// <param name="argumentVariations">Array of <see cref="ArgumentType"/></param>
///
public HarmonyPatch(Type declaringType, string methodName, Type[] argumentTypes, ArgumentType[] argumentVariations)
{
info.declaringType = declaringType;
info.methodName = methodName;
ParseSpecialArguments(argumentTypes, argumentVariations);
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="methodType">The <see cref="MethodType"/></param>
///
public HarmonyPatch(Type declaringType, MethodType methodType)
{
info.declaringType = declaringType;
info.methodType = methodType;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="methodType">The <see cref="MethodType"/></param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
///
public HarmonyPatch(Type declaringType, MethodType methodType, params Type[] argumentTypes)
{
info.declaringType = declaringType;
info.methodType = methodType;
info.argumentTypes = argumentTypes;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="methodType">The <see cref="MethodType"/></param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
/// <param name="argumentVariations">Array of <see cref="ArgumentType"/></param>
///
public HarmonyPatch(Type declaringType, MethodType methodType, Type[] argumentTypes, ArgumentType[] argumentVariations)
{
info.declaringType = declaringType;
info.methodType = methodType;
ParseSpecialArguments(argumentTypes, argumentVariations);
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
/// <param name="methodType">The <see cref="MethodType"/></param>
///
public HarmonyPatch(Type declaringType, string methodName, MethodType methodType)
{
info.declaringType = declaringType;
info.methodName = methodName;
info.methodType = methodType;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
///
public HarmonyPatch(string methodName)
{
info.methodName = methodName;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
///
public HarmonyPatch(string methodName, params Type[] argumentTypes)
{
info.methodName = methodName;
info.argumentTypes = argumentTypes;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
/// <param name="argumentVariations">An array of <see cref="ArgumentType"/></param>
///
public HarmonyPatch(string methodName, Type[] argumentTypes, ArgumentType[] argumentVariations)
{
info.methodName = methodName;
ParseSpecialArguments(argumentTypes, argumentVariations);
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
/// <param name="methodType">The <see cref="MethodType"/></param>
///
public HarmonyPatch(string methodName, MethodType methodType)
{
info.methodName = methodName;
info.methodType = methodType;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="methodType">The <see cref="MethodType"/></param>
///
public HarmonyPatch(MethodType methodType)
{
info.methodType = methodType;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="methodType">The <see cref="MethodType"/></param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
///
public HarmonyPatch(MethodType methodType, params Type[] argumentTypes)
{
info.methodType = methodType;
info.argumentTypes = argumentTypes;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="methodType">The <see cref="MethodType"/></param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
/// <param name="argumentVariations">An array of <see cref="ArgumentType"/></param>
///
public HarmonyPatch(MethodType methodType, Type[] argumentTypes, ArgumentType[] argumentVariations)
{
info.methodType = methodType;
ParseSpecialArguments(argumentTypes, argumentVariations);
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
///
public HarmonyPatch(Type[] argumentTypes)
{
info.argumentTypes = argumentTypes;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
/// <param name="argumentVariations">An array of <see cref="ArgumentType"/></param>
///
public HarmonyPatch(Type[] argumentTypes, ArgumentType[] argumentVariations)
{
ParseSpecialArguments(argumentTypes, argumentVariations);
}
void ParseSpecialArguments(Type[] argumentTypes, ArgumentType[] argumentVariations)
{
if (argumentVariations is null || argumentVariations.Length == 0)
{
info.argumentTypes = argumentTypes;
return;
}
if (argumentTypes.Length < argumentVariations.Length)
throw new ArgumentException("argumentVariations contains more elements than argumentTypes", nameof(argumentVariations));
var types = new List<Type>();
for (var i = 0; i < argumentTypes.Length; i++)
{
var type = argumentTypes[i];
switch (argumentVariations[i])
{
case ArgumentType.Normal:
break;
case ArgumentType.Ref:
case ArgumentType.Out:
type = type.MakeByRefType();
break;
case ArgumentType.Pointer:
type = type.MakePointerType();
break;
}
types.Add(type);
}
info.argumentTypes = types.ToArray();
}
}
/// <summary>Annotation to define the original method for delegate injection</summary>
///
[AttributeUsage(AttributeTargets.Delegate, AllowMultiple = true)]
public class HarmonyDelegate : HarmonyPatch
{
/// <summary>An annotation that specifies a class to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
///
public HarmonyDelegate(Type declaringType)
: base(declaringType) { }
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="argumentTypes">The argument types of the method or constructor to patch</param>
///
public HarmonyDelegate(Type declaringType, Type[] argumentTypes)
: base(declaringType, argumentTypes) { }
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
///
public HarmonyDelegate(Type declaringType, string methodName)
: base(declaringType, methodName) { }
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
///
public HarmonyDelegate(Type declaringType, string methodName, params Type[] argumentTypes)
: base(declaringType, methodName, argumentTypes) { }
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
/// <param name="argumentVariations">Array of <see cref="ArgumentType"/></param>
///
public HarmonyDelegate(Type declaringType, string methodName, Type[] argumentTypes, ArgumentType[] argumentVariations)
: base(declaringType, methodName, argumentTypes, argumentVariations) { }
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="methodDispatchType">The <see cref="MethodDispatchType"/></param>
///
public HarmonyDelegate(Type declaringType, MethodDispatchType methodDispatchType)
: base(declaringType, MethodType.Normal)
{
info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="methodDispatchType">The <see cref="MethodDispatchType"/></param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
///
public HarmonyDelegate(Type declaringType, MethodDispatchType methodDispatchType, params Type[] argumentTypes)
: base(declaringType, MethodType.Normal, argumentTypes)
{
info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="methodDispatchType">The <see cref="MethodDispatchType"/></param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
/// <param name="argumentVariations">Array of <see cref="ArgumentType"/></param>
///
public HarmonyDelegate(Type declaringType, MethodDispatchType methodDispatchType, Type[] argumentTypes, ArgumentType[] argumentVariations)
: base(declaringType, MethodType.Normal, argumentTypes, argumentVariations)
{
info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
/// <param name="methodDispatchType">The <see cref="MethodDispatchType"/></param>
///
public HarmonyDelegate(Type declaringType, string methodName, MethodDispatchType methodDispatchType)
: base(declaringType, methodName, MethodType.Normal)
{
info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
///
public HarmonyDelegate(string methodName)
: base(methodName) { }
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
///
public HarmonyDelegate(string methodName, params Type[] argumentTypes)
: base(methodName, argumentTypes) { }
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
/// <param name="argumentVariations">An array of <see cref="ArgumentType"/></param>
///
public HarmonyDelegate(string methodName, Type[] argumentTypes, ArgumentType[] argumentVariations)
: base(methodName, argumentTypes, argumentVariations) { }
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
/// <param name="methodDispatchType">The <see cref="MethodDispatchType"/></param>
///
public HarmonyDelegate(string methodName, MethodDispatchType methodDispatchType)
: base(methodName, MethodType.Normal)
{
info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
}
/// <summary>An annotation that specifies call dispatching mechanics for the delegate</summary>
/// <param name="methodDispatchType">The <see cref="MethodDispatchType"/></param>
///
public HarmonyDelegate(MethodDispatchType methodDispatchType)
{
info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="methodDispatchType">The <see cref="MethodDispatchType"/></param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
///
public HarmonyDelegate(MethodDispatchType methodDispatchType, params Type[] argumentTypes)
: base(MethodType.Normal, argumentTypes)
{
info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="methodDispatchType">The <see cref="MethodDispatchType"/></param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
/// <param name="argumentVariations">An array of <see cref="ArgumentType"/></param>
///
public HarmonyDelegate(MethodDispatchType methodDispatchType, Type[] argumentTypes, ArgumentType[] argumentVariations)
: base(MethodType.Normal, argumentTypes, argumentVariations)
{
info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
///
public HarmonyDelegate(Type[] argumentTypes)
: base(argumentTypes) { }
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
/// <param name="argumentVariations">An array of <see cref="ArgumentType"/></param>
///
public HarmonyDelegate(Type[] argumentTypes, ArgumentType[] argumentVariations)
: base(argumentTypes, argumentVariations) { }
}
/// <summary>Annotation to define your standin methods for reverse patching</summary>
///
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class HarmonyReversePatch : HarmonyAttribute
{
/// <summary>An annotation that specifies the type of reverse patching</summary>
/// <param name="type">The <see cref="HarmonyReversePatchType"/> of the reverse patch</param>
///
public HarmonyReversePatch(HarmonyReversePatchType type = HarmonyReversePatchType.Original)
{
info.reversePatchType = type;
}
}
/// <summary>A Harmony annotation to define that all methods in a class are to be patched</summary>
///
[AttributeUsage(AttributeTargets.Class)]
public class HarmonyPatchAll : HarmonyAttribute
{
}
/// <summary>A Harmony annotation</summary>
///
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class HarmonyPriority : HarmonyAttribute
{
/// <summary>A Harmony annotation to define patch priority</summary>
/// <param name="priority">The priority</param>
///
public HarmonyPriority(int priority)
{
info.priority = priority;
}
}
/// <summary>A Harmony annotation</summary>
///
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class HarmonyBefore : HarmonyAttribute
{
/// <summary>A Harmony annotation to define that a patch comes before another patch</summary>
/// <param name="before">The array of harmony IDs of the other patches</param>
///
public HarmonyBefore(params string[] before)
{
info.before = before;
}
}
/// <summary>A Harmony annotation</summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class HarmonyAfter : HarmonyAttribute
{
/// <summary>A Harmony annotation to define that a patch comes after another patch</summary>
/// <param name="after">The array of harmony IDs of the other patches</param>
///
public HarmonyAfter(params string[] after)
{
info.after = after;
}
}
/// <summary>A Harmony annotation</summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class HarmonyDebug : HarmonyAttribute
{
/// <summary>A Harmony annotation to debug a patch (output uses <see cref="FileLog"/> to log to your Desktop)</summary>
///
public HarmonyDebug()
{
info.debug = true;
}
}
/// <summary>Specifies the Prepare function in a patch class</summary>
///
[AttributeUsage(AttributeTargets.Method)]
public class HarmonyPrepare : Attribute
{
}
/// <summary>Specifies the Cleanup function in a patch class</summary>
///
[AttributeUsage(AttributeTargets.Method)]
public class HarmonyCleanup : Attribute
{
}
/// <summary>Specifies the TargetMethod function in a patch class</summary>
///
[AttributeUsage(AttributeTargets.Method)]
public class HarmonyTargetMethod : Attribute
{
}
/// <summary>Specifies the TargetMethods function in a patch class</summary>
///
[AttributeUsage(AttributeTargets.Method)]
public class HarmonyTargetMethods : Attribute
{
}
/// <summary>Specifies the Prefix function in a patch class</summary>
///
[AttributeUsage(AttributeTargets.Method)]
public class HarmonyPrefix : Attribute
{
}
/// <summary>Specifies the Postfix function in a patch class</summary>
///
[AttributeUsage(AttributeTargets.Method)]
public class HarmonyPostfix : Attribute
{
}
/// <summary>Specifies the Transpiler function in a patch class</summary>
///
[AttributeUsage(AttributeTargets.Method)]
public class HarmonyTranspiler : Attribute
{
}
/// <summary>Specifies the Finalizer function in a patch class</summary>
///
[AttributeUsage(AttributeTargets.Method)]
public class HarmonyFinalizer : Attribute
{
}
/// <summary>A Harmony annotation</summary>
///
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true)]
public class HarmonyArgument : Attribute
{
/// <summary>The name of the original argument</summary>
///
public string OriginalName { get; private set; }
/// <summary>The index of the original argument</summary>
///
public int Index { get; private set; }
/// <summary>The new name of the original argument</summary>
///
public string NewName { get; private set; }
/// <summary>An annotation to declare injected arguments by name</summary>
///
public HarmonyArgument(string originalName) : this(originalName, null)
{
}
/// <summary>An annotation to declare injected arguments by index</summary>
/// <param name="index">Zero-based index</param>
///
public HarmonyArgument(int index) : this(index, null)
{
}
/// <summary>An annotation to declare injected arguments by renaming them</summary>
/// <param name="originalName">Name of the original argument</param>
/// <param name="newName">New name</param>
///
public HarmonyArgument(string originalName, string newName)
{
OriginalName = originalName;
Index = -1;
NewName = newName;
}
/// <summary>An annotation to declare injected arguments by index and renaming them</summary>
/// <param name="index">Zero-based index</param>
/// <param name="name">New name</param>
///
public HarmonyArgument(int index, string name)
{
OriginalName = null;
Index = index;
NewName = name;
}
}
}
| pardeike/Harmony | Harmony/Public/Attributes.cs | C# | mit | 27,094 |
<?php
namespace MyApplication\Navigation\Navigation;
interface NavigationControlFactory
{
/**
* @return NavigationControl
*/
function create();
}
| Joseki/Sandbox | app/MyApplication/Navigation/Navigation/NavigationControlFactory.php | PHP | mit | 166 |
# Declaring a Function
def recurPowerNew(base, exp):
# Base case is when exp = 0
if exp <= 0:
return 1
# Recursive Call
elif exp % 2 == 0:
return recurPowerNew(base*base, exp/2)
return base * recurPowerNew(base, exp - 1)
| jabhij/MITx-6.00.1x-Python- | Week-3/L5/Prob3.py | Python | mit | 268 |
import * as riot from 'riot'
import { init, compile } from '../../helpers/'
import TargetComponent from '../../../dist/tags/popup/su-popup.js'
describe('su-popup', function () {
let element, component
let spyOnMouseover, spyOnMouseout
init(riot)
const mount = opts => {
const option = Object.assign({
'onmouseover': spyOnMouseover,
'onmouseout': spyOnMouseout,
}, opts)
element = document.createElement('app')
riot.register('su-popup', TargetComponent)
const AppComponent = compile(`
<app>
<su-popup
tooltip="{ props.tooltip }"
data-title="{ props.dataTitle }"
data-variation="{ props.dataVariation }"
onmouseover="{ () => dispatch('mouseover') }"
onmouseout="{ () => dispatch('mouseout') }"
><i class="add icon"></i></su-popup>
</app>`)
riot.register('app', AppComponent)
component = riot.mount(element, option)[0]
}
beforeEach(function () {
spyOnMouseover = sinon.spy()
spyOnMouseout = sinon.spy()
})
afterEach(function () {
riot.unregister('su-popup')
riot.unregister('app')
})
it('is mounted', function () {
mount()
expect(component).to.be.ok
})
it('show and hide popup', function () {
mount({
tooltip: 'Add users to your feed'
})
expect(component.$('.content').innerHTML).to.equal('Add users to your feed')
expect(component.$('su-popup .ui.popup').classList.contains('nowrap')).to.equal(true)
fireEvent(component.$('su-popup .ui.popup'), 'mouseover')
expect(spyOnMouseover).to.have.been.calledOnce
expect(component.$('su-popup .ui.popup').classList.contains('visible')).to.equal(true)
expect(component.$('su-popup .ui.popup').classList.contains('hidden')).to.equal(false)
fireEvent(component.$('su-popup .ui.popup'), 'mouseout')
expect(spyOnMouseout).to.have.been.calledOnce
expect(component.$('su-popup .ui.popup').classList.contains('visible')).to.equal(false)
expect(component.$('su-popup .ui.popup').classList.contains('hidden')).to.equal(true)
})
it('header', function () {
mount({
tooltip: 'Add users to your feed',
dataTitle: 'Title'
})
expect(component.$('.header').innerHTML).to.equal('Title')
expect(component.$('.content').innerHTML).to.equal('Add users to your feed')
})
it('wide', function () {
mount({
tooltip: 'Add users to your feed',
dataVariation: 'wide'
})
expect(component.$('su-popup .ui.popup').classList.contains('wide')).to.equal(true)
expect(component.$('su-popup .ui.popup').classList.contains('nowrap')).to.equal(false)
})
})
| black-trooper/semantic-ui-riot | test/spec/popup/su-popup.spec.js | JavaScript | mit | 2,656 |
require "graph_engine/engine"
module GraphEngine
end
| kenegozi/graph_engine | lib/graph_engine.rb | Ruby | mit | 54 |
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { SharedModule, ExamplesRouterViewerComponent } from '../../../shared';
import { AppModule } from './app.module';
import { AppComponent } from './app.component';
@NgModule({
imports: [
SharedModule,
AppModule,
RouterModule.forChild([
{
path: '',
component: ExamplesRouterViewerComponent,
data: {
examples: [
{
title: 'Material Prefix and Suffix',
description: `
This demonstrates adding a material suffix and prefix for material form fields.
`,
component: AppComponent,
files: [
{
file: 'app.component.html',
content: require('!!highlight-loader?raw=true&lang=html!./app.component.html'),
filecontent: require('!!raw-loader!./app.component.html'),
},
{
file: 'app.component.ts',
content: require('!!highlight-loader?raw=true&lang=typescript!./app.component.ts'),
filecontent: require('!!raw-loader!./app.component.ts'),
},
{
file: 'addons.wrapper.ts',
content: require('!!highlight-loader?raw=true&lang=typescript!./addons.wrapper.ts'),
filecontent: require('!!raw-loader!./addons.wrapper.ts'),
},
{
file: 'addons.extension.ts',
content: require('!!highlight-loader?raw=true&lang=typescript!./addons.extension.ts'),
filecontent: require('!!raw-loader!./addons.extension.ts'),
},
{
file: 'app.module.ts',
content: require('!!highlight-loader?raw=true&lang=typescript!./app.module.ts'),
filecontent: require('!!raw-loader!./app.module.ts'),
},
],
},
],
},
},
]),
],
})
export class ConfigModule {}
| ngx-formly/ngx-formly | demo/src/app/examples/other/material-prefix-suffix/config.module.ts | TypeScript | mit | 2,128 |
const jwt = require('jsonwebtoken');
const User = require('../models/User');
// import { port, auth } from '../../config';
/**
* The Auth Checker middleware function.
*/
module.exports = (req, res, next) => {
if (!req.headers.authorization) {
return res.status(401).end();
}
// get the last part from a authorization header string like "bearer token-value"
const token = req.headers.authorization.split(' ')[1];
// decode the token using a secret key-phrase
return jwt.verify(token, "React Starter Kit", (err, decoded) => {
// the 401 code is for unauthorized status
if (err) { return res.status(401).end(); }
const userId = decoded.sub;
// check if a user exists
return User.findById(userId, (userErr, user) => {
if (userErr || !user) {
return res.status(401).end();
}
return next();
});
});
};
| ziedAb/PVMourakiboun | src/data/middleware/auth-check.js | JavaScript | mit | 874 |
//10. Odd and Even Product
//You are given n integers (given in a single line, separated by a space).
//Write a program that checks whether the product of the odd elements is equal to the product of the even elements.
//Elements are counted from 1 to n, so the first element is odd, the second is even, etc.
using System;
class OddAndEvenProduct
{
static void Main()
{
Console.WriteLine("Odd And Even Product");
Console.Write("Enter a numbers in a single line separated with space: ");
string[] input = Console.ReadLine().Split();
int oddProduct = 1;
int evenProdduct = 1;
for (int index = 0; index < input.Length; index++)
{
int num = int.Parse(input[index]);
if (index %2 == 0 || index == 0)
{
oddProduct *= num;
}
else
{
evenProdduct *= num;
}
}
if (oddProduct == evenProdduct)
{
Console.WriteLine("yes");
Console.WriteLine("product = {0}", oddProduct);
}
else
{
Console.WriteLine("no");
Console.WriteLine("odd Product = {0}", oddProduct);
Console.WriteLine("even Product = {0}", evenProdduct);
}
}
}
| HMNikolova/Telerik_Academy | CSharpPartOne/6. Loops/10. OddAndEvenProduct/OddAndEvenProduct.cs | C# | mit | 1,480 |
var Ringpop = require('ringpop');
var TChannel = require('TChannel');
var express = require('express');
var NodeCache = require('node-cache');
var cache = new NodeCache();
var host = '127.0.0.1'; // not recommended for production
var httpPort = process.env.PORT || 8080;
var port = httpPort - 5080;
var bootstrapNodes = ['127.0.0.1:3000'];
var tchannel = new TChannel();
var subChannel = tchannel.makeSubChannel({
serviceName: 'ringpop',
trace: false
});
var ringpop = new Ringpop({
app: 'yourapp',
hostPort: host + ':' + port,
channel: subChannel
});
ringpop.setupChannel();
ringpop.channel.listen(port, host, function onListen() {
console.log('TChannel is listening on ' + port);
ringpop.bootstrap(bootstrapNodes,
function onBootstrap(err) {
if (err) {
console.log('Error: Could not bootstrap ' + ringpop.whoami());
process.exit(1);
}
console.log('Ringpop ' + ringpop.whoami() + ' has bootstrapped!');
});
// This is how you wire up a handler for forwarded requests
ringpop.on('request', handleReq);
});
var server = express();
server.get('/*', onReq);
server.listen(httpPort, function onListen() {
console.log('Server is listening on ' + httpPort);
});
function extractKey(req) {
var urlParts = req.url.split('/');
if (urlParts.length < 3) return ''; // URL does not have 2 parts...
return urlParts[1];
}
function onReq(req, res) {
var key = extractKey(req);
if (ringpop.handleOrProxy(key, req, res)) {
handleReq(req, res);
}
}
function handleReq(req, res) {
cache.get(req.url, function(err, value) {
if (value == undefined) {
var key = extractKey(req);
var result = host + ':' + port + ' is responsible for ' + key;
cache.set(req.url, result, function(err, success) {
if (!err && success) {
res.end(result + ' NOT CACHED');
}
});
} else {
res.end(value + ' CACHED');
}
});
}
| Andras-Simon/nodebp | second.js | JavaScript | mit | 1,982 |
Element.prototype.remove = function() {
this.parentElement.removeChild(this);
}
const addIcon = (icon) => `<i class="fa fa-${icon}"></i>`
const headerTxt = (type) => {
switch (type) {
case 'error':
return `${addIcon('ban')} Error`
case 'warning':
return `${addIcon('exclamation')} Warning`
case 'success':
return `${addIcon('check')} Success`
default:
return `${addIcon('ban')} Error`
}
}
const createModal = (texto, type) => {
let modal = document.createElement('div')
modal.classList = 'modal-background'
let headertxt = 'Error'
let content = `
<div class="modal-frame">
<header class="modal-${type} modal-header">
<h4> ${headerTxt(type)} </h4>
<span id="closeModal">×</span>
</header>
<div class="modal-mssg"> ${texto} </div>
<button id="btnAcceptModal" class="btn modal-btn modal-${type}">Aceptar</button>
</div>
`
modal.innerHTML = content
document.body.appendChild(modal)
document.getElementById('btnAcceptModal').addEventListener('click', () => modal.remove())
document.getElementById('closeModal').addEventListener('click', () => modal.remove())
}
export const errorModal = (message) => createModal(message, 'error')
export const successModal = (message) => createModal(message, 'success')
export const warningModal = (message) => createModal(message, 'warning')
| jcarral/Subsub | build/script/lib/modals.js | JavaScript | mit | 1,439 |
<?php
/*
* This file is part of Rocketeer
*
* (c) Maxime Fabre <ehtnam6@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
*/
namespace Rocketeer\Services\History;
use Illuminate\Support\Collection;
/**
* Keeps a memory of everything that was outputed/ran
* and on which connections/stages.
*/
class History extends Collection
{
/**
* Get the history, flattened.
*
* @return string[]|string[][]
*/
public function getFlattenedHistory()
{
return $this->getFlattened('history');
}
/**
* Get the output, flattened.
*
* @return string[]|string[][]
*/
public function getFlattenedOutput()
{
return $this->getFlattened('output');
}
/**
* Reset the history/output.
*/
public function reset()
{
$this->items = [];
}
//////////////////////////////////////////////////////////////////////
////////////////////////////// HELPERS ///////////////////////////////
//////////////////////////////////////////////////////////////////////
/**
* Get a flattened list of a certain type.
*
* @param string $type
*
* @return string[]|string[][]
*/
protected function getFlattened($type)
{
$history = [];
foreach ($this->items as $class => $entries) {
$history = array_merge($history, $entries[$type]);
}
ksort($history);
return array_values($history);
}
}
| rocketeers/rocketeer | src/Rocketeer/Services/History/History.php | PHP | mit | 1,576 |
<?php
/**
* Created by PhpStorm.
* User: olivier
* Date: 01/02/15
* Time: 00:58
*/
namespace AppBundle\Entity;
use Doctrine\ORM\EntityRepository;
/**
* BusinessServiceRepository
*/
class BusinessServiceRepository extends EntityRepository
{
public function findByRefList(array $refList)
{
$qb = $this->createQueryBuilder('s');
$qb->where($qb->expr()->in('s.ref', $refList));
return $qb->getQuery()->execute();
}
public function findEnabled()
{
return $this->findBy(array('enabled' => '1'));
}
/**
* get services enabled only by default or with a suffix if $filterEnabled=false
* @param bool $filterEnabled
* @return array
*/
public function getChoices($filterEnabled = true)
{
if ($filterEnabled) {
}
$qb = $this->createQueryBuilder('s');
$qb->select('s.ref, s.name, s.enabled');
$results = $qb->getQuery()->execute();
$choices = [];
foreach ($results as $item) {
if ($item['enabled'] === true) {
$choices[$item['ref']] = $item['name'];
} else {
if ($filterEnabled === false) {
$choices[$item['ref']] = sprintf('%s (désactivé)', $item['name']);
} else {
unset($choices[$item['ref']]);
}
}
}
return $choices;
}
} | casual-web/autodom | src/AppBundle/Entity/BusinessServiceRepository.php | PHP | mit | 1,434 |
package br.com.k19.android.cap3;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.frame);
}
}
| andersonsilvade/workspacejava | Workspaceandroid/MainActivity/src/br/com/k19/android/cap3/MainActivity.java | Java | mit | 280 |
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Lioncoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "base58.h"
#include "core.h"
#include "init.h"
#include "keystore.h"
#include "main.h"
#include "net.h"
#include "rpcserver.h"
#include "uint256.h"
#ifdef ENABLE_WALLET
#include "wallet.h"
#endif
#include <stdint.h>
#include <boost/assign/list_of.hpp>
#include "json/json_spirit_utils.h"
#include "json/json_spirit_value.h"
using namespace std;
using namespace boost;
using namespace boost::assign;
using namespace json_spirit;
void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out, bool fIncludeHex)
{
txnouttype type;
vector<CTxDestination> addresses;
int nRequired;
out.push_back(Pair("asm", scriptPubKey.ToString()));
if (fIncludeHex)
out.push_back(Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end())));
if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired))
{
out.push_back(Pair("type", GetTxnOutputType(type)));
return;
}
out.push_back(Pair("reqSigs", nRequired));
out.push_back(Pair("type", GetTxnOutputType(type)));
Array a;
BOOST_FOREACH(const CTxDestination& addr, addresses)
a.push_back(CLioncoinAddress(addr).ToString());
out.push_back(Pair("addresses", a));
}
void TxToJSON(const CTransaction& tx, const uint256 hashBlock, Object& entry)
{
entry.push_back(Pair("txid", tx.GetHash().GetHex()));
entry.push_back(Pair("version", tx.nVersion));
entry.push_back(Pair("locktime", (boost::int64_t)tx.nLockTime));
Array vin;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
Object in;
if (tx.IsCoinBase())
in.push_back(Pair("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
else
{
in.push_back(Pair("txid", txin.prevout.hash.GetHex()));
in.push_back(Pair("vout", (boost::int64_t)txin.prevout.n));
Object o;
o.push_back(Pair("asm", txin.scriptSig.ToString()));
o.push_back(Pair("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
in.push_back(Pair("scriptSig", o));
}
in.push_back(Pair("sequence", (boost::int64_t)txin.nSequence));
vin.push_back(in);
}
entry.push_back(Pair("vin", vin));
Array vout;
for (unsigned int i = 0; i < tx.vout.size(); i++)
{
const CTxOut& txout = tx.vout[i];
Object out;
out.push_back(Pair("value", ValueFromAmount(txout.nValue)));
out.push_back(Pair("n", (boost::int64_t)i));
Object o;
ScriptPubKeyToJSON(txout.scriptPubKey, o, true);
out.push_back(Pair("scriptPubKey", o));
vout.push_back(out);
}
entry.push_back(Pair("vout", vout));
if (hashBlock != 0)
{
entry.push_back(Pair("blockhash", hashBlock.GetHex()));
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end() && (*mi).second)
{
CBlockIndex* pindex = (*mi).second;
if (chainActive.Contains(pindex))
{
entry.push_back(Pair("confirmations", 1 + chainActive.Height() - pindex->nHeight));
entry.push_back(Pair("time", (boost::int64_t)pindex->nTime));
entry.push_back(Pair("blocktime", (boost::int64_t)pindex->nTime));
}
else
entry.push_back(Pair("confirmations", 0));
}
}
}
Value getrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getrawtransaction \"txid\" ( verbose )\n"
"\nReturn the raw transaction data.\n"
"\nIf verbose=0, returns a string that is serialized, hex-encoded data for 'txid'.\n"
"If verbose is non-zero, returns an Object with information about 'txid'.\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id\n"
"2. verbose (numeric, optional, default=0) If 0, return a string, other return a json object\n"
"\nResult (if verbose is not set or set to 0):\n"
"\"data\" (string) The serialized, hex-encoded data for 'txid'\n"
"\nResult (if verbose > 0):\n"
"{\n"
" \"hex\" : \"data\", (string) The serialized, hex-encoded data for 'txid'\n"
" \"txid\" : \"id\", (string) The transaction id (same as provided)\n"
" \"version\" : n, (numeric) The version\n"
" \"locktime\" : ttt, (numeric) The lock time\n"
" \"vin\" : [ (array of json objects)\n"
" {\n"
" \"txid\": \"id\", (string) The transaction id\n"
" \"vout\": n, (numeric) \n"
" \"scriptSig\": { (json object) The script\n"
" \"asm\": \"asm\", (string) asm\n"
" \"hex\": \"hex\" (string) hex\n"
" },\n"
" \"sequence\": n (numeric) The script sequence number\n"
" }\n"
" ,...\n"
" ],\n"
" \"vout\" : [ (array of json objects)\n"
" {\n"
" \"value\" : x.xxx, (numeric) The value in btc\n"
" \"n\" : n, (numeric) index\n"
" \"scriptPubKey\" : { (json object)\n"
" \"asm\" : \"asm\", (string) the asm\n"
" \"hex\" : \"hex\", (string) the hex\n"
" \"reqSigs\" : n, (numeric) The required sigs\n"
" \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
" \"addresses\" : [ (json array of string)\n"
" \"lioncoinaddress\" (string) lioncoin address\n"
" ,...\n"
" ]\n"
" }\n"
" }\n"
" ,...\n"
" ],\n"
" \"blockhash\" : \"hash\", (string) the block hash\n"
" \"confirmations\" : n, (numeric) The confirmations\n"
" \"time\" : ttt, (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"blocktime\" : ttt (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getrawtransaction", "\"mytxid\"")
+ HelpExampleCli("getrawtransaction", "\"mytxid\" 1")
+ HelpExampleRpc("getrawtransaction", "\"mytxid\", 1")
);
uint256 hash = ParseHashV(params[0], "parameter 1");
bool fVerbose = false;
if (params.size() > 1)
fVerbose = (params[1].get_int() != 0);
CTransaction tx;
uint256 hashBlock = 0;
if (!GetTransaction(hash, tx, hashBlock, true))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << tx;
string strHex = HexStr(ssTx.begin(), ssTx.end());
if (!fVerbose)
return strHex;
Object result;
result.push_back(Pair("hex", strHex));
TxToJSON(tx, hashBlock, result);
return result;
}
#ifdef ENABLE_WALLET
Value listunspent(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 3)
throw runtime_error(
"listunspent ( minconf maxconf [\"address\",...] )\n"
"\nReturns array of unspent transaction outputs\n"
"with between minconf and maxconf (inclusive) confirmations.\n"
"Optionally filter to only include txouts paid to specified addresses.\n"
"Results are an array of Objects, each of which has:\n"
"{txid, vout, scriptPubKey, amount, confirmations}\n"
"\nArguments:\n"
"1. minconf (numeric, optional, default=1) The minimum confirmationsi to filter\n"
"2. maxconf (numeric, optional, default=9999999) The maximum confirmations to filter\n"
"3. \"addresses\" (string) A json array of lioncoin addresses to filter\n"
" [\n"
" \"address\" (string) lioncoin address\n"
" ,...\n"
" ]\n"
"\nResult\n"
"[ (array of json object)\n"
" {\n"
" \"txid\" : \"txid\", (string) the transaction id \n"
" \"vout\" : n, (numeric) the vout value\n"
" \"address\" : \"address\", (string) the lioncoin address\n"
" \"account\" : \"account\", (string) The associated account, or \"\" for the default account\n"
" \"scriptPubKey\" : \"key\", (string) the script key\n"
" \"amount\" : x.xxx, (numeric) the transaction amount in btc\n"
" \"confirmations\" : n (numeric) The number of confirmations\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples\n"
+ HelpExampleCli("listunspent", "")
+ HelpExampleCli("listunspent", "6 9999999 \"[\\\"1PGFqEzfmQch1gKD3ra4k18PNj3tTUUSqg\\\",\\\"1LtvqCaApEdUGFkpKMM4MstjcaL4dKg8SP\\\"]\"")
+ HelpExampleRpc("listunspent", "6, 9999999 \"[\\\"1PGFqEzfmQch1gKD3ra4k18PNj3tTUUSqg\\\",\\\"1LtvqCaApEdUGFkpKMM4MstjcaL4dKg8SP\\\"]\"")
);
RPCTypeCheck(params, list_of(int_type)(int_type)(array_type));
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
int nMaxDepth = 9999999;
if (params.size() > 1)
nMaxDepth = params[1].get_int();
set<CLioncoinAddress> setAddress;
if (params.size() > 2)
{
Array inputs = params[2].get_array();
BOOST_FOREACH(Value& input, inputs)
{
CLioncoinAddress address(input.get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Lioncoin address: ")+input.get_str());
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+input.get_str());
setAddress.insert(address);
}
}
Array results;
vector<COutput> vecOutputs;
assert(pwalletMain != NULL);
pwalletMain->AvailableCoins(vecOutputs, false);
BOOST_FOREACH(const COutput& out, vecOutputs)
{
if (out.nDepth < nMinDepth || out.nDepth > nMaxDepth)
continue;
if (setAddress.size())
{
CTxDestination address;
if (!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address))
continue;
if (!setAddress.count(address))
continue;
}
int64_t nValue = out.tx->vout[out.i].nValue;
const CScript& pk = out.tx->vout[out.i].scriptPubKey;
Object entry;
entry.push_back(Pair("txid", out.tx->GetHash().GetHex()));
entry.push_back(Pair("vout", out.i));
CTxDestination address;
if (ExtractDestination(out.tx->vout[out.i].scriptPubKey, address))
{
entry.push_back(Pair("address", CLioncoinAddress(address).ToString()));
if (pwalletMain->mapAddressBook.count(address))
entry.push_back(Pair("account", pwalletMain->mapAddressBook[address].name));
}
entry.push_back(Pair("scriptPubKey", HexStr(pk.begin(), pk.end())));
if (pk.IsPayToScriptHash())
{
CTxDestination address;
if (ExtractDestination(pk, address))
{
const CScriptID& hash = boost::get<const CScriptID&>(address);
CScript redeemScript;
if (pwalletMain->GetCScript(hash, redeemScript))
entry.push_back(Pair("redeemScript", HexStr(redeemScript.begin(), redeemScript.end())));
}
}
entry.push_back(Pair("amount",ValueFromAmount(nValue)));
entry.push_back(Pair("confirmations",out.nDepth));
results.push_back(entry);
}
return results;
}
#endif
Value createrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw runtime_error(
"createrawtransaction [{\"txid\":\"id\",\"vout\":n},...] {\"address\":amount,...}\n"
"\nCreate a transaction spending the given inputs and sending to the given addresses.\n"
"Returns hex-encoded raw transaction.\n"
"Note that the transaction's inputs are not signed, and\n"
"it is not stored in the wallet or transmitted to the network.\n"
"\nArguments:\n"
"1. \"transactions\" (string, required) A json array of json objects\n"
" [\n"
" {\n"
" \"txid\":\"id\", (string, required) The transaction id\n"
" \"vout\":n (numeric, required) The output number\n"
" }\n"
" ,...\n"
" ]\n"
"2. \"addresses\" (string, required) a json object with addresses as keys and amounts as values\n"
" {\n"
" \"address\": x.xxx (numeric, required) The key is the lioncoin address, the value is the btc amount\n"
" ,...\n"
" }\n"
"\nResult:\n"
"\"transaction\" (string) hex string of the transaction\n"
"\nExamples\n"
+ HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"address\\\":0.01}\"")
+ HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"address\\\":0.01}\"")
);
RPCTypeCheck(params, list_of(array_type)(obj_type));
Array inputs = params[0].get_array();
Object sendTo = params[1].get_obj();
CTransaction rawTx;
BOOST_FOREACH(const Value& input, inputs)
{
const Object& o = input.get_obj();
uint256 txid = ParseHashO(o, "txid");
const Value& vout_v = find_value(o, "vout");
if (vout_v.type() != int_type)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
int nOutput = vout_v.get_int();
if (nOutput < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
CTxIn in(COutPoint(txid, nOutput));
rawTx.vin.push_back(in);
}
set<CLioncoinAddress> setAddress;
BOOST_FOREACH(const Pair& s, sendTo)
{
CLioncoinAddress address(s.name_);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Lioncoin address: ")+s.name_);
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_);
setAddress.insert(address);
CScript scriptPubKey;
scriptPubKey.SetDestination(address.Get());
int64_t nAmount = AmountFromValue(s.value_);
CTxOut out(nAmount, scriptPubKey);
rawTx.vout.push_back(out);
}
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << rawTx;
return HexStr(ss.begin(), ss.end());
}
Value decoderawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"decoderawtransaction \"hexstring\"\n"
"\nReturn a JSON object representing the serialized, hex-encoded transaction.\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction hex string\n"
"\nResult:\n"
"{\n"
" \"hex\" : \"data\", (string) The serialized, hex-encoded data for 'txid'\n"
" \"txid\" : \"id\", (string) The transaction id (same as provided)\n"
" \"version\" : n, (numeric) The version\n"
" \"locktime\" : ttt, (numeric) The lock time\n"
" \"vin\" : [ (array of json objects)\n"
" {\n"
" \"txid\": \"id\", (string) The transaction id\n"
" \"vout\": n, (numeric) The output number\n"
" \"scriptSig\": { (json object) The script\n"
" \"asm\": \"asm\", (string) asm\n"
" \"hex\": \"hex\" (string) hex\n"
" },\n"
" \"sequence\": n (numeric) The script sequence number\n"
" }\n"
" ,...\n"
" ],\n"
" \"vout\" : [ (array of json objects)\n"
" {\n"
" \"value\" : x.xxx, (numeric) The value in btc\n"
" \"n\" : n, (numeric) index\n"
" \"scriptPubKey\" : { (json object)\n"
" \"asm\" : \"asm\", (string) the asm\n"
" \"hex\" : \"hex\", (string) the hex\n"
" \"reqSigs\" : n, (numeric) The required sigs\n"
" \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
" \"addresses\" : [ (json array of string)\n"
" \"12tvKAXCxZjSmdNbao16dKXC8tRWfcF5oc\" (string) lioncoin address\n"
" ,...\n"
" ]\n"
" }\n"
" }\n"
" ,...\n"
" ],\n"
" \"blockhash\" : \"hash\", (string) the block hash\n"
" \"confirmations\" : n, (numeric) The confirmations\n"
" \"time\" : ttt, (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"blocktime\" : ttt (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("decoderawtransaction", "\"hexstring\"")
+ HelpExampleRpc("decoderawtransaction", "\"hexstring\"")
);
vector<unsigned char> txData(ParseHexV(params[0], "argument"));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
CTransaction tx;
try {
ssData >> tx;
}
catch (std::exception &e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
Object result;
TxToJSON(tx, 0, result);
return result;
}
Value decodescript(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"decodescript \"hex\"\n"
"\nDecode a hex-encoded script.\n"
"\nArguments:\n"
"1. \"hex\" (string) the hex encoded script\n"
"\nResult:\n"
"{\n"
" \"asm\":\"asm\", (string) Script public key\n"
" \"hex\":\"hex\", (string) hex encoded public key\n"
" \"type\":\"type\", (string) The output type\n"
" \"reqSigs\": n, (numeric) The required signatures\n"
" \"addresses\": [ (json array of string)\n"
" \"address\" (string) lioncoin address\n"
" ,...\n"
" ],\n"
" \"p2sh\",\"address\" (string) script address\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("decodescript", "\"hexstring\"")
+ HelpExampleRpc("decodescript", "\"hexstring\"")
);
RPCTypeCheck(params, list_of(str_type));
Object r;
CScript script;
if (params[0].get_str().size() > 0){
vector<unsigned char> scriptData(ParseHexV(params[0], "argument"));
script = CScript(scriptData.begin(), scriptData.end());
} else {
// Empty scripts are valid
}
ScriptPubKeyToJSON(script, r, false);
r.push_back(Pair("p2sh", CLioncoinAddress(script.GetID()).ToString()));
return r;
}
Value signrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 4)
throw runtime_error(
"signrawtransaction \"hexstring\" ( [{\"txid\":\"id\",\"vout\":n,\"scriptPubKey\":\"hex\",\"redeemScript\":\"hex\"},...] [\"privatekey1\",...] sighashtype )\n"
"\nSign inputs for raw transaction (serialized, hex-encoded).\n"
"The second optional argument (may be null) is an array of previous transaction outputs that\n"
"this transaction depends on but may not yet be in the block chain.\n"
"The third optional argument (may be null) is an array of base58-encoded private\n"
"keys that, if given, will be the only keys used to sign the transaction.\n"
#ifdef ENABLE_WALLET
+ HelpRequiringPassphrase() + "\n"
#endif
"\nArguments:\n"
"1. \"hexstring\" (string, required) The transaction hex string\n"
"2. \"prevtxs\" (string, optional) An json array of previous dependent transaction outputs\n"
" [ (json array of json objects, or 'null' if none provided)\n"
" {\n"
" \"txid\":\"id\", (string, required) The transaction id\n"
" \"vout\":n, (numeric, required) The output number\n"
" \"scriptPubKey\": \"hex\", (string, required) script key\n"
" \"redeemScript\": \"hex\" (string, required) redeem script\n"
" }\n"
" ,...\n"
" ]\n"
"3. \"privatekeys\" (string, optional) A json array of base58-encoded private keys for signing\n"
" [ (json array of strings, or 'null' if none provided)\n"
" \"privatekey\" (string) private key in base58-encoding\n"
" ,...\n"
" ]\n"
"4. \"sighashtype\" (string, optional, default=ALL) The signature has type. Must be one of\n"
" \"ALL\"\n"
" \"NONE\"\n"
" \"SINGLE\"\n"
" \"ALL|ANYONECANPAY\"\n"
" \"NONE|ANYONECANPAY\"\n"
" \"SINGLE|ANYONECANPAY\"\n"
"\nResult:\n"
"{\n"
" \"hex\": \"value\", (string) The raw transaction with signature(s) (hex-encoded string)\n"
" \"complete\": n (numeric) if transaction has a complete set of signature (0 if not)\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("signrawtransaction", "\"myhex\"")
+ HelpExampleRpc("signrawtransaction", "\"myhex\"")
);
RPCTypeCheck(params, list_of(str_type)(array_type)(array_type)(str_type), true);
vector<unsigned char> txData(ParseHexV(params[0], "argument 1"));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
vector<CTransaction> txVariants;
while (!ssData.empty())
{
try {
CTransaction tx;
ssData >> tx;
txVariants.push_back(tx);
}
catch (std::exception &e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
}
if (txVariants.empty())
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transaction");
// mergedTx will end up with all the signatures; it
// starts as a clone of the rawtx:
CTransaction mergedTx(txVariants[0]);
bool fComplete = true;
// Fetch previous transactions (inputs):
CCoinsView viewDummy;
CCoinsViewCache view(viewDummy);
{
LOCK(mempool.cs);
CCoinsViewCache &viewChain = *pcoinsTip;
CCoinsViewMemPool viewMempool(viewChain, mempool);
view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
BOOST_FOREACH(const CTxIn& txin, mergedTx.vin) {
const uint256& prevHash = txin.prevout.hash;
CCoins coins;
view.GetCoins(prevHash, coins); // this is certainly allowed to fail
}
view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long
}
bool fGivenKeys = false;
CBasicKeyStore tempKeystore;
if (params.size() > 2 && params[2].type() != null_type)
{
fGivenKeys = true;
Array keys = params[2].get_array();
BOOST_FOREACH(Value k, keys)
{
CLioncoinSecret vchSecret;
bool fGood = vchSecret.SetString(k.get_str());
if (!fGood)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
CKey key = vchSecret.GetKey();
tempKeystore.AddKey(key);
}
}
#ifdef ENABLE_WALLET
else
EnsureWalletIsUnlocked();
#endif
// Add previous txouts given in the RPC call:
if (params.size() > 1 && params[1].type() != null_type)
{
Array prevTxs = params[1].get_array();
BOOST_FOREACH(Value& p, prevTxs)
{
if (p.type() != obj_type)
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
Object prevOut = p.get_obj();
RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type));
uint256 txid = ParseHashO(prevOut, "txid");
int nOut = find_value(prevOut, "vout").get_int();
if (nOut < 0)
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive");
vector<unsigned char> pkData(ParseHexO(prevOut, "scriptPubKey"));
CScript scriptPubKey(pkData.begin(), pkData.end());
CCoins coins;
if (view.GetCoins(txid, coins)) {
if (coins.IsAvailable(nOut) && coins.vout[nOut].scriptPubKey != scriptPubKey) {
string err("Previous output scriptPubKey mismatch:\n");
err = err + coins.vout[nOut].scriptPubKey.ToString() + "\nvs:\n"+
scriptPubKey.ToString();
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);
}
// what todo if txid is known, but the actual output isn't?
}
if ((unsigned int)nOut >= coins.vout.size())
coins.vout.resize(nOut+1);
coins.vout[nOut].scriptPubKey = scriptPubKey;
coins.vout[nOut].nValue = 0; // we don't know the actual output value
view.SetCoins(txid, coins);
// if redeemScript given and not using the local wallet (private keys
// given), add redeemScript to the tempKeystore so it can be signed:
if (fGivenKeys && scriptPubKey.IsPayToScriptHash())
{
RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type)("redeemScript",str_type));
Value v = find_value(prevOut, "redeemScript");
if (!(v == Value::null))
{
vector<unsigned char> rsData(ParseHexV(v, "redeemScript"));
CScript redeemScript(rsData.begin(), rsData.end());
tempKeystore.AddCScript(redeemScript);
}
}
}
}
#ifdef ENABLE_WALLET
const CKeyStore& keystore = ((fGivenKeys || !pwalletMain) ? tempKeystore : *pwalletMain);
#else
const CKeyStore& keystore = tempKeystore;
#endif
int nHashType = SIGHASH_ALL;
if (params.size() > 3 && params[3].type() != null_type)
{
static map<string, int> mapSigHashValues =
boost::assign::map_list_of
(string("ALL"), int(SIGHASH_ALL))
(string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY))
(string("NONE"), int(SIGHASH_NONE))
(string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY))
(string("SINGLE"), int(SIGHASH_SINGLE))
(string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY))
;
string strHashType = params[3].get_str();
if (mapSigHashValues.count(strHashType))
nHashType = mapSigHashValues[strHashType];
else
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param");
}
bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
// Sign what we can:
for (unsigned int i = 0; i < mergedTx.vin.size(); i++)
{
CTxIn& txin = mergedTx.vin[i];
CCoins coins;
if (!view.GetCoins(txin.prevout.hash, coins) || !coins.IsAvailable(txin.prevout.n))
{
fComplete = false;
continue;
}
const CScript& prevPubKey = coins.vout[txin.prevout.n].scriptPubKey;
txin.scriptSig.clear();
// Only sign SIGHASH_SINGLE if there's a corresponding output:
if (!fHashSingle || (i < mergedTx.vout.size()))
SignSignature(keystore, prevPubKey, mergedTx, i, nHashType);
// ... and merge in other signatures:
BOOST_FOREACH(const CTransaction& txv, txVariants)
{
txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, txv.vin[i].scriptSig);
}
if (!VerifyScript(txin.scriptSig, prevPubKey, mergedTx, i, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC, 0))
fComplete = false;
}
Object result;
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << mergedTx;
result.push_back(Pair("hex", HexStr(ssTx.begin(), ssTx.end())));
result.push_back(Pair("complete", fComplete));
return result;
}
Value sendrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"sendrawtransaction \"hexstring\" ( allowhighfees )\n"
"\nSubmits raw transaction (serialized, hex-encoded) to local node and network.\n"
"\nAlso see createrawtransaction and signrawtransaction calls.\n"
"\nArguments:\n"
"1. \"hexstring\" (string, required) The hex string of the raw transaction)\n"
"2. allowhighfees (boolean, optional, default=false) Allow high fees\n"
"\nResult:\n"
"\"hex\" (string) The transaction hash in hex\n"
"\nExamples:\n"
"\nCreate a transaction\n"
+ HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" \"{\\\"myaddress\\\":0.01}\"") +
"Sign the transaction, and get back the hex\n"
+ HelpExampleCli("signrawtransaction", "\"myhex\"") +
"\nSend the transaction (signed hex)\n"
+ HelpExampleCli("sendrawtransaction", "\"signedhex\"") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("sendrawtransaction", "\"signedhex\"")
);
// parse hex string from parameter
vector<unsigned char> txData(ParseHexV(params[0], "parameter"));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
CTransaction tx;
bool fOverrideFees = false;
if (params.size() > 1)
fOverrideFees = params[1].get_bool();
// deserialize binary data stream
try {
ssData >> tx;
}
catch (std::exception &e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
uint256 hashTx = tx.GetHash();
bool fHave = false;
CCoinsViewCache &view = *pcoinsTip;
CCoins existingCoins;
{
fHave = view.GetCoins(hashTx, existingCoins);
if (!fHave) {
// push to local node
CValidationState state;
if (!AcceptToMemoryPool(mempool, state, tx, false, NULL, !fOverrideFees))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX rejected"); // TODO: report validation state
}
}
if (fHave) {
if (existingCoins.nHeight < 1000000000)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "transaction already in block chain");
// Not in block, but already in the memory pool; will drop
// through to re-relay it.
} else {
SyncWithWallets(hashTx, tx, NULL);
}
RelayTransaction(tx, hashTx);
return hashTx.GetHex();
}
| lion-coin/lioncoin | src/rpcrawtransaction.cpp | C++ | mit | 32,779 |
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'spec_helper'
require 'rspec/rails'
require 'shoulda/matchers'
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = true
config.infer_spec_type_from_file_location!
config.filter_rails_from_backtrace!
end
| raadler/Scrivn | spec/rails_helper.rb | Ruby | mit | 652 |
import React from 'react';
import { View, ScrollView } from 'react-native';
import ConcensusButton from '../components/ConcensusButton';
import axios from 'axios';
const t = require('tcomb-form-native');
const Form = t.form.Form;
const NewPollScreen = ({ navigation }) => {
function onProposePress() {
navigation.navigate('QRCodeShower');
axios.post('http://4d23f078.ngrok.io/createPoll');
}
return (
<View style={{ padding: 20 }}>
<ScrollView>
<Form type={Poll} />
</ScrollView>
<ConcensusButton label="Propose Motion" onPress={onProposePress} />
</View>
);
};
NewPollScreen.navigationOptions = ({ navigation }) => ({
title: 'Propose a Motion',
});
export default NewPollScreen;
const Poll = t.struct({
subject: t.String,
proposal: t.String,
endsInMinutes: t.Number,
consensusPercentage: t.Number,
});
| concensus/react-native-ios-concensus | screens/NewPollScreen.js | JavaScript | mit | 929 |
package com.mikescamell.sharedelementtransitions.recycler_view.recycler_view_to_viewpager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.mikescamell.sharedelementtransitions.R;
public class RecyclerViewToViewPagerActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment_to_fragment);
getSupportFragmentManager()
.beginTransaction()
.add(R.id.content, RecyclerViewFragment.newInstance())
.commit();
}
}
| mikescamell/shared-element-transitions | app/src/main/java/com/mikescamell/sharedelementtransitions/recycler_view/recycler_view_to_viewpager/RecyclerViewToViewPagerActivity.java | Java | mit | 652 |
define(["ace/ace"], function(ace) {
return function(element) {
var editor = ace.edit(element);
editor.setTheme("ace/theme/eclipse");
editor.getSession().setMode("ace/mode/python");
editor.getSession().setUseSoftTabs(true);
editor.getSession().setTabSize(4);
editor.setShowPrintMargin(false);
return editor;
};
})
| nachovizzo/AUTONAVx | simulator/autonavx_demo/js/init/editor.js | JavaScript | mit | 330 |
/**
* React components for kanna projects.
* @module kanna-lib-components
*/
"use strict";
module.exports = {
/**
* @name KnAccordionArrow
*/
get KnAccordionArrow() { return require('./kn_accordion_arrow'); },
/**
* @name KnAccordionBody
*/
get KnAccordionBody() { return require('./kn_accordion_body'); },
/**
* @name KnAccordionHeader
*/
get KnAccordionHeader() { return require('./kn_accordion_header'); },
/**
* @name KnAccordion
*/
get KnAccordion() { return require('./kn_accordion'); },
/**
* @name KnAnalogClock
*/
get KnAnalogClock() { return require('./kn_analog_clock'); },
/**
* @name KnBody
*/
get KnBody() { return require('./kn_body'); },
/**
* @name KnButton
*/
get KnButton() { return require('./kn_button'); },
/**
* @name KnCheckbox
*/
get KnCheckbox() { return require('./kn_checkbox'); },
/**
* @name KnClock
*/
get KnClock() { return require('./kn_clock'); },
/**
* @name KnContainer
*/
get KnContainer() { return require('./kn_container'); },
/**
* @name KnDesktopShowcase
*/
get KnDesktopShowcase() { return require('./kn_desktop_showcase'); },
/**
* @name KnDigitalClock
*/
get KnDigitalClock() { return require('./kn_digital_clock'); },
/**
* @name KnFaIcon
*/
get KnFaIcon() { return require('./kn_fa_icon'); },
/**
* @name KnFooter
*/
get KnFooter() { return require('./kn_footer'); },
/**
* @name KnHead
*/
get KnHead() { return require('./kn_head'); },
/**
* @name KnHeaderLogo
*/
get KnHeaderLogo() { return require('./kn_header_logo'); },
/**
* @name KnHeaderTabItem
*/
get KnHeaderTabItem() { return require('./kn_header_tab_item'); },
/**
* @name KnHeaderTab
*/
get KnHeaderTab() { return require('./kn_header_tab'); },
/**
* @name KnHeader
*/
get KnHeader() { return require('./kn_header'); },
/**
* @name KnHtml
*/
get KnHtml() { return require('./kn_html'); },
/**
* @name KnIcon
*/
get KnIcon() { return require('./kn_icon'); },
/**
* @name KnImage
*/
get KnImage() { return require('./kn_image'); },
/**
* @name KnIonIcon
*/
get KnIonIcon() { return require('./kn_ion_icon'); },
/**
* @name KnLabel
*/
get KnLabel() { return require('./kn_label'); },
/**
* @name KnLinks
*/
get KnLinks() { return require('./kn_links'); },
/**
* @name KnListItemArrowIcon
*/
get KnListItemArrowIcon() { return require('./kn_list_item_arrow_icon'); },
/**
* @name KnListItemIcon
*/
get KnListItemIcon() { return require('./kn_list_item_icon'); },
/**
* @name KnListItemText
*/
get KnListItemText() { return require('./kn_list_item_text'); },
/**
* @name KnListItem
*/
get KnListItem() { return require('./kn_list_item'); },
/**
* @name KnList
*/
get KnList() { return require('./kn_list'); },
/**
* @name KnMain
*/
get KnMain() { return require('./kn_main'); },
/**
* @name KnMobileShowcase
*/
get KnMobileShowcase() { return require('./kn_mobile_showcase'); },
/**
* @name KnNote
*/
get KnNote() { return require('./kn_note'); },
/**
* @name KnPassword
*/
get KnPassword() { return require('./kn_password'); },
/**
* @name KnRadio
*/
get KnRadio() { return require('./kn_radio'); },
/**
* @name KnRange
*/
get KnRange() { return require('./kn_range'); },
/**
* @name KnShowcase
*/
get KnShowcase() { return require('./kn_showcase'); },
/**
* @name KnSlider
*/
get KnSlider() { return require('./kn_slider'); },
/**
* @name KnSlideshow
*/
get KnSlideshow() { return require('./kn_slideshow'); },
/**
* @name KnSpinner
*/
get KnSpinner() { return require('./kn_spinner'); },
/**
* @name KnTabItem
*/
get KnTabItem() { return require('./kn_tab_item'); },
/**
* @name KnTab
*/
get KnTab() { return require('./kn_tab'); },
/**
* @name KnText
*/
get KnText() { return require('./kn_text'); },
/**
* @name KnThemeStyle
*/
get KnThemeStyle() { return require('./kn_theme_style'); }
}; | kanna-lab/kanna-lib-components | lib/index.js | JavaScript | mit | 4,495 |
<?php
namespace App\Helpers\Date;
use Nette;
/**
* Date and time helper for better work with dates. Functions return special
* DateTimeHolder which contains both textual and typed DateTime.
*/
class DateHelper
{
use Nette\SmartObject;
/**
* Create datetime from the given text if valid, or otherwise return first
* day of current month.
* @param string $text
* @return \App\Helpers\Date\DateTimeHolder
*/
public function createFromDateOrFirstDayOfMonth($text): DateTimeHolder
{
$holder = new DateTimeHolder;
$date = date_create_from_format("j. n. Y", $text);
$holder->typed = $date ? $date : new \DateTime('first day of this month');
$holder->textual = $holder->typed->format("j. n. Y");
return $holder;
}
/**
* Create datetime from the given text if valid, or otherwise return last
* day of current month.
* @param string $text
* @return \App\Helpers\Date\DateTimeHolder
*/
public function createFromDateOrLastDayOfMonth($text): DateTimeHolder
{
$holder = new DateTimeHolder;
$date = date_create_from_format("j. n. Y", $text);
$holder->typed = $date ? $date : new \DateTime('last day of this month');
$holder->textual = $holder->typed->format("j. n. Y");
return $holder;
}
/**
* Create date from given string, if not possible create fallback date (0000-00-00 00:00:00)
* @param string $text
* @return \App\Helpers\Date\DateTimeHolder
*/
public function createDateOrDefault($text): DateTimeHolder
{
$holder = new DateTimeHolder;
try {
$date = new \DateTime($text);
} catch (\Exception $e) {
$date = new \DateTime("0000-00-00 00:00:00");
}
$holder->typed = $date;
$holder->textual = $holder->typed->format("j. n. Y");
return $holder;
}
}
| CatUnicornKiller/web-app | app/helpers/date/DateHelper.php | PHP | mit | 1,928 |
#include <iostream>
#include <fstream>
#include <seqan/basic.h>
#include <seqan/index.h>
#include <seqan/seq_io.h>
#include <seqan/sequence.h>
#include <seqan/file.h>
#include <seqan/score.h>
#include <seqan/seeds.h>
#include <seqan/align.h>
using namespace seqan;
seqan::String<Seed<Simple> > get_global_seed_chain(seqan::DnaString seq1, seqan::DnaString seq2, seqan::String<Seed<Simple> > roughGlobalChain, unsigned q){
typedef seqan::Seed<Simple> SSeed;
typedef seqan::SeedSet<Simple> SSeedSet;
SSeed seed;
SSeedSet seedSet;
seqan::String<SSeed> seedChain;
seqan::String<SSeed> improvedGlobalSeedChain;
seqan::DnaString window1 = seqan::infix(seq1, seqan::endPositionH(seedChain[0]), seqan::beginPositionH(seedChain[1]));
seqan::DnaString window2 = seqan::infix(seq2, seqan::endPositionV(seedChain[0]), seqan::beginPositionV(seedChain[1]));
std::cout << "window1: " << window1 << std::endl;
std::cout << "window2: " << window2 << std::endl;
typedef Index< DnaString, IndexQGram<SimpleShape > > qGramIndex;
qGramIndex index(window1);
resize(indexShape(index), q);
Finder<qGramIndex> myFinder(index);
std::cout << length(window2) << std::endl;
for (unsigned i = 0; i < length(window2) - (q - 1); ++i){
DnaString qGram = infix(window2, i, i + q);
std::cout << qGram << std::endl;
while (find(myFinder, qGram)){
std::cout << position(myFinder) << std::endl;
}
clear(myFinder);
}
seqan::chainSeedsGlobally(improvedGlobalSeedChain, seedSet, seqan::SparseChaining());
return improvedGlobalSeedChain;
}
bool readFASTA(char const * path, CharString &id, Dna5String &seq){
std::fstream in(path, std::ios::binary | std::ios::in);
RecordReader<std::fstream, SinglePass<> > reader(in);
if (readRecord(id, seq, reader, Fasta()) == 0){
return true;
}
else{
return false;
}
}
std::string get_file_contents(const char* filepath){
std::ifstream in(filepath, std::ios::in | std::ios::binary);
if (in){
std::string contents;
in.seekg(0, std::ios::end);
int fileLength = in.tellg();
contents.resize(fileLength);
in.seekg(0, std::ios::beg);
in.read(&contents[0], contents.size());
in.close();
return(contents);
}
throw(errno);
}
bool writeSeedPositions(std::vector< std::pair<unsigned, unsigned> > &array1, std::vector< std::pair<unsigned, unsigned> > &array2, const char* filepath){
std::ifstream FileTest(filepath);
if(!FileTest){
return false;
}
FileTest.close();
std::string s;
s = get_file_contents(filepath);
std::string pattern1 = ("Database positions: ");
std::string pattern2 = ("Query positions: ");
std::pair<unsigned, unsigned> startEnd;
std::vector<std::string> patternContainer;
patternContainer.push_back(pattern1);
patternContainer.push_back(pattern2);
for (unsigned j = 0; j < patternContainer.size(); ++j){
unsigned found = s.find(patternContainer[j]);
while (found!=std::string::npos){
std::string temp1 = "";
std::string temp2 = "";
int i = 0;
while (s[found + patternContainer[j].length() + i] != '.'){
temp1 += s[found + patternContainer[j].length() + i];
++i;
}
i += 2;
while(s[found + patternContainer[j].length() + i] != '\n'){
temp2 += s[found + patternContainer[j].length() + i];
++i;
}
std::stringstream as(temp1);
std::stringstream bs(temp2);
int a;
int b;
as >> a;
bs >> b;
startEnd = std::make_pair(a, b);
if (j == 0){
array1.push_back(startEnd);
}
else{
array2.push_back(startEnd);
}
++found;
found = s.find(patternContainer[j], found);
}
}
return true;
}
int main(int argc, char const ** argv){
CharString idOne;
Dna5String seqOne;
CharString idTwo;
Dna5String seqTwo;
std::vector< std::pair<unsigned, unsigned> > seedsPosSeq1;
std::vector< std::pair<unsigned, unsigned> > seedsPosSeq2;
if (!readFASTA(argv[1], idOne, seqOne)){
std::cerr << "error: unable to read first sequence";
return 1;
}
if (!readFASTA(argv[2], idTwo, seqTwo)){
std::cerr << "error: unable to read second sequence";
return 1;
}
if (!writeSeedPositions(seedsPosSeq1, seedsPosSeq2, argv[3])){
std::cerr << "error: STELLAR output file not found";
return 1;
}
typedef Seed<Simple> SSeed;
typedef SeedSet<Simple> SSeedSet;
SSeedSet seedSet;
/*
for (unsigned i = 0; i < seedsPosSeq1.size(); ++i){
std::cout << "Seq1 " << seedsPosSeq1[i].first << '\t' << seedsPosSeq1[i].second << std::endl;
std::cout << "Seq2 " << seedsPosSeq2[i].first << '\t' << seedsPosSeq2[i].second << std::endl;
}
*/
//creation of seeds and adding them to a SeedSet
for (unsigned i = 0; i < seedsPosSeq1.size(); ++i){
SSeed seed(seedsPosSeq1[i].first, seedsPosSeq2[i].first, seedsPosSeq1[i].second, seedsPosSeq2[i].second);
addSeed(seedSet, seed, Single());
}
//std::cout << "Trennlinie" << std::endl;
clear(seedSet);
typedef Iterator<SSeedSet >::Type SetIterator;
for (SetIterator it = begin(seedSet, Standard()); it != end(seedSet, Standard()); ++it){
std::cout << *it;
std::cout << std::endl;
}
/*
typedef Iterator<String<SSeed> > StringIterator;
seqan::String<SSeed> seedChain;
seqan::String<SSeed> seedChain2;
std::vector<unsigned> depthCounter;
chainSeedsGlobally(seedChain, seedSet, seqan::SparseChaining());
depthCounter.push_back(length(seedChain));
unsigned initQGram = 20;
/*while (!depthCounter.empty()){
unsigned q = initQGram; // - (2 * (depthCounter.size() - 1));
seqan::String<SSeed> globalSeedChain;
while(q >= 4){
SSeed seed;
SSeedSet seedSet;
seqan::String<SSeed> seedChain;
seqan::DnaString window1 = seqan::infix(seqOne, seqan::endPositionH(seedChain[0]), seqan::beginPositionH(seedChain[1]));
seqan::DnaString window2 = seqan::infix(seqTwo, seqan::endPositionV(seedChain[0]), seqan::beginPositionV(seedChain[1]));
std::cout << "window1: " << window1 << std::endl;
std::cout << "window2: " << window2 << std::endl;
typedef Index< DnaString, IndexQGram<SimpleShape > > qGramIndex;
qGramIndex index(window1);
resize(indexShape(index), q);
Finder<qGramIndex> myFinder(index);
std::cout << length(window2) << std::endl;
for (unsigned i = 0; i < length(window2) - (q - 1); ++i){
unsigned startPosSeedSeq1;
unsigned startPosSeedSeq2;
unsigned endPosSeedSeq1;
unsigned endPosSeedSeq2;
DnaString qGram = infix(window2, i, i + q);
std::cout << qGram << std::endl;
if (find(myFinder, qGram)){
std::cout << position(myFinder) << std::endl;
addSeed()
}
clear(myFinder);
}
/*
std::cout << front(seedChain) << std::endl;
seqan::append(seedChain2, seedChain[0]);
std::cout << "bla0" << std::endl;
seqan::append(seedChain2, seedChain[1]);
std::cout << length(seedChain2) << std::endl;
seqan::insert(seedChain2, 1, seedChain);
std::cout << "seedChain[3]: " << seedChain[3] << std::endl;
std::cout << "seedChain2[1]: " << seedChain2[1] << std::endl;
std::cout << "length(seedChain2): " << length(seedChain2) << std::endl;
erase(seedChain2, 0);
std::cout << length(seedChain2) << std::endl;
std::cout << "bla2" << std::endl;
}
}
std::cout << "length(seedChain): " << length(seedChain) << std::endl;
std::cout << "seedChain[0]: " << seedChain[0] << std::endl;
std::cout << "seedChain[1]: " << seedChain[1] << std::endl;
std::cout << "seedChain[2]: " << seedChain[2] << std::endl;
/*std::cout << "test2" << std::endl;
Align<Dna5String, ArrayGaps> alignment;
resize(seqan::rows(alignment), 2);
Score<int, Simple> scoringFunction(2, -1, -2);
seqan::assignSource(seqan::row(alignment, 0), seqOne);
seqan::assignSource(seqan::row(alignment, 1), seqTwo);
int result = bandedChainAlignment(alignment, seedChain, scoringFunction, 2);
std::cout << "Score: " << result << std::endl;
std::cout << alignment << std::endl;
*/
/*std::cout << idOne << std::endl << seqOne << std::endl;
std::cout << idTwo << std::endl << seqTwo << std::endl;
for (unsigned i = 0; i < seedsPosSeq1.size(); ++i){
cout << "Seq1 " << seedsPosSeq1[i].first << '\t' << seedsPosSeq1[i].second << endl;
cout << "Seq2 " << seedsPosSeq2[i].first << '\t' << seedsPosSeq2[i].second << endl;
}
*/
return 0;
}
| bkahlert/seqan-research | raw/pmsb13/pmsb13-data-20130530/sources/130wu1dgzoqmxyu2/2013-05-01T11-34-38.877+0200/sandbox/my_sandbox/apps/lagan_neu/lagan_neu.cpp | C++ | mit | 8,171 |
#include "stdafx.h"
#include "GPUResource.h"
#include <algorithm>
#include "D3D12DeviceContext.h"
CreateChecker(GPUResource);
GPUResource::GPUResource()
{}
GPUResource::GPUResource(ID3D12Resource* Target, D3D12_RESOURCE_STATES InitalState) :GPUResource(Target, InitalState, (D3D12DeviceContext*)RHI::GetDefaultDevice())
{}
GPUResource::GPUResource(ID3D12Resource * Target, D3D12_RESOURCE_STATES InitalState, DeviceContext * device)
{
AddCheckerRef(GPUResource, this);
resource = Target;
NAME_D3D12_OBJECT(Target);
CurrentResourceState = InitalState;
Device = (D3D12DeviceContext*)device;
}
GPUResource::~GPUResource()
{
if (!IsReleased)
{
Release();
}
}
void GPUResource::SetName(LPCWSTR name)
{
resource->SetName(name);
}
void GPUResource::CreateHeap()
{
Block.Heaps.push_back(nullptr);
ID3D12Heap* pHeap = Block.Heaps[0];
int RemainingSize = 1 * TILE_SIZE;
D3D12_HEAP_DESC heapDesc = {};
heapDesc.SizeInBytes = std::min(RemainingSize, MAX_HEAP_SIZE);
heapDesc.Alignment = 0;
heapDesc.Properties.Type = D3D12_HEAP_TYPE_DEFAULT;
heapDesc.Properties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
heapDesc.Properties.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
//
// Tier 1 heaps have restrictions on the type of information that can be stored in
// a heap. To accommodate this, we will retsrict the content to only shader resources.
// The heap cannot store textures that are used as render targets, depth-stencil
// output, or buffers. But this is okay, since we do not use these heaps for those
// purposes.
//
heapDesc.Flags = D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES | D3D12_HEAP_FLAG_DENY_BUFFERS;
//ThrowIfFailed( D3D12RHI::GetDevice()->CreateHeap(&heapDesc, IID_PPV_ARGS(&pHeap)));
}
void GPUResource::Evict()
{
ensure(currentState != eResourceState::Evicted);
ID3D12Pageable* Pageableresource = resource;
ThrowIfFailed(Device->GetDevice()->Evict(1, &Pageableresource));
currentState = eResourceState::Evicted;
}
void GPUResource::MakeResident()
{
ensure(currentState != eResourceState::Resident);
ID3D12Pageable* Pageableresource = resource;
ThrowIfFailed(Device->GetDevice()->MakeResident(1, &Pageableresource));
currentState = eResourceState::Resident;
}
bool GPUResource::IsResident()
{
return (currentState == eResourceState::Resident);
}
GPUResource::eResourceState GPUResource::GetState()
{
return currentState;
}
void GPUResource::SetResourceState(ID3D12GraphicsCommandList* List, D3D12_RESOURCE_STATES newstate)
{
if (newstate != CurrentResourceState)
{
List->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(resource, CurrentResourceState, newstate));
CurrentResourceState = newstate;
TargetState = newstate;
}
}
//todo More Detailed Error checking!
void GPUResource::StartResourceTransition(ID3D12GraphicsCommandList * List, D3D12_RESOURCE_STATES newstate)
{
if (newstate != CurrentResourceState)
{
D3D12_RESOURCE_BARRIER BarrierDesc = {};
BarrierDesc.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
BarrierDesc.Flags = D3D12_RESOURCE_BARRIER_FLAG_BEGIN_ONLY;
BarrierDesc.Transition.StateBefore = CurrentResourceState;
BarrierDesc.Transition.StateAfter = newstate;
BarrierDesc.Transition.pResource = resource;
List->ResourceBarrier(1, &BarrierDesc);
TargetState = newstate;
}
}
void GPUResource::EndResourceTransition(ID3D12GraphicsCommandList * List, D3D12_RESOURCE_STATES newstate)
{
if (newstate != CurrentResourceState)
{
D3D12_RESOURCE_BARRIER BarrierDesc = {};
BarrierDesc.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
BarrierDesc.Flags = D3D12_RESOURCE_BARRIER_FLAG_END_ONLY;
BarrierDesc.Transition.StateBefore = CurrentResourceState;
BarrierDesc.Transition.StateAfter = newstate;
BarrierDesc.Transition.pResource = resource;
List->ResourceBarrier(1, &BarrierDesc);
CurrentResourceState = newstate;
}
}
bool GPUResource::IsTransitioning()
{
return (CurrentResourceState != TargetState);
}
D3D12_RESOURCE_STATES GPUResource::GetCurrentState()
{
return CurrentResourceState;
}
ID3D12Resource * GPUResource::GetResource()
{
return resource;
}
void GPUResource::Release()
{
IRHIResourse::Release();
SafeRelease(resource);
RemoveCheckerRef(GPUResource, this);
}
| Andrewcjp/GraphicsEngine | GraphicsEngine/Source/D3D12RHI/RHI/RenderAPIs/D3D12/GPUResource.cpp | C++ | mit | 4,208 |
package com.braintreepayments.api;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
import androidx.annotation.Nullable;
import com.braintreepayments.api.GraphQLConstants.Keys;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Use to construct a card tokenization request.
*/
public class Card extends BaseCard implements Parcelable {
private static final String GRAPHQL_CLIENT_SDK_METADATA_KEY = "clientSdkMetadata";
private static final String MERCHANT_ACCOUNT_ID_KEY = "merchantAccountId";
private static final String AUTHENTICATION_INSIGHT_REQUESTED_KEY = "authenticationInsight";
private static final String AUTHENTICATION_INSIGHT_INPUT_KEY = "authenticationInsightInput";
private String merchantAccountId;
private boolean authenticationInsightRequested;
private boolean shouldValidate;
JSONObject buildJSONForGraphQL() throws BraintreeException, JSONException {
JSONObject base = new JSONObject();
JSONObject input = new JSONObject();
JSONObject variables = new JSONObject();
base.put(GRAPHQL_CLIENT_SDK_METADATA_KEY, buildMetadataJSON());
JSONObject optionsJson = new JSONObject();
optionsJson.put(VALIDATE_KEY, shouldValidate);
input.put(OPTIONS_KEY, optionsJson);
variables.put(Keys.INPUT, input);
if (TextUtils.isEmpty(merchantAccountId) && authenticationInsightRequested) {
throw new BraintreeException("A merchant account ID is required when authenticationInsightRequested is true.");
}
if (authenticationInsightRequested) {
variables.put(AUTHENTICATION_INSIGHT_INPUT_KEY, new JSONObject().put(MERCHANT_ACCOUNT_ID_KEY, merchantAccountId));
}
base.put(Keys.QUERY, getCardTokenizationGraphQLMutation());
base.put(OPERATION_NAME_KEY, "TokenizeCreditCard");
JSONObject creditCard = new JSONObject()
.put(NUMBER_KEY, getNumber())
.put(EXPIRATION_MONTH_KEY, getExpirationMonth())
.put(EXPIRATION_YEAR_KEY, getExpirationYear())
.put(CVV_KEY, getCvv())
.put(CARDHOLDER_NAME_KEY, getCardholderName());
JSONObject billingAddress = new JSONObject()
.put(FIRST_NAME_KEY, getFirstName())
.put(LAST_NAME_KEY, getLastName())
.put(COMPANY_KEY, getCompany())
.put(COUNTRY_CODE_KEY, getCountryCode())
.put(LOCALITY_KEY, getLocality())
.put(POSTAL_CODE_KEY, getPostalCode())
.put(REGION_KEY, getRegion())
.put(STREET_ADDRESS_KEY, getStreetAddress())
.put(EXTENDED_ADDRESS_KEY, getExtendedAddress());
if (billingAddress.length() > 0) {
creditCard.put(BILLING_ADDRESS_KEY, billingAddress);
}
input.put(CREDIT_CARD_KEY, creditCard);
base.put(Keys.VARIABLES, variables);
return base;
}
public Card() {
}
/**
* @param id The merchant account id used to generate the authentication insight.
*/
public void setMerchantAccountId(@Nullable String id) {
merchantAccountId = TextUtils.isEmpty(id) ? null : id;
}
/**
* @param shouldValidate Flag to denote if the associated {@link Card} will be validated. Defaults to false.
* <p>
* Use this flag with caution. Enabling validation may result in adding a card to the Braintree vault.
* The circumstances that determine if a Card will be vaulted are not documented.
*/
public void setShouldValidate(boolean shouldValidate) {
this.shouldValidate = shouldValidate;
}
/**
* @param requested If authentication insight will be requested.
*/
public void setAuthenticationInsightRequested(boolean requested) {
authenticationInsightRequested = requested;
}
/**
* @return The merchant account id used to generate the authentication insight.
*/
@Nullable
public String getMerchantAccountId() {
return merchantAccountId;
}
/**
* @return If authentication insight will be requested.
*/
public boolean isAuthenticationInsightRequested() {
return authenticationInsightRequested;
}
/**
* @return If the associated card will be validated.
*/
public boolean getShouldValidate() {
return shouldValidate;
}
@Override
JSONObject buildJSON() throws JSONException {
JSONObject json = super.buildJSON();
JSONObject paymentMethodNonceJson = json.getJSONObject(CREDIT_CARD_KEY);
JSONObject optionsJson = new JSONObject();
optionsJson.put(VALIDATE_KEY, shouldValidate);
paymentMethodNonceJson.put(OPTIONS_KEY, optionsJson);
if (authenticationInsightRequested) {
json.put(MERCHANT_ACCOUNT_ID_KEY, merchantAccountId);
json.put(AUTHENTICATION_INSIGHT_REQUESTED_KEY, authenticationInsightRequested);
}
return json;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeString(merchantAccountId);
dest.writeByte(shouldValidate ? (byte) 1 : 0);
dest.writeByte(authenticationInsightRequested ? (byte) 1 : 0);
}
protected Card(Parcel in) {
super(in);
merchantAccountId = in.readString();
shouldValidate = in.readByte() > 0;
authenticationInsightRequested = in.readByte() > 0;
}
public static final Creator<Card> CREATOR = new Creator<Card>() {
@Override
public Card createFromParcel(Parcel in) {
return new Card(in);
}
@Override
public Card[] newArray(int size) {
return new Card[size];
}
};
private String getCardTokenizationGraphQLMutation() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("mutation TokenizeCreditCard($input: TokenizeCreditCardInput!");
if (authenticationInsightRequested) {
stringBuilder.append(", $authenticationInsightInput: AuthenticationInsightInput!");
}
stringBuilder.append(") {" +
" tokenizeCreditCard(input: $input) {" +
" token" +
" creditCard {" +
" bin" +
" brand" +
" expirationMonth" +
" expirationYear" +
" cardholderName" +
" last4" +
" binData {" +
" prepaid" +
" healthcare" +
" debit" +
" durbinRegulated" +
" commercial" +
" payroll" +
" issuingBank" +
" countryOfIssuance" +
" productId" +
" }" +
" }");
if (authenticationInsightRequested) {
stringBuilder.append("" +
" authenticationInsight(input: $authenticationInsightInput) {" +
" customerAuthenticationRegulationEnvironment" +
" }");
}
stringBuilder.append("" +
" }" +
"}");
return stringBuilder.toString();
}
} | braintree/braintree_android | Card/src/main/java/com/braintreepayments/api/Card.java | Java | mit | 7,536 |
package cn.edu.siso.rlxapf;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class DeviceActivity extends AppCompatActivity {
private Button devicePrefOk = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_device);
devicePrefOk = (Button) findViewById(R.id.device_pref_ok);
devicePrefOk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(DeviceActivity.this, MainActivity.class);
startActivity(intent);
DeviceActivity.this.finish();
}
});
getSupportFragmentManager().beginTransaction().replace(
R.id.device_pref, new DevicePrefFragment()).commit();
}
}
| taowenyin/RLXAPF | app/src/main/java/cn/edu/siso/rlxapf/DeviceActivity.java | Java | mit | 995 |
require 'spec_helper'
RSpec.configure do |config|
config.before(:suite) do
VCR.configuration.configure_rspec_metadata!
end
end
describe VCR::RSpec::Metadata, :skip_vcr_reset do
before(:all) { VCR.reset! }
after(:each) { VCR.reset! }
context 'an example group', :vcr do
context 'with a nested example group' do
it 'uses a cassette for any examples' do
VCR.current_cassette.name.split('/').should eq([
'VCR::RSpec::Metadata',
'an example group',
'with a nested example group',
'uses a cassette for any examples'
])
end
end
end
context 'with the cassette name overridden at the example group level', :vcr => { :cassette_name => 'foo' } do
it 'overrides the cassette name for an example' do
VCR.current_cassette.name.should eq('foo')
end
it 'overrides the cassette name for another example' do
VCR.current_cassette.name.should eq('foo')
end
end
it 'allows the cassette name to be overriden', :vcr => { :cassette_name => 'foo' } do
VCR.current_cassette.name.should eq('foo')
end
it 'allows the cassette options to be set', :vcr => { :match_requests_on => [:method] } do
VCR.current_cassette.match_requests_on.should eq([:method])
end
end
describe VCR::RSpec::Macros do
extend described_class
describe '#use_vcr_cassette' do
def self.perform_test(context_name, expected_cassette_name, *args, &block)
context context_name do
after(:each) do
if example.metadata[:test_ejection]
VCR.current_cassette.should be_nil
end
end
use_vcr_cassette(*args)
it 'ejects the cassette in an after hook', :test_ejection do
VCR.current_cassette.should be_a(VCR::Cassette)
end
it "creates a cassette named '#{expected_cassette_name}" do
VCR.current_cassette.name.should eq(expected_cassette_name)
end
module_eval(&block) if block
end
end
perform_test 'when called with an explicit name', 'explicit_name', 'explicit_name'
perform_test 'when called with an explicit name and some options', 'explicit_name', 'explicit_name', :match_requests_on => [:method, :host] do
it 'uses the provided cassette options' do
VCR.current_cassette.match_requests_on.should eq([:method, :host])
end
end
perform_test 'when called with nothing', 'VCR::RSpec::Macros/#use_vcr_cassette/when called with nothing'
perform_test 'when called with some options', 'VCR::RSpec::Macros/#use_vcr_cassette/when called with some options', :match_requests_on => [:method, :host] do
it 'uses the provided cassette options' do
VCR.current_cassette.match_requests_on.should eq([:method, :host])
end
end
end
end
| spookandpuff/spooky-core | .bundle/gems/vcr-2.0.0/spec/vcr/test_frameworks/rspec_spec.rb | Ruby | mit | 2,807 |
<?php
declare(strict_types=1);
namespace OAuth2Framework\Tests\Component\ClientRule;
use InvalidArgumentException;
use OAuth2Framework\Component\ClientRule\ApplicationTypeParametersRule;
use OAuth2Framework\Component\ClientRule\RuleHandler;
use OAuth2Framework\Component\Core\Client\ClientId;
use OAuth2Framework\Component\Core\DataBag\DataBag;
use OAuth2Framework\Tests\Component\OAuth2TestCase;
/**
* @internal
*/
final class ApplicationTypeParameterRuleTest extends OAuth2TestCase
{
/**
* @test
*/
public function applicationTypeParameterRuleSetAsDefault(): void
{
$clientId = ClientId::create('CLIENT_ID');
$commandParameters = DataBag::create([]);
$rule = new ApplicationTypeParametersRule();
$validatedParameters = $rule->handle($clientId, $commandParameters, DataBag::create([]), $this->getCallable());
static::assertTrue($validatedParameters->has('application_type'));
static::assertSame('web', $validatedParameters->get('application_type'));
}
/**
* @test
*/
public function applicationTypeParameterRuleDefineInParameters(): void
{
$clientId = ClientId::create('CLIENT_ID');
$commandParameters = DataBag::create([
'application_type' => 'native',
]);
$rule = new ApplicationTypeParametersRule();
$validatedParameters = $rule->handle($clientId, $commandParameters, DataBag::create([]), $this->getCallable());
static::assertTrue($validatedParameters->has('application_type'));
static::assertSame('native', $validatedParameters->get('application_type'));
}
/**
* @test
*/
public function applicationTypeParameterRule(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('The parameter "application_type" must be either "native" or "web".');
$clientId = ClientId::create('CLIENT_ID');
$commandParameters = DataBag::create([
'application_type' => 'foo',
]);
$rule = new ApplicationTypeParametersRule();
$rule->handle($clientId, $commandParameters, DataBag::create([]), $this->getCallable());
}
private function getCallable(): RuleHandler
{
return new RuleHandler(function (
ClientId $clientId,
DataBag $commandParameters,
DataBag $validatedParameters
): DataBag {
return $validatedParameters;
});
}
}
| OAuth2-Framework/oauth2-framework | tests/Component/ClientRule/ApplicationTypeParameterRuleTest.php | PHP | mit | 2,505 |
function countBs(string) {
return countChar(string, "B");
}
function countChar(string, ch) {
var counted = 0;
for (var i = 0; i < string.length; i++) {
if (string.charAt(i) == ch)
counted += 1;
}
return counted;
}
console.log(countBs("BBC"));
// -> 2
console.log(countChar("kakkerlak", "k"));
// -> 4
| jdhunterae/eloquent_js | ch03/su03-bean_counting.js | JavaScript | mit | 343 |
// dvt
/* 1. Да се напише if-конструкция,
* която изчислява стойността на две целочислени променливи и
* разменя техните стойности,
* ако стойността на първата променлива е по-голяма от втората.
*/
package myJava;
import java.util.Scanner;
public class dvt {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int a, b, temp;
System.out.print("a = "); a = read.nextInt();
System.out.print("b = "); b = read.nextInt();
if (a > b){
temp = a;
a = b;
b = temp;
System.out.println(
"a > b! The values have been switched!\n"
+ "a = " + a + " b = " + b);
}
}
}
| dvt32/cpp-journey | Java/Unsorted/21.05.2015.14.36.java | Java | mit | 793 |
/*
* Copyright (c) André Bargull
* Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms.
*
* <https://github.com/anba/es6draft>
*/
/*---
id: sec-function-calls-runtime-semantics-evaluation
info: Check TypeError is thrown from correct realm with tco-call to class constructor from class [[Construct]] invocation.
description: >
12.3.4.3 Runtime Semantics: EvaluateDirectCall( func, thisValue, arguments, tailPosition )
...
4. If tailPosition is true, perform PrepareForTailCall().
5. Let result be Call(func, thisValue, argList).
6. Assert: If tailPosition is true, the above call will not return here, but instead evaluation will continue as if the following return has already occurred.
7. Assert: If result is not an abrupt completion, then Type(result) is an ECMAScript language type.
8. Return result.
9.2.1 [[Call]] ( thisArgument, argumentsList)
...
2. If F.[[FunctionKind]] is "classConstructor", throw a TypeError exception.
3. Let callerContext be the running execution context.
4. Let calleeContext be PrepareForOrdinaryCall(F, undefined).
5. Assert: calleeContext is now the running execution context.
...
features: [tail-call-optimization, class]
---*/
// - The class constructor call is in a valid tail-call position, which means PrepareForTailCall is performed.
// - The function call returns from `otherRealm` and proceeds the tail-call in this realm.
// - Calling the class constructor throws a TypeError from the current realm, that means this realm and not `otherRealm`.
var code = "(class { constructor() { return (class {})(); } });";
var otherRealm = $262.createRealm();
var tco = otherRealm.evalScript(code);
assert.throws(TypeError, function() {
new tco();
});
| anba/es6draft | src/test/scripts/suite262/language/expressions/call/tco-cross-realm-class-construct.js | JavaScript | mit | 1,776 |
package com.rootulp.rootulpjsona;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import java.io.InputStream;
public class picPage extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pic_page);
Intent local = getIntent();
Bundle localBundle = local.getExtras();
artist selected = (artist) localBundle.getSerializable("selected");
String imageURL = selected.getImageURL();
new DownloadImageTask((ImageView) findViewById(R.id.painting)).execute(imageURL);
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_pic_page, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| rootulp/school | mobile_apps/assignment6_rootulp/RootulpJsonA/app/src/main/java/com/rootulp/rootulpjsona/picPage.java | Java | mit | 2,172 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace GameBuilder.BuilderControl
{
/// <summary>
/// Interaction logic for ResourcesSelector.xaml
/// </summary>
public partial class ResourcesBuilder : UserControl
{
public string Header
{
get
{
return ResourcesBox.Header.ToString();
}
set
{
ResourcesBox.Header = value;
}
}
public ResourcesBuilder()
{
InitializeComponent();
}
}
}
| bruno-cadorette/IFT232Projet | GameBuilder/BuilderControl/ResourcesControl.xaml.cs | C# | mit | 911 |
<?php
declare(strict_types=1);
namespace JDWil\Xsd\Event;
/**
* Class FoundAnyAttributeEvent
* @package JDWil\Xsd\Event
*/
class FoundAnyAttributeEvent extends AbstractXsdNodeEvent
{
} | jdwil/xsd-tool | src/Event/FoundAnyAttributeEvent.php | PHP | mit | 190 |
# Copyright (c) 2008-2013 Michael Dvorkin and contributors.
#
# Fat Free CRM is freely distributable under the terms of MIT license.
# See MIT-LICENSE file or http://www.opensource.org/licenses/mit-license.php
#------------------------------------------------------------------------------
# == Schema Information
#
# Table name: avatars
#
# id :integer not null, primary key
# user_id :integer
# entity_id :integer
# entity_type :string(255)
# image_file_size :integer
# image_file_name :string(255)
# image_content_type :string(255)
# created_at :datetime
# updated_at :datetime
#
class FatFreeCRM::Avatar < ActiveRecord::Base
STYLES = { large: "75x75#", medium: "50x50#", small: "25x25#", thumb: "16x16#" }.freeze
belongs_to :user
belongs_to :entity, polymorphic: true, class_name: 'FatFreeCRM::Entity'
# We want to store avatars in separate directories based on entity type
# (i.e. /avatar/User/, /avatars/Lead/, etc.), so we are adding :entity_type
# interpolation to the Paperclip::Interpolations module. Also, Paperclip
# doesn't seem to care preserving styles hash so we must use STYLES.dup.
#----------------------------------------------------------------------------
Paperclip::Interpolations.module_eval do
def entity_type(attachment, _style_name = nil)
attachment.instance.entity_type
end
end
has_attached_file :image, styles: STYLES.dup, url: "/avatars/:entity_type/:id/:style_:filename", default_url: "/assets/avatar.jpg"
validates_attachment :image, presence: true,
content_type: { content_type: %w(image/jpeg image/jpg image/png image/gif) }
# Convert STYLE symbols to 'w x h' format for Gravatar and Rails
# e.g. Avatar.size_from_style(:size => :large) -> '75x75'
# Allow options to contain :width and :height override keys
#----------------------------------------------------------------------------
def self.size_from_style!(options)
if options[:width] && options[:height]
options[:size] = [:width, :height].map { |d| options[d] }.join("x")
elsif FatFreeCRM::Avatar::STYLES.keys.include?(options[:size])
options[:size] = FatFreeCRM::Avatar::STYLES[options[:size]].sub(/\#\z/, '')
end
options
end
ActiveSupport.run_load_hooks(:fat_free_crm_avatar, self)
end
| fkoessler/fat_free_crm | app/models/polymorphic/fat_free_crm/avatar.rb | Ruby | mit | 2,377 |
// Copyright (c) 2015 Elements of Programming Interviews. All rights reserved.
package com.epi;
import java.util.Random;
public class RabinKarp {
// @include
// Returns the index of the first character of the substring if found, -1
// otherwise.
public static int rabinKarp(String t, String s) {
if (s.length() > t.length()) {
return -1; // s is not a substring of t.
}
final int BASE = 26;
int tHash = 0, sHash = 0; // Hash codes for the substring of t and s.
int powerS = 1; // BASE^|s|.
for (int i = 0; i < s.length(); i++) {
powerS = i > 0 ? powerS * BASE : 1;
tHash = tHash * BASE + t.charAt(i);
sHash = sHash * BASE + s.charAt(i);
}
for (int i = s.length(); i < t.length(); i++) {
// Checks the two substrings are actually equal or not, to protect
// against hash collision.
if (tHash == sHash && t.substring(i - s.length(), i).equals(s)) {
return i - s.length(); // Found a match.
}
// Uses rolling hash to compute the new hash code.
tHash -= t.charAt(i - s.length()) * powerS;
tHash = tHash * BASE + t.charAt(i);
}
// Tries to match s and t.substring(t.length() - s.length()).
if (tHash == sHash && t.substring(t.length() - s.length()).equals(s)) {
return t.length() - s.length();
}
return -1; // s is not a substring of t.
}
// @exclude
private static int checkAnswer(String t, String s) {
for (int i = 0; i + s.length() - 1 < t.length(); ++i) {
boolean find = true;
for (int j = 0; j < s.length(); ++j) {
if (t.charAt(i + j) != s.charAt(j)) {
find = false;
break;
}
}
if (find) {
return i;
}
}
return -1; // No matching.
}
private static String randString(int len) {
Random r = new Random();
StringBuilder ret = new StringBuilder(len);
while (len-- > 0) {
ret.append((char)(r.nextInt(26) + 'a'));
}
return ret.toString();
}
private static void smallTest() {
assert(rabinKarp("GACGCCA", "CGC") == 2);
assert(rabinKarp("GATACCCATCGAGTCGGATCGAGT", "GAG") == 10);
assert(rabinKarp("FOOBARWIDGET", "WIDGETS") == -1);
assert(rabinKarp("A", "A") == 0);
assert(rabinKarp("A", "B") == -1);
assert(rabinKarp("A", "") == 0);
assert(rabinKarp("ADSADA", "") == 0);
assert(rabinKarp("", "A") == -1);
assert(rabinKarp("", "AAA") == -1);
assert(rabinKarp("A", "AAA") == -1);
assert(rabinKarp("AA", "AAA") == -1);
assert(rabinKarp("AAA", "AAA") == 0);
assert(rabinKarp("BAAAA", "AAA") == 1);
assert(rabinKarp("BAAABAAAA", "AAA") == 1);
assert(rabinKarp("BAABBAABAAABS", "AAA") == 8);
assert(rabinKarp("BAABBAABAAABS", "AAAA") == -1);
assert(rabinKarp("FOOBAR", "BAR") > 0);
}
public static void main(String args[]) {
smallTest();
if (args.length == 2) {
String t = args[0];
String s = args[1];
System.out.println("t = " + t);
System.out.println("s = " + s);
assert(checkAnswer(t, s) == rabinKarp(t, s));
} else {
Random r = new Random();
for (int times = 0; times < 10000; ++times) {
String t = randString(r.nextInt(1000) + 1);
String s = randString(r.nextInt(20) + 1);
System.out.println("t = " + t);
System.out.println("s = " + s);
assert(checkAnswer(t, s) == rabinKarp(t, s));
}
}
}
}
| adnanaziz/epicode | java/src/main/java/com/epi/RabinKarp.java | Java | mit | 3,435 |
using System;
using System.Collections.Generic;
using Sekhmet.Serialization.Utility;
namespace Sekhmet.Serialization
{
public class CachingObjectContextFactory : IObjectContextFactory
{
private readonly IInstantiator _instantiator;
private readonly ReadWriteLock _lock = new ReadWriteLock();
private readonly IDictionary<Type, ObjectContextInfo> _mapActualTypeToContextInfo = new Dictionary<Type, ObjectContextInfo>();
private readonly IObjectContextInfoFactory _objectContextInfoFactory;
private readonly IObjectContextFactory _recursionFactory;
public CachingObjectContextFactory(IInstantiator instantiator, IObjectContextInfoFactory objectContextInfoFactory, IObjectContextFactory recursionFactory)
{
if (instantiator == null)
throw new ArgumentNullException("instantiator");
if (objectContextInfoFactory == null)
throw new ArgumentNullException("objectContextInfoFactory");
if (recursionFactory == null)
throw new ArgumentNullException("recursionFactory");
_instantiator = instantiator;
_objectContextInfoFactory = objectContextInfoFactory;
_recursionFactory = recursionFactory;
}
public IObjectContext CreateForDeserialization(IMemberContext targetMember, Type targetType, IAdviceRequester adviceRequester)
{
ObjectContextInfo contextInfo = GetContextInfo(targetType, adviceRequester);
object target = _instantiator.Create(targetType, adviceRequester);
if (target == null)
throw new ArgumentException("Unable to create instance of '" + targetType + "' for member '" + targetMember + "'.");
return contextInfo.CreateFor(target);
}
public IObjectContext CreateForSerialization(IMemberContext sourceMember, object source, IAdviceRequester adviceRequester)
{
if (source == null)
return null;
ObjectContextInfo contextInfo = GetContextInfo(source.GetType(), adviceRequester);
return contextInfo.CreateFor(source);
}
private ObjectContextInfo CreateContextInfo(Type actualType, IAdviceRequester adviceRequester)
{
return _objectContextInfoFactory.Create(_recursionFactory, actualType, adviceRequester);
}
private ObjectContextInfo GetContextInfo(Type actualType, IAdviceRequester adviceRequester)
{
ObjectContextInfo contextInfo;
using (_lock.EnterReadScope())
_mapActualTypeToContextInfo.TryGetValue(actualType, out contextInfo);
if (contextInfo == null)
{
using (_lock.EnterWriteScope())
{
if (!_mapActualTypeToContextInfo.TryGetValue(actualType, out contextInfo))
_mapActualTypeToContextInfo[actualType] = contextInfo = CreateContextInfo(actualType, adviceRequester);
}
}
return contextInfo;
}
}
} | kimbirkelund/SekhmetSerialization | trunk/src/Sekhmet.Serialization/CachingObjectContextFactory.cs | C# | mit | 3,112 |
require "rails_helper"
RSpec.describe DiagnosesController, type: :routing do
describe "routing" do
it "routes to #index" do
expect(:get => "/diagnoses").to route_to("diagnoses#index")
end
it "routes to #new" do
expect(:get => "/diagnoses/new").to route_to("diagnoses#new")
end
it "routes to #show" do
expect(:get => "/diagnoses/1").to route_to("diagnoses#show", :id => "1")
end
it "routes to #edit" do
expect(:get => "/diagnoses/1/edit").to route_to("diagnoses#edit", :id => "1")
end
it "routes to #create" do
expect(:post => "/diagnoses").to route_to("diagnoses#create")
end
it "routes to #update via PUT" do
expect(:put => "/diagnoses/1").to route_to("diagnoses#update", :id => "1")
end
it "routes to #update via PATCH" do
expect(:patch => "/diagnoses/1").to route_to("diagnoses#update", :id => "1")
end
it "routes to #destroy" do
expect(:delete => "/diagnoses/1").to route_to("diagnoses#destroy", :id => "1")
end
end
end
| KarlHeitmann/Programa-Clinico | spec/routing/diagnoses_routing_spec.rb | Ruby | mit | 1,050 |
__global__ void /*{kernel_name}*/(/*{parameters}*/)
{
int _tid_ = threadIdx.x + blockIdx.x * blockDim.x;
if (_tid_ < /*{num_threads}*/)
{
/*{execution}*/
_result_[_tid_] = /*{block_invocation}*/;
}
}
| prg-titech/ikra-ruby | lib/resources/cuda/kernel.cpp | C++ | mit | 238 |
#!/usr/bin/env python2.7
import sys
for line in open(sys.argv[1]):
cut=line.split('\t')
if len(cut)<11: continue
print ">"+cut[0]
print cut[9]
print "+"
print cut[10]
| ursky/metaWRAP | bin/metawrap-scripts/sam_to_fastq.py | Python | mit | 173 |
#ifndef __CXXU_TYPE_TRAITS_H__
#define __CXXU_TYPE_TRAITS_H__
#include <type_traits>
#include <memory>
namespace cxxu {
template <typename T>
struct is_shared_ptr_helper : std::false_type
{
typedef T element_type;
static
element_type& deref(element_type& e)
{ return e; }
static
const element_type& deref(const element_type& e)
{ return e; }
};
template <typename T>
struct is_shared_ptr_helper<std::shared_ptr<T>> : std::true_type
{
typedef typename std::remove_cv<T>::type element_type;
typedef std::shared_ptr<element_type> ptr_type;
static
element_type& deref(ptr_type& p)
{ return *p; }
static
const element_type& deref(const ptr_type& p)
{ return *p; }
};
template <typename T>
struct is_shared_ptr
: is_shared_ptr_helper<typename std::remove_cv<T>::type>
{};
} // namespace cxxu
#endif // __CXXU_TYPE_TRAITS_H__
| ExpandiumSAS/cxxutils | sources/include/cxxu/cxxu/type_traits.hpp | C++ | mit | 890 |
package by.itransition.dpm.service;
import by.itransition.dpm.dao.BookDao;
import by.itransition.dpm.dao.UserDao;
import by.itransition.dpm.entity.Book;
import by.itransition.dpm.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
public class BookService {
@Autowired
private BookDao bookDao;
@Autowired
private UserDao userDao;
@Autowired
private UserService userService;
public void setBookDao(BookDao bookDao) {
this.bookDao = bookDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Transactional
public void addBook(Book book){
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String name = authentication.getName();
User user = userDao.getUserByLogin(name);
book.setUser(user);
bookDao.saveBook(book);
userService.addBook(user, book);
}
@Transactional
public List<Book> getAllBooks() {
return bookDao.getAllBooks();
}
@Transactional
public List<Book> getUserBooks(User user) {
return user.getBooks();
}
@Transactional
public void deleteBookById(Integer id) {
bookDao.deleteBookById(id);
}
@Transactional
public Book getBookById (Integer id){
return bookDao.getBookById(id);
}
}
| AndreiBiruk/DPM | src/main/java/by/itransition/dpm/service/BookService.java | Java | mit | 1,653 |
/**
* getRoles - get all roles
*
* @api {get} /roles Get all roles
* @apiName GetRoles
* @apiGroup Role
*
*
* @apiSuccess {Array[Role]} raw Return table of roles
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* [
* {
* "id": 1,
* "name": "Administrator",
* "slug": "administrator"
* }
* ]
*
* @apiUse InternalServerError
*/
/**
* createRole - create new role
*
* @api {post} /roles Create a role
* @apiName CreateRole
* @apiGroup Role
* @apiPermission admin
*
* @apiParam {String} name Name of new role
* @apiParam {String} slug Slug from name of new role
*
* @apiSuccess (Created 201) {Number} id Id of new role
* @apiSuccess (Created 201) {String} name Name of new role
* @apiSuccess (Created 201) {String} slug Slug of new role
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 201 Created
* {
* "id": 3,
* "name": "Custom",
* "slug": "custom"
* }
*
* @apiUse BadRequest
* @apiUse InternalServerError
*/
/**
* getRole - get role by id
*
* @api {get} /roles/:id Get role by id
* @apiName GetRole
* @apiGroup Role
*
* @apiSuccess {Number} id Id of role
* @apiSuccess {String} name Name of role
* @apiSuccess {String} slug Slug of role
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* "id": 2,
* "name": "User",
* "slug": "user"
* }
*
* @apiUse NotFound
* @apiUse InternalServerError
*/
/**
* updateRole - update role
*
* @api {put} /roles/:id Update role from id
* @apiName UpdateRole
* @apiGroup Role
* @apiPermission admin
*
*
* @apiParam {String} name New role name
* @apiParam {String} slug New role slug
*
* @apiSuccess {Number} id Id of role
* @apiSuccess {String} name Name of role
* @apiSuccess {String} slug Slug of role
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* "id": 3,
* "name": "Customer",
* "slug": "customer"
* }
*
* @apiUse NotFound
* @apiUse BadRequest
* @apiUse InternalServerError
*/
/**
* deleteRole - delete role
*
* @api {delete} /roles/:id Delete role from id
* @apiName DeleteRole
* @apiGroup Role
* @apiPermission admin
*
*
* @apiSuccessExample Success-Response:
* HTTP/1.1 204 No Content
*
* @apiUse NotFound
* @apiUse BadRequest
* @apiUse InternalServerError
*/
| MadDeveloper/easy.js | src/bundles/role/doc/role.doc.js | JavaScript | mit | 2,414 |
import { Component } from 'react';
import format from '../components/format';
import parse from 'date-fns/parse';
import getDay from 'date-fns/get_day';
import Media from 'react-media';
import Page from '../layouts/Page';
import TimelineView from '../components/TimelineView';
import ListView from '../components/ListView';
import db from '../events';
export default class extends Component {
static async getInitialProps({ query }) {
const response = db
.map((event, id) => ({
...event,
id
}))
.filter((event) => {
if (!query.day) {
return true;
}
return getDay(event.startsAt) === parseInt(query.day, 10);
});
const events = await Promise.resolve(response);
return {
events: events.reduce((groupedByDay, event) => {
const day = format(event.startsAt, 'dddd');
groupedByDay[day] = [...(groupedByDay[day] || []), event];
return groupedByDay;
}, {})
};
}
render() {
return (
<Page title="Arrangementer">
<Media
query="(max-width: 799px)"
>
{(matches) => {
const Component = matches ? ListView : TimelineView;
return <Component events={this.props.events} />;
}}
</Media>
</Page>
);
}
}
| webkom/jubileum.abakus.no | pages/index.js | JavaScript | mit | 1,320 |
import { defineAsyncComponent } from 'vue';
import { showModal } from '../../../modal/modal.service';
import { User } from '../../../user/user.model';
import { GameBuild } from '../../build/build.model';
import { Game } from '../../game.model';
import { GamePackage } from '../package.model';
interface GamePackagePurchaseModalOptions {
game: Game;
package: GamePackage;
build: GameBuild | null;
fromExtraSection: boolean;
partnerKey?: string;
partner?: User;
}
export class GamePackagePurchaseModal {
static async show(options: GamePackagePurchaseModalOptions) {
return await showModal<void>({
modalId: 'GamePackagePurchase',
component: defineAsyncComponent(() => import('./purchase-modal.vue')),
size: 'sm',
props: options,
});
}
}
| gamejolt/gamejolt | src/_common/game/package/purchase-modal/purchase-modal.service.ts | TypeScript | mit | 761 |
//
// detail/win_iocp_socket_recvfrom_op.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2012 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.lslboost.org/LICENSE_1_0.txt)
//
#ifndef BOOST_ASIO_DETAIL_WIN_IOCP_SOCKET_RECVFROM_OP_HPP
#define BOOST_ASIO_DETAIL_WIN_IOCP_SOCKET_RECVFROM_OP_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <lslboost/asio/detail/config.hpp>
#if defined(BOOST_ASIO_HAS_IOCP)
#include <lslboost/utility/addressof.hpp>
#include <lslboost/asio/detail/bind_handler.hpp>
#include <lslboost/asio/detail/buffer_sequence_adapter.hpp>
#include <lslboost/asio/detail/fenced_block.hpp>
#include <lslboost/asio/detail/handler_alloc_helpers.hpp>
#include <lslboost/asio/detail/handler_invoke_helpers.hpp>
#include <lslboost/asio/detail/operation.hpp>
#include <lslboost/asio/detail/socket_ops.hpp>
#include <lslboost/asio/error.hpp>
#include <lslboost/asio/detail/push_options.hpp>
namespace lslboost {
namespace asio {
namespace detail {
template <typename MutableBufferSequence, typename Endpoint, typename Handler>
class win_iocp_socket_recvfrom_op : public operation
{
public:
BOOST_ASIO_DEFINE_HANDLER_PTR(win_iocp_socket_recvfrom_op);
win_iocp_socket_recvfrom_op(Endpoint& endpoint,
socket_ops::weak_cancel_token_type cancel_token,
const MutableBufferSequence& buffers, Handler& handler)
: operation(&win_iocp_socket_recvfrom_op::do_complete),
endpoint_(endpoint),
endpoint_size_(static_cast<int>(endpoint.capacity())),
cancel_token_(cancel_token),
buffers_(buffers),
handler_(BOOST_ASIO_MOVE_CAST(Handler)(handler))
{
}
int& endpoint_size()
{
return endpoint_size_;
}
static void do_complete(io_service_impl* owner, operation* base,
const lslboost::system::error_code& result_ec,
std::size_t bytes_transferred)
{
lslboost::system::error_code ec(result_ec);
// Take ownership of the operation object.
win_iocp_socket_recvfrom_op* o(
static_cast<win_iocp_socket_recvfrom_op*>(base));
ptr p = { lslboost::addressof(o->handler_), o, o };
BOOST_ASIO_HANDLER_COMPLETION((o));
#if defined(BOOST_ASIO_ENABLE_BUFFER_DEBUGGING)
// Check whether buffers are still valid.
if (owner)
{
buffer_sequence_adapter<lslboost::asio::mutable_buffer,
MutableBufferSequence>::validate(o->buffers_);
}
#endif // defined(BOOST_ASIO_ENABLE_BUFFER_DEBUGGING)
socket_ops::complete_iocp_recvfrom(o->cancel_token_, ec);
// Record the size of the endpoint returned by the operation.
o->endpoint_.resize(o->endpoint_size_);
// Make a copy of the handler so that the memory can be deallocated before
// the upcall is made. Even if we're not about to make an upcall, a
// sub-object of the handler may be the true owner of the memory associated
// with the handler. Consequently, a local copy of the handler is required
// to ensure that any owning sub-object remains valid until after we have
// deallocated the memory here.
detail::binder2<Handler, lslboost::system::error_code, std::size_t>
handler(o->handler_, ec, bytes_transferred);
p.h = lslboost::addressof(handler.handler_);
p.reset();
// Make the upcall if required.
if (owner)
{
fenced_block b(fenced_block::half);
BOOST_ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_, handler.arg2_));
lslboost_asio_handler_invoke_helpers::invoke(handler, handler.handler_);
BOOST_ASIO_HANDLER_INVOCATION_END;
}
}
private:
Endpoint& endpoint_;
int endpoint_size_;
socket_ops::weak_cancel_token_type cancel_token_;
MutableBufferSequence buffers_;
Handler handler_;
};
} // namespace detail
} // namespace asio
} // namespace lslboost
#include <lslboost/asio/detail/pop_options.hpp>
#endif // defined(BOOST_ASIO_HAS_IOCP)
#endif // BOOST_ASIO_DETAIL_WIN_IOCP_SOCKET_RECVFROM_OP_HPP
| gazzlab/LSL-gazzlab-branch | liblsl/external/lslboost/asio/detail/win_iocp_socket_recvfrom_op.hpp | C++ | mit | 4,108 |
module.exports = (req, res, next) => {
req.context = req.context || {};
next();
};
| thedavisproject/davis-web | src/middleware/initContext.js | JavaScript | mit | 87 |
'use strict';
angular.module('achan.previewer').service('imagePreviewService', function () {
var source;
var ImagePreviewService = {
render: function (scope, element) {
element.html('<img src="' + source + '" class="img-responsive" />');
},
forSource: function (src) {
source = src;
return ImagePreviewService;
}
};
return ImagePreviewService;
});
| achan/angular-previewer | app/scripts/services/imagePreviewService.js | JavaScript | mit | 392 |
require 'spec_helper'
describe Group do
# Check that gems are installed
# Acts as Taggable on gem
it { should have_many(:base_tags).through(:taggings) }
# Check that appropriate fields are accessible
it { should allow_mass_assignment_of(:name) }
it { should allow_mass_assignment_of(:description) }
it { should allow_mass_assignment_of(:public) }
it { should allow_mass_assignment_of(:tag_list) }
# Check that validations are happening properly
it { should validate_presence_of(:name) }
context 'Class Methods' do
describe '#open_to_the_public' do
include_context 'groups support'
subject { Group.open_to_the_public }
it { should include public_group }
it { should_not include private_group }
end
end
end | gemvein/cooperative | spec/models/group_spec.rb | Ruby | mit | 768 |
# -*- coding: utf-8 -*-
# Keyak v2 implementation by Jos Wetzels and Wouter Bokslag
# hereby denoted as "the implementer".
# Based on Keccak Python and Keyak v2 C++ implementations
# by the Keccak, Keyak and Ketje Teams, namely, Guido Bertoni,
# Joan Daemen, Michaël Peeters, Gilles Van Assche and Ronny Van Keer
#
# For more information, feedback or questions, please refer to:
# http://keyak.noekeon.org/
# http://keccak.noekeon.org/
# http://ketje.noekeon.org/
from StringIO import StringIO
class stringStream(StringIO):
# Peek (extract byte without advancing position, return None if no more stream is available)
def peek(self):
oldPos = self.tell()
b = self.read(1)
newPos = self.tell()
if((newPos == (oldPos+1)) and (b != '')):
r = ord(b)
else:
r = None
self.seek(oldPos, 0)
return r
# Pop a single byte (as integer representation)
def get(self):
return ord(self.read(1))
# Push a single byte (as integer representation)
def put(self, b):
self.write(chr(b))
return
# Erase buffered contents
def erase(self):
self.truncate(0)
self.seek(0, 0)
return
# Set buffered contents
def setvalue(self, s):
self.erase()
self.write(s)
return
def hasMore(I):
return (I.peek() != None)
def enc8(x):
if (x > 255):
raise Exception("The integer %d cannot be encoded on 8 bits." % x)
else:
return x
# Constant-time comparison from the Django source: https://github.com/django/django/blob/master/django/utils/crypto.py
# Is constant-time only if both strings are of equal length but given the use-case that is always the case.
def constant_time_compare(val1, val2):
if len(val1) != len(val2):
return False
result = 0
for x, y in zip(val1, val2):
result |= ord(x) ^ ord(y)
return result == 0 | samvartaka/keyak-python | utils.py | Python | mit | 1,775 |
import _plotly_utils.basevalidators
class BordercolorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(
self, plotly_name="bordercolor", parent_name="sankey.hoverlabel", **kwargs
):
super(BordercolorValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
array_ok=kwargs.pop("array_ok", True),
edit_type=kwargs.pop("edit_type", "calc"),
**kwargs
)
| plotly/plotly.py | packages/python/plotly/plotly/validators/sankey/hoverlabel/_bordercolor.py | Python | mit | 482 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace jaytwo.Common.Futures.Numbers
{
public static class MathUtility
{
public static double StandardDeviation(IEnumerable<double> data)
{
var average = data.Average();
var individualDeviations = data.Select(x => Math.Pow(x - average, 2));
return Math.Sqrt(individualDeviations.Average());
}
public static double StandardDeviation(params double[] data)
{
return StandardDeviation((IEnumerable<double>)data);
}
}
} | jakegough/jaytwo.CommonLib | CommonLib.Futures/Numbers/MathUtility.cs | C# | mit | 534 |
using FFImageLoading.Forms.Sample.WinPhoneSL.Resources;
namespace FFImageLoading.Forms.Sample.WinPhoneSL
{
/// <summary>
/// Provides access to string resources.
/// </summary>
public class LocalizedStrings
{
private static AppResources _localizedResources = new AppResources();
public AppResources LocalizedResources { get { return _localizedResources; } }
}
}
| AndreiMisiukevich/FFImageLoading | samples/ImageLoading.Forms.Sample/WinPhoneSL/FFImageLoading.Forms.Sample.WinPhoneSL/LocalizedStrings.cs | C# | mit | 407 |
package com.aws.global.dao;
import java.util.ArrayList;
import com.aws.global.classes.Pizza;
import com.aws.global.common.base.BaseDAO;
import com.aws.global.mapper.PizzaRowMapper;
public class PizzaDAO extends BaseDAO{
//SQL Statement when user adds a pizza to his inventory
public void addPizza(String pizzaName, int pizzaPrice)
{
String sql = "INSERT INTO PIZZA (pizza_id, pizza_name, pizza_price) VALUES (NULL, ?, ?);";
getJdbcTemplate().update(sql, new Object[] { pizzaName, pizzaPrice});
}
//SQL Statement when user wants to get a list of pizzas
public ArrayList<Pizza> getAllPizza()
{
String sql = "SELECT * FROM Pizza";
ArrayList<Pizza> pizzas = (ArrayList<Pizza>) getJdbcTemplate().query(sql, new PizzaRowMapper());
return pizzas;
}
//SQL Statement when user wants to get a pizza record using a pizza id
public Pizza getPizzaById(int id)
{
String sql = "SELECT * FROM PIZZA WHERE pizza_id = ?";
Pizza pizza = (Pizza)getJdbcTemplate().queryForObject(
sql, new Object[] { id },
new PizzaRowMapper());
return pizza;
}
//SQL Statement when user wants to update a certain pizza's information
public void editPizza(String pizza_name, int pizza_price, int id)
{
String sql = "UPDATE PIZZA SET pizza_name = ?, pizza_price = ? WHERE pizza_id = ?;";
getJdbcTemplate().update(sql, new Object[] { pizza_name, pizza_price, id });
}
//SQL Statement when user wants to delete a pizza information
public void deletePizza(int id)
{
String sql = "DELETE FROM PIZZA WHERE pizza_id = ?";
getJdbcTemplate().update(sql, new Object[] { id });
}
}
| sethbusque/pizzaccio | src_custom/com/aws/global/dao/PizzaDAO.java | Java | mit | 1,598 |
var test = require('./tape')
var mongojs = require('../index')
test('should export bson types', function (t) {
t.ok(mongojs.Binary)
t.ok(mongojs.Code)
t.ok(mongojs.DBRef)
t.ok(mongojs.Double)
t.ok(mongojs.Long)
t.ok(mongojs.MinKey)
t.ok(mongojs.MaxKey)
t.ok(mongojs.ObjectID)
t.ok(mongojs.ObjectId)
t.ok(mongojs.Symbol)
t.ok(mongojs.Timestamp)
t.ok(mongojs.Decimal128)
t.end()
})
| mafintosh/mongojs | test/test-expose-bson-types.js | JavaScript | mit | 408 |
class SuchStreamingBot
class << self
def matches? text
!!(text =~ /hello world/)
end
end
end
| coleww/twitter_bot_generator | such_streaming_bot/src/such_streaming_bot.rb | Ruby | mit | 115 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Les informations générales relatives à un assembly dépendent de
// l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations
// associées à un assembly.
[assembly: AssemblyTitle("Client")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Client")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly
// aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de
// COM, affectez la valeur true à l'attribut ComVisible sur ce type.
[assembly: ComVisible(false)]
// Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM
[assembly: Guid("210de826-2c8c-4023-a45b-777ce845b803")]
// Les informations de version pour un assembly se composent des quatre valeurs suivantes :
//
// Version principale
// Version secondaire
// Numéro de build
// Révision
//
// Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut
// en utilisant '*', comme indiqué ci-dessous :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| Monkios/ClientServerGame | ConsoleClient/Properties/AssemblyInfo.cs | C# | mit | 1,546 |
package com.instaclick.filter;
/**
* Defines a behavior that should be implement by all filter
*
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
*/
public interface DataFilter
{
/**
* Adds the given {@link Data} if it does not exists
*
* @param data
*
* @return <b>TRUE</b> if the the {@link Data} does not exists; <b>FALSE</b> otherwise
*/
public boolean add(Data data);
/**
* Check if the given {@link Data} exists
*
* @param data
*
* @return <b>TRUE</b> if the the {@link Data} does not exists; <b>FALSE</b> otherwise
*/
public boolean contains(Data data);
/**
* Flushes the filter data, this operation should be invoked at the end of the filter
*/
public void flush();
} | instaclick/PDI-Plugin-Step-BloomFilter | ic-filter/src/main/java/com/instaclick/filter/DataFilter.java | Java | mit | 780 |
#include <bits/stdc++.h>
using namespace std;
int count_consecutive(string &s, int n, int k, char x) {
int mx_count = 0;
int x_count = 0;
int curr_count = 0;
int l = 0;
int r = 0;
while (r < n) {
if (x_count <= k) {
if (s[r] == x)
x_count++;
r++;
curr_count++;
if (s[r-1] != x) mx_count = max(mx_count, curr_count);
} else {
if (s[l] == x) {
x_count--;
}
l++;
curr_count--;
}
}
if (s[s.size()-1] == x && x_count) mx_count++;
return mx_count;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, k;
string s;
cin >> n >> k;
cin >> s;
cout << max(count_consecutive(s, n, k, 'b'), count_consecutive(s, n, k, 'a')) << endl;
return 0;
}
| sazid/codes | problem_solving/codeforces/676C.cpp | C++ | mit | 881 |
using BaxterWorks.B2.Exceptions;
using BaxterWorks.B2.Types;
namespace BaxterWorks.B2.Extensions
{
public static class BucketExtensions
{
public static Bucket GetOrCreateBucket(this ServiceStackB2Api client, CreateBucketRequest request)
{
try
{
return client.CreateBucket(request);
}
catch (DuplicateBucketException) //todo: there are other ways this could fail
{
return client.GetBucketByName(request.BucketName);
}
}
/// <summary>
/// Get an existing bucket, or create a new one if it doesn't exist. Defaults to a private bucket
/// </summary>
/// <param name="client"></param>
/// <param name="bucketName"></param>
/// <returns><see cref="Bucket"/></returns>
public static Bucket GetOrCreateBucket(this ServiceStackB2Api client, string bucketName)
{
try
{
return client.CreateBucket(bucketName);
}
catch (DuplicateBucketException) //todo: there are other ways this could fail
{
return client.GetBucketByName(bucketName);
}
}
public static Bucket OverwriteBucket(this ServiceStackB2Api client, CreateBucketRequest request, bool deleteFiles = false)
{
try
{
return client.CreateBucket(request);
}
catch (DuplicateBucketException) //todo: there are other ways this could fail
{
Bucket targetBucket = client.GetBucketByName(request.BucketName);
if (deleteFiles)
{
client.DeleteBucketRecursively(targetBucket);
}
else
{
client.DeleteBucket(targetBucket);
}
return client.CreateBucket(request);
}
}
}
} | voltagex/b2-csharp | BaxterWorks.B2/Extensions/BucketExtensions.cs | C# | mit | 2,003 |
/*
* The MIT License
*
* Copyright 2017 Arnaud Hamon
*
* 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 com.github.ptitnoony.components.fxtreemap;
import java.beans.PropertyChangeListener;
import java.util.List;
/**
*
* @author ahamon
*/
public interface MapData {
/**
* Data type that represents whether a data is represents a single object
* (ie LEAF) or an aggregation of objects (ie NODE)
*/
enum DataType {
LEAF, NODE
};
DataType getType();
/**
* Get the data value.
*
* @return the data value
*/
double getValue();
/**
* Set the data value. If the data has children data, their value will be
* set with the same percentage of the value they use to have before the
* setValue is applied. The value must be equal or greater to 0.
*
* @param newValue the new data value
*/
void setValue(double newValue);
/**
* Get the data name.
*
* @return the data name
*/
String getName();
/**
* Set the data name.
*
* @param newName the new data name
*/
void setName(String newName);
/**
* If the data is an aggregation of children data.
*
* @return if the data is an aggregation of children data
*/
boolean hasChildrenData();
/**
* Get the children aggregated data if any.
*
* @return the list of aggregated data
*/
List<MapData> getChildrenData();
/**
* Add a child data. If the data had no child before, adding a child data
* will override the previously set data value.
*
* @param data the data to be added as a child data to aggregate
*/
void addChildrenData(MapData data);
/**
* Remove a child data.
*
* @param data the data to be removed
*/
void removeChildrenData(MapData data);
/**
* Add a property change listener.
*
* @param listener the listener to be added
*/
void addPropertyChangeListener(PropertyChangeListener listener);
/**
* Remove a property change listener.
*
* @param listener the listener to be removed
*/
void removePropertyChangeListener(PropertyChangeListener listener);
}
| PtitNoony/FxTreeMap | src/main/java/com/github/ptitnoony/components/fxtreemap/MapData.java | Java | mit | 3,281 |
# Potrubi
gemName = 'potrubi'
#requireList = %w(mixin/bootstrap)
#requireList.each {|r| require_relative "#{gemName}/#{r}"}
__END__
| ianrumford/potrubi | lib/potrubi/potrubi.rb | Ruby | mit | 137 |
import numpy as np
import warnings
from .._explainer import Explainer
from packaging import version
torch = None
class PyTorchDeep(Explainer):
def __init__(self, model, data):
# try and import pytorch
global torch
if torch is None:
import torch
if version.parse(torch.__version__) < version.parse("0.4"):
warnings.warn("Your PyTorch version is older than 0.4 and not supported.")
# check if we have multiple inputs
self.multi_input = False
if type(data) == list:
self.multi_input = True
if type(data) != list:
data = [data]
self.data = data
self.layer = None
self.input_handle = None
self.interim = False
self.interim_inputs_shape = None
self.expected_value = None # to keep the DeepExplainer base happy
if type(model) == tuple:
self.interim = True
model, layer = model
model = model.eval()
self.layer = layer
self.add_target_handle(self.layer)
# if we are taking an interim layer, the 'data' is going to be the input
# of the interim layer; we will capture this using a forward hook
with torch.no_grad():
_ = model(*data)
interim_inputs = self.layer.target_input
if type(interim_inputs) is tuple:
# this should always be true, but just to be safe
self.interim_inputs_shape = [i.shape for i in interim_inputs]
else:
self.interim_inputs_shape = [interim_inputs.shape]
self.target_handle.remove()
del self.layer.target_input
self.model = model.eval()
self.multi_output = False
self.num_outputs = 1
with torch.no_grad():
outputs = model(*data)
# also get the device everything is running on
self.device = outputs.device
if outputs.shape[1] > 1:
self.multi_output = True
self.num_outputs = outputs.shape[1]
self.expected_value = outputs.mean(0).cpu().numpy()
def add_target_handle(self, layer):
input_handle = layer.register_forward_hook(get_target_input)
self.target_handle = input_handle
def add_handles(self, model, forward_handle, backward_handle):
"""
Add handles to all non-container layers in the model.
Recursively for non-container layers
"""
handles_list = []
model_children = list(model.children())
if model_children:
for child in model_children:
handles_list.extend(self.add_handles(child, forward_handle, backward_handle))
else: # leaves
handles_list.append(model.register_forward_hook(forward_handle))
handles_list.append(model.register_backward_hook(backward_handle))
return handles_list
def remove_attributes(self, model):
"""
Removes the x and y attributes which were added by the forward handles
Recursively searches for non-container layers
"""
for child in model.children():
if 'nn.modules.container' in str(type(child)):
self.remove_attributes(child)
else:
try:
del child.x
except AttributeError:
pass
try:
del child.y
except AttributeError:
pass
def gradient(self, idx, inputs):
self.model.zero_grad()
X = [x.requires_grad_() for x in inputs]
outputs = self.model(*X)
selected = [val for val in outputs[:, idx]]
grads = []
if self.interim:
interim_inputs = self.layer.target_input
for idx, input in enumerate(interim_inputs):
grad = torch.autograd.grad(selected, input,
retain_graph=True if idx + 1 < len(interim_inputs) else None,
allow_unused=True)[0]
if grad is not None:
grad = grad.cpu().numpy()
else:
grad = torch.zeros_like(X[idx]).cpu().numpy()
grads.append(grad)
del self.layer.target_input
return grads, [i.detach().cpu().numpy() for i in interim_inputs]
else:
for idx, x in enumerate(X):
grad = torch.autograd.grad(selected, x,
retain_graph=True if idx + 1 < len(X) else None,
allow_unused=True)[0]
if grad is not None:
grad = grad.cpu().numpy()
else:
grad = torch.zeros_like(X[idx]).cpu().numpy()
grads.append(grad)
return grads
def shap_values(self, X, ranked_outputs=None, output_rank_order="max", check_additivity=False):
# X ~ self.model_input
# X_data ~ self.data
# check if we have multiple inputs
if not self.multi_input:
assert type(X) != list, "Expected a single tensor model input!"
X = [X]
else:
assert type(X) == list, "Expected a list of model inputs!"
X = [x.detach().to(self.device) for x in X]
if ranked_outputs is not None and self.multi_output:
with torch.no_grad():
model_output_values = self.model(*X)
# rank and determine the model outputs that we will explain
if output_rank_order == "max":
_, model_output_ranks = torch.sort(model_output_values, descending=True)
elif output_rank_order == "min":
_, model_output_ranks = torch.sort(model_output_values, descending=False)
elif output_rank_order == "max_abs":
_, model_output_ranks = torch.sort(torch.abs(model_output_values), descending=True)
else:
assert False, "output_rank_order must be max, min, or max_abs!"
model_output_ranks = model_output_ranks[:, :ranked_outputs]
else:
model_output_ranks = (torch.ones((X[0].shape[0], self.num_outputs)).int() *
torch.arange(0, self.num_outputs).int())
# add the gradient handles
handles = self.add_handles(self.model, add_interim_values, deeplift_grad)
if self.interim:
self.add_target_handle(self.layer)
# compute the attributions
output_phis = []
for i in range(model_output_ranks.shape[1]):
phis = []
if self.interim:
for k in range(len(self.interim_inputs_shape)):
phis.append(np.zeros((X[0].shape[0], ) + self.interim_inputs_shape[k][1: ]))
else:
for k in range(len(X)):
phis.append(np.zeros(X[k].shape))
for j in range(X[0].shape[0]):
# tile the inputs to line up with the background data samples
tiled_X = [X[l][j:j + 1].repeat(
(self.data[l].shape[0],) + tuple([1 for k in range(len(X[l].shape) - 1)])) for l
in range(len(X))]
joint_x = [torch.cat((tiled_X[l], self.data[l]), dim=0) for l in range(len(X))]
# run attribution computation graph
feature_ind = model_output_ranks[j, i]
sample_phis = self.gradient(feature_ind, joint_x)
# assign the attributions to the right part of the output arrays
if self.interim:
sample_phis, output = sample_phis
x, data = [], []
for k in range(len(output)):
x_temp, data_temp = np.split(output[k], 2)
x.append(x_temp)
data.append(data_temp)
for l in range(len(self.interim_inputs_shape)):
phis[l][j] = (sample_phis[l][self.data[l].shape[0]:] * (x[l] - data[l])).mean(0)
else:
for l in range(len(X)):
phis[l][j] = (torch.from_numpy(sample_phis[l][self.data[l].shape[0]:]).to(self.device) * (X[l][j: j + 1] - self.data[l])).cpu().detach().numpy().mean(0)
output_phis.append(phis[0] if not self.multi_input else phis)
# cleanup; remove all gradient handles
for handle in handles:
handle.remove()
self.remove_attributes(self.model)
if self.interim:
self.target_handle.remove()
if not self.multi_output:
return output_phis[0]
elif ranked_outputs is not None:
return output_phis, model_output_ranks
else:
return output_phis
# Module hooks
def deeplift_grad(module, grad_input, grad_output):
"""The backward hook which computes the deeplift
gradient for an nn.Module
"""
# first, get the module type
module_type = module.__class__.__name__
# first, check the module is supported
if module_type in op_handler:
if op_handler[module_type].__name__ not in ['passthrough', 'linear_1d']:
return op_handler[module_type](module, grad_input, grad_output)
else:
print('Warning: unrecognized nn.Module: {}'.format(module_type))
return grad_input
def add_interim_values(module, input, output):
"""The forward hook used to save interim tensors, detached
from the graph. Used to calculate the multipliers
"""
try:
del module.x
except AttributeError:
pass
try:
del module.y
except AttributeError:
pass
module_type = module.__class__.__name__
if module_type in op_handler:
func_name = op_handler[module_type].__name__
# First, check for cases where we don't need to save the x and y tensors
if func_name == 'passthrough':
pass
else:
# check only the 0th input varies
for i in range(len(input)):
if i != 0 and type(output) is tuple:
assert input[i] == output[i], "Only the 0th input may vary!"
# if a new method is added, it must be added here too. This ensures tensors
# are only saved if necessary
if func_name in ['maxpool', 'nonlinear_1d']:
# only save tensors if necessary
if type(input) is tuple:
setattr(module, 'x', torch.nn.Parameter(input[0].detach()))
else:
setattr(module, 'x', torch.nn.Parameter(input.detach()))
if type(output) is tuple:
setattr(module, 'y', torch.nn.Parameter(output[0].detach()))
else:
setattr(module, 'y', torch.nn.Parameter(output.detach()))
if module_type in failure_case_modules:
input[0].register_hook(deeplift_tensor_grad)
def get_target_input(module, input, output):
"""A forward hook which saves the tensor - attached to its graph.
Used if we want to explain the interim outputs of a model
"""
try:
del module.target_input
except AttributeError:
pass
setattr(module, 'target_input', input)
# From the documentation: "The current implementation will not have the presented behavior for
# complex Module that perform many operations. In some failure cases, grad_input and grad_output
# will only contain the gradients for a subset of the inputs and outputs.
# The tensor hook below handles such failure cases (currently, MaxPool1d). In such cases, the deeplift
# grad should still be computed, and then appended to the complex_model_gradients list. The tensor hook
# will then retrieve the proper gradient from this list.
failure_case_modules = ['MaxPool1d']
def deeplift_tensor_grad(grad):
return_grad = complex_module_gradients[-1]
del complex_module_gradients[-1]
return return_grad
complex_module_gradients = []
def passthrough(module, grad_input, grad_output):
"""No change made to gradients"""
return None
def maxpool(module, grad_input, grad_output):
pool_to_unpool = {
'MaxPool1d': torch.nn.functional.max_unpool1d,
'MaxPool2d': torch.nn.functional.max_unpool2d,
'MaxPool3d': torch.nn.functional.max_unpool3d
}
pool_to_function = {
'MaxPool1d': torch.nn.functional.max_pool1d,
'MaxPool2d': torch.nn.functional.max_pool2d,
'MaxPool3d': torch.nn.functional.max_pool3d
}
delta_in = module.x[: int(module.x.shape[0] / 2)] - module.x[int(module.x.shape[0] / 2):]
dup0 = [2] + [1 for i in delta_in.shape[1:]]
# we also need to check if the output is a tuple
y, ref_output = torch.chunk(module.y, 2)
cross_max = torch.max(y, ref_output)
diffs = torch.cat([cross_max - ref_output, y - cross_max], 0)
# all of this just to unpool the outputs
with torch.no_grad():
_, indices = pool_to_function[module.__class__.__name__](
module.x, module.kernel_size, module.stride, module.padding,
module.dilation, module.ceil_mode, True)
xmax_pos, rmax_pos = torch.chunk(pool_to_unpool[module.__class__.__name__](
grad_output[0] * diffs, indices, module.kernel_size, module.stride,
module.padding, list(module.x.shape)), 2)
org_input_shape = grad_input[0].shape # for the maxpool 1d
grad_input = [None for _ in grad_input]
grad_input[0] = torch.where(torch.abs(delta_in) < 1e-7, torch.zeros_like(delta_in),
(xmax_pos + rmax_pos) / delta_in).repeat(dup0)
if module.__class__.__name__ == 'MaxPool1d':
complex_module_gradients.append(grad_input[0])
# the grad input that is returned doesn't matter, since it will immediately be
# be overridden by the grad in the complex_module_gradient
grad_input[0] = torch.ones(org_input_shape)
return tuple(grad_input)
def linear_1d(module, grad_input, grad_output):
"""No change made to gradients."""
return None
def nonlinear_1d(module, grad_input, grad_output):
delta_out = module.y[: int(module.y.shape[0] / 2)] - module.y[int(module.y.shape[0] / 2):]
delta_in = module.x[: int(module.x.shape[0] / 2)] - module.x[int(module.x.shape[0] / 2):]
dup0 = [2] + [1 for i in delta_in.shape[1:]]
# handles numerical instabilities where delta_in is very small by
# just taking the gradient in those cases
grads = [None for _ in grad_input]
grads[0] = torch.where(torch.abs(delta_in.repeat(dup0)) < 1e-6, grad_input[0],
grad_output[0] * (delta_out / delta_in).repeat(dup0))
return tuple(grads)
op_handler = {}
# passthrough ops, where we make no change to the gradient
op_handler['Dropout3d'] = passthrough
op_handler['Dropout2d'] = passthrough
op_handler['Dropout'] = passthrough
op_handler['AlphaDropout'] = passthrough
op_handler['Conv1d'] = linear_1d
op_handler['Conv2d'] = linear_1d
op_handler['Conv3d'] = linear_1d
op_handler['ConvTranspose1d'] = linear_1d
op_handler['ConvTranspose2d'] = linear_1d
op_handler['ConvTranspose3d'] = linear_1d
op_handler['Linear'] = linear_1d
op_handler['AvgPool1d'] = linear_1d
op_handler['AvgPool2d'] = linear_1d
op_handler['AvgPool3d'] = linear_1d
op_handler['AdaptiveAvgPool1d'] = linear_1d
op_handler['AdaptiveAvgPool2d'] = linear_1d
op_handler['AdaptiveAvgPool3d'] = linear_1d
op_handler['BatchNorm1d'] = linear_1d
op_handler['BatchNorm2d'] = linear_1d
op_handler['BatchNorm3d'] = linear_1d
op_handler['LeakyReLU'] = nonlinear_1d
op_handler['ReLU'] = nonlinear_1d
op_handler['ELU'] = nonlinear_1d
op_handler['Sigmoid'] = nonlinear_1d
op_handler["Tanh"] = nonlinear_1d
op_handler["Softplus"] = nonlinear_1d
op_handler['Softmax'] = nonlinear_1d
op_handler['MaxPool1d'] = maxpool
op_handler['MaxPool2d'] = maxpool
op_handler['MaxPool3d'] = maxpool
| slundberg/shap | shap/explainers/_deep/deep_pytorch.py | Python | mit | 16,170 |
using Lemonade.Data.Entities;
namespace Lemonade.Data.Commands
{
public interface IUpdateFeature
{
void Execute(Feature feature);
}
} | thesheps/lemonade | src/Lemonade.Data/Commands/IUpdateFeature.cs | C# | mit | 157 |
/*
Misojs Codemirror component
*/
var m = require('mithril'),
basePath = "external/codemirror/",
pjson = require("./package.json");
// Here we have a few fixes to make CM work in node - we only setup each,
// if they don't already exist, otherwise we would override the browser
global.document = global.document || {};
global.document.createElement = global.document.createElement || function(){
return {
setAttribute: function(){}
};
};
global.window = global.window || {};
global.window.getSelection = global.window.getSelection || function(){
return false;
};
global.navigator = global.navigator || {};
global.navigator.userAgent = global.navigator.userAgent || "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.130 Safari/537.36";
// Grab code mirror and the javascript language
// Note: you cannot dynamically require with browserify,
// so we must get whatever modes we need here.
// If you need other languages, simply equire them statically in your program.
var CodeMirror = require('codemirror');
require("codemirror/mode/javascript/javascript.js");
require("codemirror/mode/htmlmixed/htmlmixed.js");
require("codemirror/mode/css/css.js");
// Our component
var CodemirrorComponent = {
// Returns a textarea
view: function(ctrl, attrs) {
return m("div", [
// It is ok to include CSS here - the browser will cache it,
// though a more ideal setup would be the ability to load only
// once when required.
m("LINK", { href: basePath + "lib/codemirror.css", rel: "stylesheet"}),
m("textarea", {config: CodemirrorComponent.config(attrs)}, attrs.value())
]);
},
config: function(attrs) {
return function(element, isInitialized) {
if(typeof CodeMirror !== 'undefined') {
if (!isInitialized) {
var editor = CodeMirror.fromTextArea(element, {
lineNumbers: true
});
editor.on("change", function(instance, object) {
m.startComputation();
attrs.value(editor.doc.getValue());
if (typeof attrs.onchange == "function"){
attrs.onchange(instance, object);
}
m.endComputation();
});
}
} else {
console.warn('ERROR: You need Codemirror in the page');
}
};
}
};
// Allow the user to pass in arguments when loading.
module.exports = function(args){
if(args && args.basePath) {
basePath = args.basePath;
}
return CodemirrorComponent;
}; | jsguy/misojs-codemirror-component | codemirror.component.js | JavaScript | mit | 2,410 |
// github package provides an API client for github.com
//
// Copyright (C) 2014 Yohei Sasaki
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package github
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"time"
)
const BaseUrl = "https://api.github.com"
type Client struct {
RateLimit int
RateLimitRemaining int
RateLimitReset time.Time
baseUrl string
client *http.Client
}
func NewClient(c *http.Client) *Client {
return &Client{
baseUrl: BaseUrl,
client: c,
}
}
type MarkdownMode string
var Markdown = MarkdownMode("markdown")
var Gfm = MarkdownMode("gfm")
type ApiError struct {
Status int
Body string
*Client
}
func (e *ApiError) Error() string {
return fmt.Sprintf("Github API Error: %d - %v", e.Status, e.Body)
}
func NewApiError(status int, body string, c *Client) *ApiError {
return &ApiError{Status: status, Body: body, Client: c}
}
func IsApiError(err error) bool {
switch err.(type) {
case *ApiError:
return true
default:
return false
}
}
// Call /markdown API
// See: https://developer.github.com/v3/markdown/
func (g *Client) Markdown(text string, mode MarkdownMode, context string) (string, error) {
url := g.baseUrl + "/markdown"
body := map[string]string{
"text": text,
"mode": string(mode),
"context": context,
}
buff, _ := json.Marshal(body)
resp, err := g.client.Post(url, "application/json", bytes.NewBuffer(buff))
if err != nil {
return "", err
}
defer resp.Body.Close()
buff, err = ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
g.updateRateLimit(resp)
if resp.StatusCode != http.StatusOK {
return "", NewApiError(resp.StatusCode, string(buff), g)
}
return string(buff), nil
}
// Returns if the client exceeds the limit or not.
func (g *Client) LimitExceeded() bool {
if g.RateLimit == 0 && g.RateLimitRemaining == 0 { // initial value
return false
}
return g.RateLimitRemaining == 0
}
func (g *Client) updateRateLimit(resp *http.Response) {
limit := resp.Header.Get("X-Ratelimit-Limit")
i, err := strconv.ParseInt(limit, 10, 32)
if err == nil {
g.RateLimit = int(i)
}
remaining := resp.Header.Get("X-Ratelimit-Remaining")
i, err = strconv.ParseInt(remaining, 10, 32)
if err == nil {
g.RateLimitRemaining = int(i)
}
reset := resp.Header.Get("X-Ratelimit-Reset")
i, err = strconv.ParseInt(reset, 10, 32)
if err == nil {
g.RateLimitReset = time.Unix(i, 0)
}
}
| speedland/wcg | supports/github/api.go | GO | mit | 3,000 |
<?php
namespace Oro\Bundle\AttachmentBundle\Tests\Unit\Entity;
use Oro\Bundle\AttachmentBundle\Entity\File;
use Oro\Bundle\UserBundle\Entity\User;
use Oro\Component\Testing\Unit\EntityTestCaseTrait;
use Oro\Component\Testing\Unit\EntityTrait;
use Symfony\Component\HttpFoundation\File\File as ComponentFile;
class FileTest extends \PHPUnit\Framework\TestCase
{
use EntityTestCaseTrait;
use EntityTrait;
/** @var File */
private $entity;
protected function setUp()
{
$this->entity = new File();
}
public function testAccessors(): void
{
$properties = [
['id', 1],
['uuid', '123e4567-e89b-12d3-a456-426655440000', false],
['owner', new User()],
['filename', 'sample_filename'],
['extension', 'smplext'],
['mimeType', 'sample/mime-type'],
['originalFilename', 'sample_original_filename'],
['fileSize', 12345],
['parentEntityClass', \stdClass::class],
['parentEntityId', 2],
['parentEntityFieldName', 'sampleFieldName'],
['createdAt', new \DateTime('today')],
['updatedAt', new \DateTime('today')],
['file', new ComponentFile('sample/file', false)],
['emptyFile', true],
];
static::assertPropertyAccessors($this->entity, $properties);
}
public function testPrePersists(): void
{
$testDate = new \DateTime('now', new \DateTimeZone('UTC'));
$this->entity->prePersist();
$this->entity->preUpdate();
$this->assertEquals($testDate->format('Y-m-d'), $this->entity->getCreatedAt()->format('Y-m-d'));
$this->assertEquals($testDate->format('Y-m-d'), $this->entity->getUpdatedAt()->format('Y-m-d'));
}
public function testEmptyFile(): void
{
$this->assertNull($this->entity->isEmptyFile());
$this->entity->setEmptyFile(true);
$this->assertTrue($this->entity->isEmptyFile());
}
public function testToString(): void
{
$this->assertSame('', $this->entity->__toString());
$this->entity->setFilename('file.doc');
$this->entity->setOriginalFilename('original.doc');
$this->assertEquals('file.doc (original.doc)', $this->entity->__toString());
}
public function testSerialize(): void
{
$this->assertSame(serialize([null, null, $this->entity->getUuid()]), $this->entity->serialize());
$this->assertEquals(
serialize([1, 'sample_filename', 'test-uuid']),
$this->getEntity(
File::class,
['id' => 1, 'filename' => 'sample_filename', 'uuid' => 'test-uuid']
)->serialize()
);
}
public function testUnserialize(): void
{
$this->entity->unserialize(serialize([1, 'sample_filename', 'test-uuid']));
$this->assertSame('sample_filename', $this->entity->getFilename());
$this->assertSame(1, $this->entity->getId());
$this->assertSame('test-uuid', $this->entity->getUuid());
}
}
| orocrm/platform | src/Oro/Bundle/AttachmentBundle/Tests/Unit/Entity/FileTest.php | PHP | mit | 3,094 |
require 'json_diff/version'
# Provides helper methods to compare object trees (like those generated by JSON.parse)
# and generate a list of their differences.
module JSONDiff
# Generates an Array of differences between the two supplied object trees with Hash roots.
#
# @param a [Hash] the left hand side of the comparison.
# @param b [Hash] the right hand side of the comparison.
# @param path [String] the JSON path at which `a` and `b` are found in a larger object tree.
# @return [Array<String>] the differences found between `a` and `b`.
def self.objects(a, b, path='')
differences = []
a.each do |k, v|
if b.has_key? k
if v.class != b[k].class
differences << "type mismatch: #{path}/#{k} '#{v.class}' != '#{b[k].class}'"
else
if v.is_a? Hash
differences += objects(v, b[k], "#{path}/#{k}")
elsif v.is_a? Array
differences += arrays(v, b[k], "#{path}/#{k}")
elsif v != b[k] # String, TrueClass, FalseClass, NilClass, Float, Fixnum
differences << "value mismatch: #{path}/#{k} '#{v}' != '#{b[k]}'"
end
end
else
differences << "b is missing: #{path}/#{k}"
end
end
(b.keys - a.keys).each do |k, v|
differences << "a is missing: #{path}/#{k}"
end
differences
end
# Generates an Array of differences between the two supplied object trees with Array roots.
#
# @param a [Array] the left hand side of the comparison.
# @param b [Array] the right hand side of the comparison.
# @param path [String] the JSON path at which `a` and `b` are found in a larger object tree.
# @return [Array<String>] the differences found between `a` and `b`.
def self.arrays(a, b, path='/')
differences = []
if a.size != b.size
differences << "size mismatch: #{path}"
else
a.zip(b).each_with_index do |pair, index|
if pair[0].class != pair[1].class
differences << "type mismatch: #{path}[#{index}] '#{pair[0].class}' != '#{pair[1].class}'"
else
if pair[0].is_a? Hash
differences += objects(pair[0], pair[1], "#{path}[#{index}]")
elsif pair[0].is_a? Array
differences += arrays(pair[0], pair[1], "#{path}[#{index}]")
elsif pair[0] != pair[1] # String, TrueClass, FalseClass, NilClass, Float, Fixnum
differences << "value mismatch: #{path}[#{index}] '#{pair[0]}' != '#{pair[1]}'"
end
end
end
end
differences
end
end
| chrisvroberts/json_diff | lib/json_diff.rb | Ruby | mit | 2,550 |
import { observable, action } from 'mobx';
import Fuse from 'fuse.js';
import Activity from './../utils/Activity';
import noop from 'lodash/noop';
import uniqBy from 'lodash/uniqBy';
const inactive = Activity(500);
export default class Story {
@observable keyword = '';
@observable allStories = [];
@observable stories = [];
@action search(keyword) {
this.keyword = keyword;
inactive().then(() => {
this.stories = this.searchStories(this.allStories, this.keyword);
}, noop);
}
@action addStories(stories){
this.allStories = uniqBy(this.allStories.concat(stories), story => story.key);
this.stories = this.searchStories(this.allStories, this.keyword);
}
searchStories(stories, keyword) {
/**
* threshold is the correctness of the search
* @type {{threshold: number, keys: string[]}}
*/
const options = {
threshold: 0.2,
keys: ['text']
};
const google = new Fuse(stories, options);
return google.search(keyword) || [];
}
}
| nadimtuhin/facebook-activity-monitor | src/content/store/Story.js | JavaScript | mit | 1,020 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import time
import curses
from . import docs
from .content import SubmissionContent, SubredditContent
from .page import Page, PageController, logged_in
from .objects import Navigator, Color, Command
from .exceptions import TemporaryFileError
class SubmissionController(PageController):
character_map = {}
class SubmissionPage(Page):
FOOTER = docs.FOOTER_SUBMISSION
def __init__(self, reddit, term, config, oauth, url=None, submission=None):
super(SubmissionPage, self).__init__(reddit, term, config, oauth)
self.controller = SubmissionController(self, keymap=config.keymap)
if url:
self.content = SubmissionContent.from_url(
reddit, url, term.loader,
max_comment_cols=config['max_comment_cols'])
else:
self.content = SubmissionContent(
submission, term.loader,
max_comment_cols=config['max_comment_cols'])
# Start at the submission post, which is indexed as -1
self.nav = Navigator(self.content.get, page_index=-1)
self.selected_subreddit = None
@SubmissionController.register(Command('SUBMISSION_TOGGLE_COMMENT'))
def toggle_comment(self):
"Toggle the selected comment tree between visible and hidden"
current_index = self.nav.absolute_index
self.content.toggle(current_index)
# This logic handles a display edge case after a comment toggle. We
# want to make sure that when we re-draw the page, the cursor stays at
# its current absolute position on the screen. In order to do this,
# apply a fixed offset if, while inverted, we either try to hide the
# bottom comment or toggle any of the middle comments.
if self.nav.inverted:
data = self.content.get(current_index)
if data['hidden'] or self.nav.cursor_index != 0:
window = self._subwindows[-1][0]
n_rows, _ = window.getmaxyx()
self.nav.flip(len(self._subwindows) - 1)
self.nav.top_item_height = n_rows
@SubmissionController.register(Command('SUBMISSION_EXIT'))
def exit_submission(self):
"Close the submission and return to the subreddit page"
self.active = False
@SubmissionController.register(Command('REFRESH'))
def refresh_content(self, order=None, name=None):
"Re-download comments and reset the page index"
order = order or self.content.order
url = name or self.content.name
with self.term.loader('Refreshing page'):
self.content = SubmissionContent.from_url(
self.reddit, url, self.term.loader, order=order,
max_comment_cols=self.config['max_comment_cols'])
if not self.term.loader.exception:
self.nav = Navigator(self.content.get, page_index=-1)
@SubmissionController.register(Command('PROMPT'))
def prompt_subreddit(self):
"Open a prompt to navigate to a different subreddit"
name = self.term.prompt_input('Enter page: /')
if name is not None:
with self.term.loader('Loading page'):
content = SubredditContent.from_name(
self.reddit, name, self.term.loader)
if not self.term.loader.exception:
self.selected_subreddit = content
self.active = False
@SubmissionController.register(Command('SUBMISSION_OPEN_IN_BROWSER'))
def open_link(self):
"Open the selected item with the webbrowser"
data = self.get_selected_item()
url = data.get('permalink')
if url:
self.term.open_browser(url)
else:
self.term.flash()
@SubmissionController.register(Command('SUBMISSION_OPEN_IN_PAGER'))
def open_pager(self):
"Open the selected item with the system's pager"
data = self.get_selected_item()
if data['type'] == 'Submission':
text = '\n\n'.join((data['permalink'], data['text']))
self.term.open_pager(text)
elif data['type'] == 'Comment':
text = '\n\n'.join((data['permalink'], data['body']))
self.term.open_pager(text)
else:
self.term.flash()
@SubmissionController.register(Command('SUBMISSION_POST'))
@logged_in
def add_comment(self):
"""
Submit a reply to the selected item.
Selected item:
Submission - add a top level comment
Comment - add a comment reply
"""
data = self.get_selected_item()
if data['type'] == 'Submission':
body = data['text']
reply = data['object'].add_comment
elif data['type'] == 'Comment':
body = data['body']
reply = data['object'].reply
else:
self.term.flash()
return
# Construct the text that will be displayed in the editor file.
# The post body will be commented out and added for reference
lines = ['# |' + line for line in body.split('\n')]
content = '\n'.join(lines)
comment_info = docs.COMMENT_FILE.format(
author=data['author'],
type=data['type'].lower(),
content=content)
with self.term.open_editor(comment_info) as comment:
if not comment:
self.term.show_notification('Canceled')
return
with self.term.loader('Posting', delay=0):
reply(comment)
# Give reddit time to process the submission
time.sleep(2.0)
if self.term.loader.exception is None:
self.refresh_content()
else:
raise TemporaryFileError()
@SubmissionController.register(Command('DELETE'))
@logged_in
def delete_comment(self):
"Delete the selected comment"
if self.get_selected_item()['type'] == 'Comment':
self.delete_item()
else:
self.term.flash()
@SubmissionController.register(Command('SUBMISSION_OPEN_IN_URLVIEWER'))
def comment_urlview(self):
data = self.get_selected_item()
comment = data.get('body') or data.get('text') or data.get('url_full')
if comment:
self.term.open_urlview(comment)
else:
self.term.flash()
def _draw_item(self, win, data, inverted):
if data['type'] == 'MoreComments':
return self._draw_more_comments(win, data)
elif data['type'] == 'HiddenComment':
return self._draw_more_comments(win, data)
elif data['type'] == 'Comment':
return self._draw_comment(win, data, inverted)
else:
return self._draw_submission(win, data)
def _draw_comment(self, win, data, inverted):
n_rows, n_cols = win.getmaxyx()
n_cols -= 1
# Handle the case where the window is not large enough to fit the text.
valid_rows = range(0, n_rows)
offset = 0 if not inverted else -(data['n_rows'] - n_rows)
# If there isn't enough space to fit the comment body on the screen,
# replace the last line with a notification.
split_body = data['split_body']
if data['n_rows'] > n_rows:
# Only when there is a single comment on the page and not inverted
if not inverted and len(self._subwindows) == 0:
cutoff = data['n_rows'] - n_rows + 1
split_body = split_body[:-cutoff]
split_body.append('(Not enough space to display)')
row = offset
if row in valid_rows:
attr = curses.A_BOLD
attr |= (Color.BLUE if not data['is_author'] else Color.GREEN)
self.term.add_line(win, '{author} '.format(**data), row, 1, attr)
if data['flair']:
attr = curses.A_BOLD | Color.YELLOW
self.term.add_line(win, '{flair} '.format(**data), attr=attr)
text, attr = self.term.get_arrow(data['likes'])
self.term.add_line(win, text, attr=attr)
self.term.add_line(win, ' {score} {created} '.format(**data))
if data['gold']:
text, attr = self.term.guilded
self.term.add_line(win, text, attr=attr)
if data['stickied']:
text, attr = '[stickied]', Color.GREEN
self.term.add_line(win, text, attr=attr)
if data['saved']:
text, attr = '[saved]', Color.GREEN
self.term.add_line(win, text, attr=attr)
for row, text in enumerate(split_body, start=offset+1):
if row in valid_rows:
self.term.add_line(win, text, row, 1)
# Unfortunately vline() doesn't support custom color so we have to
# build it one segment at a time.
attr = Color.get_level(data['level'])
x = 0
for y in range(n_rows):
self.term.addch(win, y, x, self.term.vline, attr)
return attr | self.term.vline
def _draw_more_comments(self, win, data):
n_rows, n_cols = win.getmaxyx()
n_cols -= 1
self.term.add_line(win, '{body}'.format(**data), 0, 1)
self.term.add_line(
win, ' [{count}]'.format(**data), attr=curses.A_BOLD)
attr = Color.get_level(data['level'])
self.term.addch(win, 0, 0, self.term.vline, attr)
return attr | self.term.vline
def _draw_submission(self, win, data):
n_rows, n_cols = win.getmaxyx()
n_cols -= 3 # one for each side of the border + one for offset
for row, text in enumerate(data['split_title'], start=1):
self.term.add_line(win, text, row, 1, curses.A_BOLD)
row = len(data['split_title']) + 1
attr = curses.A_BOLD | Color.GREEN
self.term.add_line(win, '{author}'.format(**data), row, 1, attr)
attr = curses.A_BOLD | Color.YELLOW
if data['flair']:
self.term.add_line(win, ' {flair}'.format(**data), attr=attr)
self.term.add_line(win, ' {created} {subreddit}'.format(**data))
row = len(data['split_title']) + 2
attr = curses.A_UNDERLINE | Color.BLUE
self.term.add_line(win, '{url}'.format(**data), row, 1, attr)
offset = len(data['split_title']) + 3
# Cut off text if there is not enough room to display the whole post
split_text = data['split_text']
if data['n_rows'] > n_rows:
cutoff = data['n_rows'] - n_rows + 1
split_text = split_text[:-cutoff]
split_text.append('(Not enough space to display)')
for row, text in enumerate(split_text, start=offset):
self.term.add_line(win, text, row, 1)
row = len(data['split_title']) + len(split_text) + 3
self.term.add_line(win, '{score} '.format(**data), row, 1)
text, attr = self.term.get_arrow(data['likes'])
self.term.add_line(win, text, attr=attr)
self.term.add_line(win, ' {comments} '.format(**data))
if data['gold']:
text, attr = self.term.guilded
self.term.add_line(win, text, attr=attr)
if data['nsfw']:
text, attr = 'NSFW', (curses.A_BOLD | Color.RED)
self.term.add_line(win, text, attr=attr)
if data['saved']:
text, attr = '[saved]', Color.GREEN
self.term.add_line(win, text, attr=attr)
win.border()
| shaggytwodope/rtv | rtv/submission_page.py | Python | mit | 11,574 |
#include <zombye/core/game.hpp>
#include <zombye/gameplay/camera_follow_component.hpp>
#include <zombye/gameplay/game_states.hpp>
#include <zombye/gameplay/gameplay_system.hpp>
#include <zombye/gameplay/states/menu_state.hpp>
#include <zombye/gameplay/states/play_state.hpp>
#include <zombye/gameplay/state_component.hpp>
#include <zombye/scripting/scripting_system.hpp>
#include <zombye/utils/state_machine.hpp>
#include <zombye/utils/component_helper.hpp>
zombye::gameplay_system::gameplay_system(zombye::game *game) {
sm_ = std::unique_ptr<zombye::state_machine>(new zombye::state_machine(game));
init_game_states();
}
void zombye::gameplay_system::init_game_states() {
sm_->add<zombye::menu_state>(GAME_STATE_MENU);
sm_->add<zombye::play_state>(GAME_STATE_PLAY);
}
void zombye::gameplay_system::use(std::string name) {
sm_->use(name);
}
void zombye::gameplay_system::dispose_current() {
sm_->dispose_current();
}
void zombye::gameplay_system::update(float delta_time) {
sm_->update(delta_time);
for (auto& c : camera_follow_components_) {
c->update(delta_time);
}
for (auto& s : state_components_) {
s->update(delta_time);
}
}
void zombye::gameplay_system::register_component(camera_follow_component* component) {
camera_follow_components_.emplace_back(component);
}
void zombye::gameplay_system::unregister_component(camera_follow_component* component) {
remove(camera_follow_components_, component);
}
void zombye::gameplay_system::register_component(state_component* component) {
state_components_.emplace_back(component);
}
void zombye::gameplay_system::unregister_component(state_component* component) {
remove(state_components_, component);
}
| kasoki/project-zombye | src/source/zombye/gameplay/gameplay_system.cpp | C++ | mit | 1,741 |
/**
* @module popoff/overlay
*
* Because overlay-component is hopelessly out of date.
* This is modern rewrite.
*/
const Emitter = require('events').EventEmitter;
const inherits = require('inherits');
const extend = require('xtend/mutable');
module.exports = Overlay;
/**
* Initialize a new `Overlay`.
*
* @param {Object} options
* @api public
*/
function Overlay(options) {
if (!(this instanceof Overlay)) return new Overlay(options);
Emitter.call(this);
extend(this, options);
if (!this.container) {
this.container = document.body || document.documentElement;
}
//create overlay element
this.element = document.createElement('div');
this.element.classList.add('popoff-overlay');
if (this.closable) {
this.element.addEventListener('click', e => {
this.hide();
});
this.element.classList.add('popoff-closable');
}
}
inherits(Overlay, Emitter);
//close overlay by click
Overlay.prototype.closable = true;
/**
* Show the overlay.
*
* Emits "show" event.
*
* @return {Overlay}
* @api public
*/
Overlay.prototype.show = function () {
this.emit('show');
this.container.appendChild(this.element);
//class removed in a timeout to save animation
setTimeout( () => {
this.element.classList.add('popoff-visible');
this.emit('afterShow');
}, 10);
return this;
};
/**
* Hide the overlay.
*
* Emits "hide" event.
*
* @return {Overlay}
* @api public
*/
Overlay.prototype.hide = function () {
this.emit('hide');
this.element.classList.remove('popoff-visible');
this.element.addEventListener('transitionend', end);
this.element.addEventListener('webkitTransitionEnd', end);
this.element.addEventListener('otransitionend', end);
this.element.addEventListener('oTransitionEnd', end);
this.element.addEventListener('msTransitionEnd', end);
var to = setTimeout(end, 1000);
var that = this;
function end () {
that.element.removeEventListener('transitionend', end);
that.element.removeEventListener('webkitTransitionEnd', end);
that.element.removeEventListener('otransitionend', end);
that.element.removeEventListener('oTransitionEnd', end);
that.element.removeEventListener('msTransitionEnd', end);
clearInterval(to);
that.container.removeChild(that.element);
that.emit('afterHide');
}
return this;
};
| dfcreative/popoff | overlay.js | JavaScript | mit | 2,294 |
#!/usr/bin/env python
import os
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
# Test label reading from an MNI tag file
#
# The current directory must be writeable.
#
try:
fname = "mni-tagtest.tag"
channel = open(fname, "wb")
channel.close()
# create some random points in a sphere
#
sphere1 = vtk.vtkPointSource()
sphere1.SetNumberOfPoints(13)
xform = vtk.vtkTransform()
xform.RotateWXYZ(20, 1, 0, 0)
xformFilter = vtk.vtkTransformFilter()
xformFilter.SetTransform(xform)
xformFilter.SetInputConnection(sphere1.GetOutputPort())
labels = vtk.vtkStringArray()
labels.InsertNextValue("0")
labels.InsertNextValue("1")
labels.InsertNextValue("2")
labels.InsertNextValue("3")
labels.InsertNextValue("Halifax")
labels.InsertNextValue("Toronto")
labels.InsertNextValue("Vancouver")
labels.InsertNextValue("Larry")
labels.InsertNextValue("Bob")
labels.InsertNextValue("Jackie")
labels.InsertNextValue("10")
labels.InsertNextValue("11")
labels.InsertNextValue("12")
weights = vtk.vtkDoubleArray()
weights.InsertNextValue(1.0)
weights.InsertNextValue(1.1)
weights.InsertNextValue(1.2)
weights.InsertNextValue(1.3)
weights.InsertNextValue(1.4)
weights.InsertNextValue(1.5)
weights.InsertNextValue(1.6)
weights.InsertNextValue(1.7)
weights.InsertNextValue(1.8)
weights.InsertNextValue(1.9)
weights.InsertNextValue(0.9)
weights.InsertNextValue(0.8)
weights.InsertNextValue(0.7)
writer = vtk.vtkMNITagPointWriter()
writer.SetFileName(fname)
writer.SetInputConnection(sphere1.GetOutputPort())
writer.SetInputConnection(1, xformFilter.GetOutputPort())
writer.SetLabelText(labels)
writer.SetWeights(weights)
writer.SetComments("Volume 1: sphere points\nVolume 2: transformed points")
writer.Write()
reader = vtk.vtkMNITagPointReader()
reader.CanReadFile(fname)
reader.SetFileName(fname)
textProp = vtk.vtkTextProperty()
textProp.SetFontSize(12)
textProp.SetColor(1.0, 1.0, 0.5)
labelHier = vtk.vtkPointSetToLabelHierarchy()
labelHier.SetInputConnection(reader.GetOutputPort())
labelHier.SetTextProperty(textProp)
labelHier.SetLabelArrayName("LabelText")
labelHier.SetMaximumDepth(15)
labelHier.SetTargetLabelCount(12)
labelMapper = vtk.vtkLabelPlacementMapper()
labelMapper.SetInputConnection(labelHier.GetOutputPort())
labelMapper.UseDepthBufferOff()
labelMapper.SetShapeToRect()
labelMapper.SetStyleToOutline()
labelActor = vtk.vtkActor2D()
labelActor.SetMapper(labelMapper)
glyphSource = vtk.vtkSphereSource()
glyphSource.SetRadius(0.01)
glyph = vtk.vtkGlyph3D()
glyph.SetSourceConnection(glyphSource.GetOutputPort())
glyph.SetInputConnection(reader.GetOutputPort())
mapper = vtk.vtkDataSetMapper()
mapper.SetInputConnection(glyph.GetOutputPort())
actor = vtk.vtkActor()
actor.SetMapper(mapper)
# Create rendering stuff
ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.SetMultiSamples(0)
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
# Add the actors to the renderer, set the background and size
#
ren1.AddViewProp(actor)
ren1.AddViewProp(labelActor)
ren1.SetBackground(0, 0, 0)
renWin.SetSize(300, 300)
renWin.Render()
try:
os.remove(fname)
except OSError:
pass
# render the image
#
# iren.Start()
except IOError:
print "Unable to test the writer/reader."
| timkrentz/SunTracker | IMU/VTK-6.2.0/IO/MINC/Testing/Python/TestMNITagPoints.py | Python | mit | 3,826 |
// The MIT License (MIT)
//
// Copyright (c) 2015 Rasmus Mikkelsen
// https://github.com/rasmus/EventFlow
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using EventFlow.Core;
using EventFlow.Jobs;
using EventFlow.Logs;
using Hangfire;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace EventFlow.Hangfire.Integration
{
public class HangfireJobScheduler : IJobScheduler
{
private readonly IBackgroundJobClient _backgroundJobClient;
private readonly IJobDefinitionService _jobDefinitionService;
private readonly IJsonSerializer _jsonSerializer;
private readonly ILog _log;
public HangfireJobScheduler(
ILog log,
IJsonSerializer jsonSerializer,
IBackgroundJobClient backgroundJobClient,
IJobDefinitionService jobDefinitionService)
{
_log = log;
_jsonSerializer = jsonSerializer;
_backgroundJobClient = backgroundJobClient;
_jobDefinitionService = jobDefinitionService;
}
public Task<IJobId> ScheduleNowAsync(IJob job, CancellationToken cancellationToken)
{
return ScheduleAsync(job, (c, d, j) => _backgroundJobClient.Enqueue<IJobRunner>(r => r.Execute(d.Name, d.Version, j)));
}
public Task<IJobId> ScheduleAsync(IJob job, DateTimeOffset runAt, CancellationToken cancellationToken)
{
return ScheduleAsync(job, (c, d, j) => _backgroundJobClient.Schedule<IJobRunner>(r => r.Execute(d.Name, d.Version, j), runAt));
}
public Task<IJobId> ScheduleAsync(IJob job, TimeSpan delay, CancellationToken cancellationToken)
{
return ScheduleAsync(job, (c, d, j) => _backgroundJobClient.Schedule<IJobRunner>(r => r.Execute(d.Name, d.Version, j), delay));
}
private Task<IJobId> ScheduleAsync(IJob job, Func<IBackgroundJobClient, JobDefinition, string, string> schedule)
{
var jobDefinition = _jobDefinitionService.GetJobDefinition(job.GetType());
var json = _jsonSerializer.Serialize(job);
var id = schedule(_backgroundJobClient, jobDefinition, json);
_log.Verbose($"Scheduled job '{id}' in Hangfire");
return Task.FromResult<IJobId>(new HangfireJobId(id));
}
}
} | liemqv/EventFlow | Source/EventFlow.Hangfire/Integration/HangfireJobScheduler.cs | C# | mit | 3,367 |
if (isset($_POST['upload'])) {
$target = "../img".basename($_FILES['image']['name']);
$image = $_FILES['image']['name'];
$msg = "";
$sql = "UPDATE user SET avatar='$image' WHERE id='$id'";
mysqli_query($conn, $sql);
if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
$msg = "Uploaded file.";
} else {
$msg = "there was a problem uploading image";
}
}
if (isset($_POST['upload'])) {
$imageName = mysqli_real_escape_string($conn, $_FILES['image']['name']);
$imageData = mysqli_real_escape_string($conn,file_get_contents($_FILES['image']['tmp_name']));
$imageType = mysqli_real_escape_string($conn, $_FILES['image']['type']);
if (substr($imageType, 0, 5) == "image") {
$sql = "UPDATE user SET avatar='$imageData' WHERE id='$id'";
mysqli_query($conn, $sql);
echo "Image uploaded!";
} else {
echo "only images are allowed";
}
}
$sql = "SELECT * FROM user";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
$sqlImg = "SELECT * FROM profileimg WHERE userid='$id'";
$resultImg = mysqli_query($conn, $sqlImg);
while ($rowImg = mysqli_fetch_assoc($resultImg)) {
echo "<div class='user-container'>";
if ($rowImg['status'] == 0) {
echo "<img src='img/profile".$id.".jpg?'".mt_rand().">";
} else {
echo "<img src='img/profiledefault.jpg'>";
}
echo "<p>".$row['uid']."</p>";
echo "</div>";
}
}
} else {
echo "There are no users yet!";
}
// if ($userRow['image'] == "") {
echo "<form action='".upload($conn)."' method='POST' enctype='multipart/form-data'>
<input type='file' name='file'>
<button type='submit' name='submit'>UPLOAD</button>
</form>";
if (isset($_POST['upload'])) {
} else {
}
// }
// function upload($conn) {
// $id = $_SESSION['id'];
//
//
// if (isset($_POST['submit'])) {
// $file = $_FILES['file'];
// $fileName = $file['name'];
// $fileTmpName = $file['tmp_name'];
// $fileSize = $file['size'];
// $fileError = $file['error'];
// $fileType = $file['type'];
//
// $fileExt = explode('.', $fileName);
// $fileActualExt = strtolower(end($fileExt));
//
// $allowed = array('jpg', 'jpeg', 'png', 'pdf');
//
// if (in_array($fileActualExt, $allowed)) {
// if ($fileError === 0) {
// if ($fileSize < 1000000) {
// $fileNameNew = "profile".$id.".".$fileActualExt;
// $fileDestination = 'uploads/'.$fileNameNew;
// move_uploaded_file($fileTmpName, $fileDestination);
// $sql = "UPDATE profileimg SET status =0 WHERE userid='$id'";
// $result = mysqli_query($conn, $sql);
// header("Location: index.php?uploadsuccess");
// } else {
// echo "Your file is too big!";
// }
// } else {
// echo "There was an error uploading your file!";
// }
// } else {
// echo "You cannot upload files of this type!";
// }
// }
// }
| vicols92/linkify | resources/includes/TRASH/KANSKESPARA.php | PHP | mit | 3,055 |
module Twitter
class JSONStream
protected
def reconnect_after timeout
@reconnect_callback.call(timeout, @reconnect_retries) if @reconnect_callback
if timeout == 0
reconnect @options[:host], @options[:port]
start_tls if @options[:ssl]
else
EventMachine.add_timer(timeout) do
reconnect @options[:host], @options[:port]
start_tls if @options[:ssl]
end
end
end
end
end
module TwitterOAuth
class Client
private
def consumer
@consumer ||= OAuth::Consumer.new(
@consumer_key,
@consumer_secret,
{ :site => 'https://api.twitter.com', :proxy => @proxy }
)
end
end
end
class String
def c(*codes)
return self if Earthquake.config[:lolize]
codes = codes.flatten.map { |code|
case code
when String, Symbol
Earthquake.config[:color][code.to_sym] rescue nil
else
code
end
}.compact.unshift(0)
"\e[#{codes.join(';')}m#{self}\e[0m"
end
def coloring(pattern, color = nil, &block)
return self if Earthquake.config[:lolize]
self.gsub(pattern) do |i|
applied_colors = $`.scan(/\e\[[\d;]+m/)
c = color || block.call(i)
"#{i.c(c)}#{applied_colors.join}"
end
end
t = {
?& => "&",
?< => "<",
?> => ">",
?' => "'",
?" => """,
}
define_method(:u) do
gsub(/(#{Regexp.union(t.values)})/o, t.invert)
end
define_method(:e) do
gsub(/[#{t.keys.join}]/o, t)
end
end
| neurodrone/earthquake | lib/earthquake/ext.rb | Ruby | mit | 1,538 |
namespace Jello.Nodes
{
public abstract class TerminalNode<T> : Node<T> where T : class
{
public override INode GetSingleChild()
{
return null;
}
}
} | jordanwallwork/jello | src/Jello/Nodes/TerminalNode.cs | C# | mit | 197 |
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2011-2012 Litecoin Developers
// Copyright (c) 2013 Fastcoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "irc.h"
#include "net.h"
#include "strlcpy.h"
#include "base58.h"
using namespace std;
using namespace boost;
int nGotIRCAddresses = 0;
void ThreadIRCSeed2(void* parg);
#pragma pack(push, 1)
struct ircaddr
{
struct in_addr ip;
short port;
};
#pragma pack(pop)
string EncodeAddress(const CService& addr)
{
struct ircaddr tmp;
if (addr.GetInAddr(&tmp.ip))
{
tmp.port = htons(addr.GetPort());
vector<unsigned char> vch(UBEGIN(tmp), UEND(tmp));
return string("u") + EncodeBase58Check(vch);
}
return "";
}
bool DecodeAddress(string str, CService& addr)
{
vector<unsigned char> vch;
if (!DecodeBase58Check(str.substr(1), vch))
return false;
struct ircaddr tmp;
if (vch.size() != sizeof(tmp))
return false;
memcpy(&tmp, &vch[0], sizeof(tmp));
addr = CService(tmp.ip, ntohs(tmp.port));
return true;
}
static bool Send(SOCKET hSocket, const char* pszSend)
{
if (strstr(pszSend, "PONG") != pszSend)
printf("IRC SENDING: %s\n", pszSend);
const char* psz = pszSend;
const char* pszEnd = psz + strlen(psz);
while (psz < pszEnd)
{
int ret = send(hSocket, psz, pszEnd - psz, MSG_NOSIGNAL);
if (ret < 0)
return false;
psz += ret;
}
return true;
}
bool RecvLineIRC(SOCKET hSocket, string& strLine)
{
loop
{
bool fRet = RecvLine(hSocket, strLine);
if (fRet)
{
if (fShutdown)
return false;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() >= 1 && vWords[0] == "PING")
{
strLine[1] = 'O';
strLine += '\r';
Send(hSocket, strLine.c_str());
continue;
}
}
return fRet;
}
}
int RecvUntil(SOCKET hSocket, const char* psz1, const char* psz2=NULL, const char* psz3=NULL, const char* psz4=NULL)
{
loop
{
string strLine;
strLine.reserve(10000);
if (!RecvLineIRC(hSocket, strLine))
return 0;
printf("IRC %s\n", strLine.c_str());
if (psz1 && strLine.find(psz1) != string::npos)
return 1;
if (psz2 && strLine.find(psz2) != string::npos)
return 2;
if (psz3 && strLine.find(psz3) != string::npos)
return 3;
if (psz4 && strLine.find(psz4) != string::npos)
return 4;
}
}
bool Wait(int nSeconds)
{
if (fShutdown)
return false;
printf("IRC waiting %d seconds to reconnect\n", nSeconds);
for (int i = 0; i < nSeconds; i++)
{
if (fShutdown)
return false;
Sleep(1000);
}
return true;
}
bool RecvCodeLine(SOCKET hSocket, const char* psz1, string& strRet)
{
strRet.clear();
loop
{
string strLine;
if (!RecvLineIRC(hSocket, strLine))
return false;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() < 2)
continue;
if (vWords[1] == psz1)
{
printf("IRC %s\n", strLine.c_str());
strRet = strLine;
return true;
}
}
}
bool GetIPFromIRC(SOCKET hSocket, string strMyName, CNetAddr& ipRet)
{
Send(hSocket, strprintf("USERHOST %s\r", strMyName.c_str()).c_str());
string strLine;
if (!RecvCodeLine(hSocket, "302", strLine))
return false;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() < 4)
return false;
string str = vWords[3];
if (str.rfind("@") == string::npos)
return false;
string strHost = str.substr(str.rfind("@")+1);
// Hybrid IRC used by lfnet always returns IP when you userhost yourself,
// but in case another IRC is ever used this should work.
printf("GetIPFromIRC() got userhost %s\n", strHost.c_str());
CNetAddr addr(strHost, true);
if (!addr.IsValid())
return false;
ipRet = addr;
return true;
}
void ThreadIRCSeed(void* parg)
{
IMPLEMENT_RANDOMIZE_STACK(ThreadIRCSeed(parg));
// Make this thread recognisable as the IRC seeding thread
RenameThread("bitcoin-ircseed");
try
{
ThreadIRCSeed2(parg);
}
catch (std::exception& e) {
PrintExceptionContinue(&e, "ThreadIRCSeed()");
} catch (...) {
PrintExceptionContinue(NULL, "ThreadIRCSeed()");
}
printf("ThreadIRCSeed exited\n");
}
void ThreadIRCSeed2(void* parg)
{
/* Dont advertise on IRC if we don't allow incoming connections */
if (mapArgs.count("-connect") || fNoListen)
return;
if (!GetBoolArg("-irc", false))
return;
printf("ThreadIRCSeed started\n");
int nErrorWait = 10;
int nRetryWait = 10;
while (!fShutdown)
{
CService addrConnect("92.243.23.21", 6667); // irc.lfnet.org
CService addrIRC("irc.lfnet.org", 6667, true);
if (addrIRC.IsValid())
addrConnect = addrIRC;
SOCKET hSocket;
if (!ConnectSocket(addrConnect, hSocket))
{
printf("IRC connect failed\n");
nErrorWait = nErrorWait * 11 / 10;
if (Wait(nErrorWait += 60))
continue;
else
return;
}
if (!RecvUntil(hSocket, "Found your hostname", "using your IP address instead", "Couldn't look up your hostname", "ignoring hostname"))
{
closesocket(hSocket);
hSocket = INVALID_SOCKET;
nErrorWait = nErrorWait * 11 / 10;
if (Wait(nErrorWait += 60))
continue;
else
return;
}
CNetAddr addrIPv4("1.2.3.4"); // arbitrary IPv4 address to make GetLocal prefer IPv4 addresses
CService addrLocal;
string strMyName;
if (GetLocal(addrLocal, &addrIPv4))
strMyName = EncodeAddress(GetLocalAddress(&addrConnect));
if (strMyName == "")
strMyName = strprintf("x%u", GetRand(1000000000));
Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str());
Send(hSocket, strprintf("USER %s 8 * : %s\r", strMyName.c_str(), strMyName.c_str()).c_str());
int nRet = RecvUntil(hSocket, " 004 ", " 433 ");
if (nRet != 1)
{
closesocket(hSocket);
hSocket = INVALID_SOCKET;
if (nRet == 2)
{
printf("IRC name already in use\n");
Wait(10);
continue;
}
nErrorWait = nErrorWait * 11 / 10;
if (Wait(nErrorWait += 60))
continue;
else
return;
}
Sleep(500);
// Get our external IP from the IRC server and re-nick before joining the channel
CNetAddr addrFromIRC;
if (GetIPFromIRC(hSocket, strMyName, addrFromIRC))
{
printf("GetIPFromIRC() returned %s\n", addrFromIRC.ToString().c_str());
if (addrFromIRC.IsRoutable())
{
// IRC lets you to re-nick
AddLocal(addrFromIRC, LOCAL_IRC);
strMyName = EncodeAddress(GetLocalAddress(&addrConnect));
Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str());
}
}
if (fTestNet) {
Send(hSocket, "JOIN #fastcoinTEST3\r");
Send(hSocket, "WHO #fastcoinTEST3\r");
} else {
// randomly join #fastcoin00-#fastcoin99
int channel_number = GetRandInt(100);
channel_number = 0; // Fastcoin: for now, just use one channel
Send(hSocket, strprintf("JOIN #fastcoin%02d\r", channel_number).c_str());
Send(hSocket, strprintf("WHO #fastcoin%02d\r", channel_number).c_str());
}
int64 nStart = GetTime();
string strLine;
strLine.reserve(10000);
while (!fShutdown && RecvLineIRC(hSocket, strLine))
{
if (strLine.empty() || strLine.size() > 900 || strLine[0] != ':')
continue;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() < 2)
continue;
char pszName[10000];
pszName[0] = '\0';
if (vWords[1] == "352" && vWords.size() >= 8)
{
// index 7 is limited to 16 characters
// could get full length name at index 10, but would be different from join messages
strlcpy(pszName, vWords[7].c_str(), sizeof(pszName));
printf("IRC got who\n");
}
if (vWords[1] == "JOIN" && vWords[0].size() > 1)
{
// :username!username@50000007.F000000B.90000002.IP JOIN :#channelname
strlcpy(pszName, vWords[0].c_str() + 1, sizeof(pszName));
if (strchr(pszName, '!'))
*strchr(pszName, '!') = '\0';
printf("IRC got join\n");
}
if (pszName[0] == 'u')
{
CAddress addr;
if (DecodeAddress(pszName, addr))
{
addr.nTime = GetAdjustedTime();
if (addrman.Add(addr, addrConnect, 51 * 60))
printf("IRC got new address: %s\n", addr.ToString().c_str());
nGotIRCAddresses++;
}
else
{
printf("IRC decode failed\n");
}
}
}
closesocket(hSocket);
hSocket = INVALID_SOCKET;
if (GetTime() - nStart > 20 * 60)
{
nErrorWait /= 3;
nRetryWait /= 3;
}
nRetryWait = nRetryWait * 11 / 10;
if (!Wait(nRetryWait += 60))
return;
}
}
#ifdef TEST
int main(int argc, char *argv[])
{
WSADATA wsadata;
if (WSAStartup(MAKEWORD(2,2), &wsadata) != NO_ERROR)
{
printf("Error at WSAStartup()\n");
return false;
}
ThreadIRCSeed(NULL);
WSACleanup();
return 0;
}
#endif
| RandCoin/randcoin | src/irc.cpp | C++ | mit | 10,568 |
package fyskam.fyskamssngbok;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
/**
* Fragment used for managing interactions for and presentation of a navigation drawer.
* See the <a href="https://developer.android.com/design/patterns/navigation-drawer.html#Interaction">
* design guidelines</a> for a complete explanation of the behaviors implemented here.
*/
public class NavigationDrawerFragment extends Fragment {
/**
* Remember the position of the selected item.
*/
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
/**
* Per the design guidelines, you should show the drawer on launch until the user manually
* expands it. This shared preference tracks this.
*/
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
/**
* A pointer to the current callbacks instance (the Activity).
*/
private NavigationDrawerCallbacks mCallbacks;
/**
* Helper component that ties the action bar to the navigation drawer.
*/
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
public NavigationDrawerFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Read in the flag indicating whether or not the user has demonstrated awareness of the
// drawer. See PREF_USER_LEARNED_DRAWER for details.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
// Select either the default item (0) or the last selected item.
selectItem(mCurrentSelectedPosition);
}
@Override
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Indicate that this fragment would like to influence the set of actions in the action bar.
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mDrawerListView = (ListView) inflater.inflate(
R.layout.fragment_navigation_drawer, container, false);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
new String[]{
getString(R.string.title_section1),
getString(R.string.title_section2),
getString(R.string.title_section3),
}));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* @param fragmentId The android:id of this fragment in its activity's layout.
* @param drawerLayout The DrawerLayout containing this fragment's UI.
*/
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
R.string.navigation_drawer_close /* "close drawer" description for accessibility */
) {
@Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
// The user manually opened the drawer; store this flag to prevent auto-showing
// the navigation drawer automatically in the future.
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
@Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
@Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If the drawer is open, show the global app actions in the action bar. See also
// showGlobalContextActionBar, which controls the top-left area of the action bar.
if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.global, menu);
showGlobalContextActionBar();
}
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
if (item.getItemId() == R.id.action_example) {
Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Per the navigation drawer design guidelines, updates the action bar to show the global app
* 'context', rather than just what's in the current screen.
*/
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setTitle(R.string.app_name);
}
private ActionBar getActionBar() {
return getActivity().getActionBar();
}
/**
* Callbacks interface that all activities using this fragment must implement.
*/
public static interface NavigationDrawerCallbacks {
/**
* Called when an item in the navigation drawer is selected.
*/
void onNavigationDrawerItemSelected(int position);
}
}
| fyskam/FysKams-sangbok | FysKamsSangbok/app/src/main/java/fyskam/fyskamssngbok/NavigationDrawerFragment.java | Java | mit | 10,600 |
import uuid
from uqbar.objects import new
from supriya.patterns.Pattern import Pattern
class EventPattern(Pattern):
### CLASS VARIABLES ###
__slots__ = ()
### SPECIAL METHODS ###
def _coerce_iterator_output(self, expr, state=None):
import supriya.patterns
if not isinstance(expr, supriya.patterns.Event):
expr = supriya.patterns.NoteEvent(**expr)
if expr.get("uuid") is None:
expr = new(expr, uuid=uuid.uuid4())
return expr
### PUBLIC METHODS ###
def play(self, clock=None, server=None):
import supriya.patterns
import supriya.realtime
event_player = supriya.patterns.RealtimeEventPlayer(
self, clock=clock, server=server or supriya.realtime.Server.default()
)
event_player.start()
return event_player
def with_bus(self, calculation_rate="audio", channel_count=None, release_time=0.25):
import supriya.patterns
return supriya.patterns.Pbus(
self,
calculation_rate=calculation_rate,
channel_count=channel_count,
release_time=release_time,
)
def with_effect(self, synthdef, release_time=0.25, **settings):
import supriya.patterns
return supriya.patterns.Pfx(
self, synthdef=synthdef, release_time=release_time, **settings
)
def with_group(self, release_time=0.25):
import supriya.patterns
return supriya.patterns.Pgroup(self, release_time=release_time)
| Pulgama/supriya | supriya/patterns/EventPattern.py | Python | mit | 1,545 |
/*
Copyright (c) 2011 Andrei Mackenzie
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.
*/
// Compute the edit distance between the two given strings
exports.getEditDistance = function(a, b){
if(a.length == 0) return b.length;
if(b.length == 0) return a.length;
var matrix = [];
// increment along the first column of each row
var i;
for(i = 0; i <= b.length; i++){
matrix[i] = [i];
}
// increment each column in the first row
var j;
for(j = 0; j <= a.length; j++){
matrix[0][j] = j;
}
// Fill in the rest of the matrix
for(i = 1; i <= b.length; i++){
for(j = 1; j <= a.length; j++){
if(b.charAt(i-1) == a.charAt(j-1)){
matrix[i][j] = matrix[i-1][j-1];
} else {
matrix[i][j] = Math.min(matrix[i-1][j-1] + 1, // substitution
Math.min(matrix[i][j-1] + 1, // insertion
matrix[i-1][j] + 1)); // deletion
}
}
}
return matrix[b.length][a.length];
};
| crazyfacka/text2meo | data/lib/levenshtein.js | JavaScript | mit | 1,980 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Pervasive_Heart_Monitor
{
class Program
{
static bool checknum(string s)
{
return (s.Contains("1") || s.Contains("2") || s.Contains("3") || s.Contains("4") || s.Contains("5") || s.Contains("6") || s.Contains("7") || s.Contains("8") || s.Contains("9") || s.Contains("."));
}
static void Main(string[] args)
{
string s = Console.ReadLine();
while (!string.IsNullOrEmpty(s))
{
float total=0;
int n=0;
string name = "";
string[] ssplit = s.Split();
for(int i = 0; i < ssplit.Length; i++)
{
if (!checknum(ssplit[i])) { name += (ssplit[i] + " "); }
else
{
total += float.Parse(ssplit[i]);
n++;
}
}
Console.WriteLine("{0:F6} {1}", (float)(total / n), name);
s = Console.ReadLine();
}
}
}
}
| SurgicalSteel/Competitive-Programming | Kattis-Solutions/Pervasive Heart Monitor.cs | C# | mit | 1,202 |
//! \file ArcSG.cs
//! \date 2018 Feb 01
//! \brief 'fSGX' multi-frame image container.
//
// Copyright (C) 2018 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
namespace GameRes.Formats.Ivory
{
[Export(typeof(ArchiveFormat))]
public class SgOpener : ArchiveFormat
{
public override string Tag { get { return "SG/cOBJ"; } }
public override string Description { get { return "Ivory multi-frame image"; } }
public override uint Signature { get { return 0x58475366; } } // 'fSGX'
public override bool IsHierarchic { get { return false; } }
public override bool CanWrite { get { return false; } }
public override ArcFile TryOpen (ArcView file)
{
long offset = 8;
var base_name = Path.GetFileNameWithoutExtension (file.Name);
var dir = new List<Entry>();
while (offset < file.MaxOffset && file.View.AsciiEqual (offset, "cOBJ"))
{
uint obj_size = file.View.ReadUInt32 (offset+4);
if (0 == obj_size)
break;
if (file.View.AsciiEqual (offset+0x10, "fSG "))
{
var entry = new Entry {
Name = string.Format ("{0}#{1}", base_name, dir.Count),
Type = "image",
Offset = offset+0x10,
Size = file.View.ReadUInt32 (offset+0x14),
};
dir.Add (entry);
}
offset += obj_size;
}
if (0 == dir.Count)
return null;
return new ArcFile (file, this, dir);
}
}
}
| morkt/GARbro | ArcFormats/Ivory/ArcSG.cs | C# | mit | 2,865 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace track_downloader
{
class Program
{
static void Main(string[] args)
{
string[] blacklisted = Console.ReadLine().Split();
List<string> filenames = ReadFilenames();
filenames = filenames
.Where(a => ContainsBlackListed(a, blacklisted))
.OrderBy(a => a)
.ToList();
Console.WriteLine(string.Join("\r\n", filenames));
}
private static bool ContainsBlackListed(string a, string[] blacklisted)
{
for (int i = 0; i < blacklisted.Length; i++)
{
if (a.Contains(blacklisted[i]))
{
return false;
}
}
return true;
}
private static List<string> ReadFilenames()
{
List<string> output = new List<string>();
string filename = Console.ReadLine();
while (filename != "end")
{
output.Add(filename);
filename = Console.ReadLine();
}
return output;
}
}
} | Avarea/Programming-Fundamentals | Lists/02TrackDownloader/Program.cs | C# | mit | 1,263 |
import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import GroupPage from './GroupPage.js';
import GroupNotFoundPage from './GroupNotFoundPage.js';
const Group = ({ isValid, groupId }) => (isValid ? <GroupPage groupId={groupId} /> : <GroupNotFoundPage groupId={groupId} />);
Group.propTypes = {
groupId: PropTypes.string,
isValid: PropTypes.bool.isRequired
};
export default connect(state => ({
groupId: state.router.params.groupId,
isValid: !!state.groups.data[state.router.params.groupId]
}))(Group);
| logger-app/logger-app | src/containers/Group/Group.js | JavaScript | mit | 545 |