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 /** * This file is part of the phpkata project. * * (c) Yannick Voyer (http://github.com/yvoyer) */ namespace Star\Kata\Infrastructure\InMemory; use Star\Component\Collection\TypedCollection; use Star\Kata\Domain\Kata; use Star\Kata\Domain\KataRepository; /** * Class KataCollection * * @author Yannick Voyer (http://github.com/yvoyer) * * @package Star\Kata\Infrastructure\InMemory */ class KataCollection implements KataRepository { /** * @var TypedCollection|Kata[] */ private $katas; /** * @param Kata[] $katas */ public function __construct(array $katas = array()) { $this->katas = new TypedCollection('Star\Kata\Domain\Kata'); $this->addKatas($katas); } /** * @param string $name * * @return Kata */ public function findOneByName($name) { return $this->katas[$name]; } /** * @param Kata[] $elements */ private function addKatas(array $elements) { foreach ($elements as $element) { $this->addKata($element); } } /** * @param Kata $kata */ public function addKata(Kata $kata) { $this->katas[$kata->name()] = $kata; } /** * Return the number of elements. * * @return int */ public function count() { return count($this->katas); } /** * @return Kata[] */ public function findAllKatas() { return $this->katas->toArray(); } }
yvoyer/php-kata
lib/Infrastructure/InMemory/KataCollection.php
PHP
mit
1,522
var assert = require("chai").assert; var Init = require("truffle-init"); var Migrate = require("truffle-migrate"); var Contracts = require("../lib/contracts"); var Networks = require("../lib/networks"); var path = require("path"); var fs = require("fs"); var TestRPC = require("ethereumjs-testrpc"); var Resolver = require("truffle-resolver"); var Artifactor = require("truffle-artifactor"); var Web3 = require("web3"); describe("migrate", function() { var config; var accounts; var network_id_one; var network_id_two; var from_addresses = []; before("Create a sandbox", function(done) { this.timeout(10000); Init.sandbox(function(err, result) { if (err) return done(err); config = result; config.resolver = new Resolver(config); config.artifactor = new Artifactor(config.contracts_build_directory); config.networks = {}; done(); }); }); function createProviderAndSetNetworkConfig(network, callback) { var provider = TestRPC.provider({seed: network}); var web3 = new Web3(provider); web3.eth.getAccounts(function(err, accs) { if (err) return callback(err); web3.version.getNetwork(function(err, network_id) { if (err) return callback(err); config.networks[network] = { provider: provider, network_id: network_id + "", from: accs[0] }; callback(); }); }); }; before("Get accounts and network id of network one", function(done) { createProviderAndSetNetworkConfig("primary", done); }); before("Get accounts and network id of network one", function(done) { createProviderAndSetNetworkConfig("secondary", done); }); it('profiles a new project as not having any contracts deployed', function(done) { Networks.deployed(config, function(err, networks) { if (err) return done(err); assert.equal(Object.keys(networks).length, 2, "Should have results for two networks from profiler"); assert.equal(Object.keys(networks["primary"]), 0, "Primary network should not have been deployed to"); assert.equal(Object.keys(networks["secondary"]), 0, "Secondary network should not have been deployed to"); done(); }) }); it('links libraries in initial project, and runs all migrations', function(done) { this.timeout(10000); config.network = "primary"; Contracts.compile(config.with({ all: false, quiet: true }), function(err, contracts) { if (err) return done(err); Migrate.run(config.with({ quiet: true }), function(err) { if (err) return done(err); Networks.deployed(config, function(err, networks) { if (err) return done(err); assert.equal(Object.keys(networks).length, 2, "Should have results for two networks from profiler"); assert.equal(Object.keys(networks["primary"]).length, 3, "Primary network should have three contracts deployed"); assert.isNotNull(networks["primary"]["MetaCoin"], "MetaCoin contract should have an address"); assert.isNotNull(networks["primary"]["ConvertLib"], "ConvertLib library should have an address"); assert.isNotNull(networks["primary"]["Migrations"], "Migrations contract should have an address"); assert.equal(Object.keys(networks["secondary"]), 0, "Secondary network should not have been deployed to"); done(); }); }); }); }); it('should migrate secondary network without altering primary network', function(done) { this.timeout(10000); config.network = "secondary"; var currentAddresses = {}; Networks.deployed(config, function(err, networks) { if (err) return done(err); ["MetaCoin", "ConvertLib", "Migrations"].forEach(function(contract_name) { currentAddresses[contract_name] = networks["primary"][contract_name]; }); Migrate.run(config.with({ quiet: true }), function(err, contracts) { if (err) return done(err); Networks.deployed(config, function(err, networks) { if (err) return done(err); assert.equal(Object.keys(networks).length, 2, "Should have results for two networks from profiler"); assert.equal(Object.keys(networks["primary"]).length, 3, "Primary network should have three contracts deployed"); assert.equal(networks["primary"]["MetaCoin"], currentAddresses["MetaCoin"], "MetaCoin contract updated on primary network"); assert.equal(networks["primary"]["ConvertLib"], currentAddresses["ConvertLib"], "ConvertLib library updated on primary network"); assert.equal(networks["primary"]["Migrations"], currentAddresses["Migrations"], "Migrations contract updated on primary network"); assert.equal(Object.keys(networks["secondary"]).length, 3, "Secondary network should have three contracts deployed"); assert.isNotNull(networks["secondary"]["MetaCoin"], "MetaCoin contract should have an address on secondary network"); assert.isNotNull(networks["secondary"]["ConvertLib"], "ConvertLib library should have an address on secondary network"); assert.isNotNull(networks["secondary"]["Migrations"], "Migrations contract should have an address on secondary network"); Object.keys(networks["primary"]).forEach(function(contract_name) { assert.notEqual(networks["secondary"][contract_name], networks["primary"][contract_name], "Contract " + contract_name + " has the same address on both networks") }); done(); }); }); }); }); it("should ignore files that don't start with a number", function(done) { fs.writeFileSync(path.join(config.migrations_directory, "~2_deploy_contracts.js"), "module.exports = function() {};", "utf8"); Migrate.assemble(config, function(err, migrations) { if (err) return done(err); assert.equal(migrations.length, 2, "~2_deploy_contracts.js should have been ignored!"); done(); }); }); it("should ignore non-js extensions", function(done) { fs.writeFileSync(path.join(config.migrations_directory, "2_deploy_contracts.js~"), "module.exports = function() {};", "utf8"); Migrate.assemble(config, function(err, migrations) { if (err) return done(err); assert.equal(migrations.length, 2, "2_deploy_contracts.js~ should have been ignored!"); done(); }); }); });
prashantpawar/truffle
test/migrate.js
JavaScript
mit
6,446
var LiveStream = require('../') var SubLevel = require('level-sublevel') var db = SubLevel(require('level-test')()('test-level-live-stream')) var assert = require('assert') var i = 10 var j = 10 var k = 10 LiveStream(db, {tail: true}).on('data', function (data) { console.log(data) if(data.type === 'put') assert.equal(data.key, j--) }) LiveStream(db, {old: false}).on('data', function (data) { if(data.type === 'put') assert.equal(data.key, k--) }) var a = [] var int = setInterval(function () { var key = i + '' if(Math.random() < 0.2 && a.length) { var r = ~~(Math.random()*a.length) key = a[r] a.slice(r, 1) db.del(key, function (err) { assert(err == undefined) }) } else { a.push(key) db.put(key, new Date(), function(err) { assert(err == undefined) }) if(--i) return clearInterval(int) } }, 100)
dominictarr/level-live-stream
test/index.js
JavaScript
mit
886
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { fetchIP } from '../../actions/fetchIP'; import { Snackbar } from 'react-toolbox'; import theme from './Snackbar.css'; class SnackbarComponent extends Component { constructor(props) { super(props); this.state = { active: false, message: '' }; this.handleSnackbarClick = this.handleSnackbarClick.bind(this); this.handleSnackbarTimeout = this.handleSnackbarTimeout.bind(this); } handleSnackbarClick = () => { this.setState({active: false}); }; handleSnackbarTimeout = () => { if (this._isMounted) { this.setState({active: false}); } this.props.fetchIP(); }; componentWillReceiveProps(props) { this.setState({ active: props.error, message: props.message }); } componentDidMount() { this._isMounted = true; } componentWillUnmount() { this._isMounted = false; } render() { return ( <section> <Snackbar theme={theme} action="Hide" active={this.props.weather.error} label={this.props.weather.message} timeout={1500} onClick={this.handleSnackbarClick} onTimeout={this.handleSnackbarTimeout} type="warning" /> </section> ); } } function mapDispatchToProps(dispatch) { return bindActionCreators({ fetchIP }, dispatch); } function mapStateToProps({ weather }) { return { weather }; } export default connect(mapStateToProps, mapDispatchToProps)(SnackbarComponent);
ericvandevprod/redux-d3
src/app/components/Snackbar/Snackbar.js
JavaScript
mit
1,668
// @flow import React, { type Node, Component } from 'react'; import { Image, View, ScrollView, StyleSheet, TouchableHighlight, TouchableOpacity, Dimensions, } from 'react-native'; const reactNativePackage = require('react-native/package.json'); const splitVersion = reactNativePackage.version.split('.'); const majorVersion = +splitVersion[0]; const minorVersion = +splitVersion[1]; type Slide = { index: number, style?: any, width?: number, item?: any, }; type PropsType = { images: Array<number | string>, style?: any, loop?: boolean, loopBothSides?: boolean, autoPlayWithInterval?: number, position?: number, onPositionChanged?: number => void, onPress?: Object => void, customButtons?: (number, (number, animated?: boolean) => void) => Node, customSlide?: Slide => Node, imagesWidth: number }; type StateType = { position: number, width: number, interval: any, onPositionChangedCalled: boolean, }; class ImageSlider extends Component<PropsType, StateType> { state = { position: 0, width: Dimensions.get('window').width, onPositionChangedCalled: false, interval: null, }; _ref = null; _panResponder = {}; _onRef = (ref: any) => { this._ref = ref; if (ref && this.state.position !== this._getPosition()) { this._move(this._getPosition()); } }; // In iOS you can pop view by swiping left, with active ScrollView // you can't do that. This View on top of ScrollView enables call of // pop function. _popHelperView = () => !this.props.loopBothSides && this._getPosition() === 0 && ( <View style={{ position: 'absolute', width: 50, height: '100%' }} /> ); _move = (index: number, animated: boolean = true, autoCalled: boolean = true) => { if (!this.autoPlayFlag && autoCalled) { return; } const isUpdating = index !== this._getPosition(); const x = (this.props.imagesWidth ? this.props.imagesWidth : Dimensions.get("window").width) * index; this._ref && this._ref.scrollTo({ y: 0, x, animated }); this.setState({ position: index }); if ( isUpdating && this.props.onPositionChanged && index < this.props.images.length && index > -1 ) { this.props.onPositionChanged(index); this.setState({ onPositionChangedCalled: true }); } this._setInterval(); }; _getPosition() { if (typeof this.props.position === 'number') { return this.props.position % this.props.images.length; } return this.state.position % this.props.images.length; } componentDidUpdate(prevProps: Object) { const { position, autoPlayFlag } = this.props; this.autoPlayFlag = autoPlayFlag; if (position && prevProps.position !== position) { this._move(position); } } _clearInterval = () => this.state.interval && clearInterval(this.state.interval); _setInterval = () => { this._clearInterval(); const { autoPlayWithInterval, images, loop, loopBothSides } = this.props; if (autoPlayWithInterval) { this.setState({ interval: setInterval( () => this._move( !(loop || loopBothSides) && this.state.position === images.length - 1 ? 0 : this.state.position + 1, ), autoPlayWithInterval, ), }); } }; _handleScroll = (event: Object) => { const { position, width } = this.state; const { loop, loopBothSides, images, onPositionChanged } = this.props; const { x } = event.nativeEvent.contentOffset; if ( (loop || loopBothSides) && x.toFixed() >= +(width * images.length).toFixed() ) { return this._move(0, false); } else if (loopBothSides && x.toFixed() <= +(-width).toFixed()) { return this._move(images.length - 1, false); } let newPosition = 0; if (position !== -1 && position !== images.length) { newPosition = Math.round(event.nativeEvent.contentOffset.x / width); this.setState({ position: newPosition }); } if ( onPositionChanged && !this.state.onPositionChangedCalled && newPosition < images.length && newPosition > -1 ) { onPositionChanged(newPosition); } else { this.setState({ onPositionChangedCalled: false }); } this._setInterval(); }; componentDidMount() { this._setInterval(); } componentWillUnmount() { this._clearInterval(); } _onLayout = () => { this.setState({ width: Dimensions.get('window').width }); this._move(this.state.position, false); }; _renderImage = (image: any, index: number) => { const { width } = Dimensions.get('window'); const { onPress, customSlide } = this.props; const offset = { marginLeft: index === -1 ? -width : 0 }; const imageStyle = [styles.image, { width }, offset]; if (customSlide) { return customSlide({ item: image, style: imageStyle, index, width }); } const imageObject = typeof image === 'string' ? { uri: image } : image; const imageComponent = ( <Image key={index} source={imageObject} style={[imageStyle]} /> ); if (onPress) { return ( <TouchableOpacity key={index} style={[imageStyle, offset]} onPress={() => onPress && onPress({ image, index })} delayPressIn={200} > {imageComponent} </TouchableOpacity> ); } return imageComponent; }; // We make shure, that, when loop is active, // fake images at the begin and at the end of ScrollView // do not scroll. _scrollEnabled = (position: number) => position !== -1 && position !== this.props.images.length; moveNext = () => { const next = (this.state.position + 1) % this.props.images.length; this._move(next, true, false); } movePrev = () => { const prev = (this.state.position + this.props.images.length - 1) % this.props.images.length; this._move(prev, true, false); } render() { const { onPress, customButtons, style, loop, images, loopBothSides, } = this.props; const position = this._getPosition(); const scrollEnabled = this._scrollEnabled(position); return ( <View style={[styles.container, style]} onLayout={this._onLayout}> <ScrollView onLayout={this._onLayout} ref={ref => this._onRef(ref)} onMomentumScrollEnd={this._handleScroll} scrollEventThrottle={16} pagingEnabled={true} bounces={loopBothSides} contentInset={loopBothSides ? { left: this.state.width } : {}} horizontal={true} scrollEnabled={scrollEnabled} showsHorizontalScrollIndicator={false} style={[styles.scrollViewContainer, style]} > {loopBothSides && this._renderImage(images[images.length - 1], -1)} {images.map(this._renderImage)} {(loop || loopBothSides) && this._renderImage(images[0], images.length)} </ScrollView> {customButtons ? ( customButtons(position, this._move) ) : ( <View style={styles.buttons}> {this.props.images.map((image, index) => ( <TouchableHighlight key={index} underlayColor="#ccc" onPress={() => this._move(index)} style={[ styles.button, position === index && styles.buttonSelected, ]} > <View /> </TouchableHighlight> ))} </View> )} {this._popHelperView()} </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, }, scrollViewContainer: { flexDirection: 'row', backgroundColor: '#222', }, image: { width: 200, height: '100%', }, buttons: { height: 15, marginTop: -15, justifyContent: 'center', alignItems: 'center', flexDirection: 'row', }, button: { margin: 3, width: 8, height: 8, borderRadius: 8 / 2, backgroundColor: '#ccc', opacity: 0.9, }, buttonSelected: { opacity: 1, backgroundColor: '#fff', }, }); export default ImageSlider;
PaulBGD/react-native-image-slider
ImageSlider.js
JavaScript
mit
8,352
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails oncall+relay * @format */ 'use strict'; const RelayClassic = require('../../RelayPublic'); const RelayQuery = require('../../query/RelayQuery'); const RelayTestUtils = require('RelayTestUtils'); const flattenRelayQuery = require('../flattenRelayQuery'); const generateRQLFieldAlias = require('../../query/generateRQLFieldAlias'); const splitDeferredRelayQueries = require('../splitDeferredRelayQueries'); describe('splitDeferredRelayQueries()', () => { // helper functions const {defer, getNode, getRefNode} = RelayTestUtils; // remove the root `id` field function filterGeneratedRootFields(node) { const children = node .getChildren() .filter( child => !(child instanceof RelayQuery.Field && child.isGenerated()), ); return node.clone(children); } beforeEach(() => { // Reset query numbers back to q0. jest.resetModules(); expect.extend(RelayTestUtils.matchers); }); it('returns the original query when there are no fragments', () => { const node = RelayClassic.QL`query{node(id:"4"){id,name}}`; const queryNode = getNode(node); const {required, deferred} = splitDeferredRelayQueries(queryNode); expect(required).toBe(queryNode); expect(deferred).toEqual([]); }); it('returns the original query when there are no deferred fragments', () => { const fragment = RelayClassic.QL`fragment on User{hometown{name}}`; const node = RelayClassic.QL` query { node(id:"4") { id name ${fragment} } } `; const queryNode = getNode(node); const {required, deferred} = splitDeferredRelayQueries(queryNode); expect(required).toBe(queryNode); expect(deferred).toEqual([]); }); it('splits a deferred fragment on the viewer root', () => { const fragment = RelayClassic.QL` fragment on Viewer { newsFeed(first: 10) { edges { node { id actorCount } } } } `; const node = RelayClassic.QL` query { viewer { actor { id } ${defer(fragment)} } } `; const queryNode = getNode(node); const {required, deferred} = splitDeferredRelayQueries(queryNode); // required part expect(required.getName()).toBe(queryNode.getName()); expect(required).toEqualQueryRoot( getNode(RelayClassic.QL`query{viewer{actor{id}}}`), ); expect(required.getID()).toBe('q3'); // deferred part expect(deferred.length).toBe(1); expect(deferred[0].required.getName()).toBe(queryNode.getName()); expect(deferred[0].required).toEqualQueryRoot( getNode( RelayClassic.QL` query { viewer { ${fragment} } } `, ), ); expect(deferred[0].required.getID()).toBe('q2'); expect(deferred[0].required.isDeferred()).toBe(true); // no nested deferreds expect(deferred[0].deferred).toEqual([]); }); it('splits a deferred fragment on a query without an ID argument', () => { const fragment = RelayClassic.QL` fragment on Actor { name } `; const node = RelayClassic.QL` query { username(name:"yuzhi") { id ${defer(fragment)} } } `; const queryNode = getNode(node); const {deferred} = splitDeferredRelayQueries(queryNode); expect(deferred.length).toBe(1); expect(deferred[0].required.getConcreteQueryNode().metadata).toEqual({ identifyingArgName: 'name', identifyingArgType: 'String!', isAbstract: true, isPlural: false, }); }); it('splits a nested feed on the viewer root', () => { const nestedFragment = RelayClassic.QL` fragment on Viewer { newsFeed(first: 10) { edges { node { id actorCount } } } } `; const fragment = RelayClassic.QL` fragment on Viewer { actor { name } ${defer(nestedFragment)} } `; const node = RelayClassic.QL` query { viewer { actor { id } ${fragment} } } `; const queryNode = getNode(node); const {required, deferred} = splitDeferredRelayQueries(queryNode); // required part expect(required.getName()).toBe(queryNode.getName()); expect(required).toEqualQueryRoot( getNode( RelayClassic.QL` query { viewer { actor { id } ${RelayClassic.QL` fragment on Viewer { actor { name, } } `} } } `, ), ); // deferred part expect(deferred.length).toBe(1); expect(deferred[0].required.getName()).toBe(queryNode.getName()); expect(deferred[0].required).toEqualQueryRoot( getNode( RelayClassic.QL` query { viewer { ${nestedFragment} } } `, ), ); expect(deferred[0].required.isDeferred()).toBe(true); // no nested deferreds expect(deferred[0].deferred).toEqual([]); }); it('splits nested deferred fragments', () => { const nestedFragment = RelayClassic.QL`fragment on NonNodeStory{message{text}}`; const fragment = RelayClassic.QL` fragment on Viewer { newsFeed(first: 10) { edges { node { tracking ${defer(nestedFragment)} } } } } `; const node = RelayClassic.QL` query { viewer { actor { name } ${defer(fragment)} } } `; const queryNode = getNode(node); const {required, deferred} = splitDeferredRelayQueries(queryNode); // required part expect(required.getName()).toBe(queryNode.getName()); expect(required).toEqualQueryRoot( getNode( RelayClassic.QL` query { viewer{actor{id,name}} } `, ), ); expect(required.getID()).toBe('q5'); // deferred part expect(deferred.length).toBe(1); expect(deferred[0].required.getName()).toBe(queryNode.getName()); expect(deferred[0].required).toEqualQueryRoot( getNode( RelayClassic.QL` query { viewer { ${RelayClassic.QL` fragment on Viewer { newsFeed(first: 10) { edges { cursor, node { id, tracking } }, pageInfo { hasNextPage, hasPreviousPage } } } `} } } `, ), ); expect(deferred[0].required.getID()).toBe('q4'); expect(deferred[0].required.isDeferred()).toBe(true); // nested deferred part expect(deferred[0].deferred.length).toBe(1); expect(deferred[0].deferred[0].required.getName()).toBe( queryNode.getName(), ); // TODO (#7891872): test unflattened queries. The expected output's `edges` // field has two `node` children: // - the requisite `node{id}` // - the nested deferred fragment expect( flattenRelayQuery(deferred[0].deferred[0].required), ).toEqualQueryRoot( flattenRelayQuery( getNode( RelayClassic.QL` query { viewer { newsFeed(first: 10) { edges { cursor node { ${nestedFragment} id } } pageInfo { hasNextPage hasPreviousPage } } } } `, ), ), ); expect(deferred[0].deferred[0].required.getID()).toBe('q2'); expect(deferred[0].deferred[0].required.isDeferred()).toBe(true); // no nested nested deferreds expect(deferred[0].deferred[0].deferred).toEqual([]); }); it('splits deferred fragments using ref queries', () => { const fragment = RelayClassic.QL`fragment on Page{profilePicture{uri}}`; const node = RelayClassic.QL` query { node(id:"4") { id name hometown { ${defer(fragment)} } } } `; const queryNode = getNode(node); const {required, deferred} = splitDeferredRelayQueries(queryNode); // required part expect(required.getName()).toBe(queryNode.getName()); expect(required).toEqualQueryRoot( getNode(RelayClassic.QL`query{node(id:"4"){hometown{id},id,name}}`), ); expect(required.getID()).toBe('q1'); expect( required .getFieldByStorageKey('hometown') .getFieldByStorageKey('id') .isRefQueryDependency(), ).toBe(true); // deferred part expect(deferred.length).toBe(1); expect(deferred[0].required.getName()).toBe(queryNode.getName()); expect(deferred[0].required).toEqualQueryRoot( filterGeneratedRootFields( getRefNode( RelayClassic.QL` query { nodes(ids:$ref_q1) { ${fragment} } } `, {path: '$.*.hometown.id'}, ), ), ); expect(deferred[0].required.getID()).toBe('q2'); expect(deferred[0].required.isDeferred()).toBe(true); // no nested deferreds expect(deferred[0].deferred).toEqual([]); }); it('splits a nested deferred fragments as a ref queries', () => { const nestedFragment = RelayClassic.QL`fragment on Page{profilePicture{uri}}`; const fragment = RelayClassic.QL` fragment on User { hometown { name ${defer(nestedFragment)} } } `; const node = RelayClassic.QL` query { node(id:"4") { id name ${defer(fragment)} } } `; const queryNode = getNode(node); const {required, deferred} = splitDeferredRelayQueries(queryNode); // required part expect(required.getName()).toBe(queryNode.getName()); expect(required).toEqualQueryRoot( getNode(RelayClassic.QL`query{node(id:"4"){id,name}}`), ); expect(required.getID()).toBe('q3'); // deferred part expect(deferred.length).toBe(1); expect(deferred[0].required.getName()).toBe(queryNode.getName()); expect(deferred[0].required).toEqualQueryRoot( getNode( RelayClassic.QL` query { node(id:"4") { ${RelayClassic.QL`fragment on User{hometown{name}}`}, id } } `, ), ); expect(deferred[0].required.getID()).toBe('q2'); expect(deferred[0].required.isDeferred()).toBe(true); expect( deferred[0].required .getChildren()[0] // node(4){hometown} (fragment) .getChildren()[0] // node(4){hometown} (field) .getChildren()[0] // node(4){hometown{id}} (field) .isRefQueryDependency(), ).toBe(true); // nested deferred part expect(deferred[0].deferred.length).toBe(1); expect(deferred[0].deferred[0].required.getName()).toBe( queryNode.getName(), ); expect(deferred[0].deferred[0].required).toEqualQueryRoot( filterGeneratedRootFields( getRefNode( RelayClassic.QL` query { nodes(ids:$ref_q2) { ${nestedFragment} } } `, {path: '$.*.hometown.id'}, ), ), ); expect(deferred[0].deferred[0].required.getID()).toBe('q4'); expect(deferred[0].deferred[0].required.isDeferred()).toBe(true); // no nested nested deferreds expect(deferred[0].deferred[0].deferred).toEqual([]); }); it('splits a deferred fragment nested inside a ref query', () => { // this time, going to defer something inside the ref const nestedFragment = RelayClassic.QL`fragment on Page{address{city}}`; const fragment = RelayClassic.QL` fragment on Page { profilePicture { uri } ${defer(nestedFragment)} } `; const node = RelayClassic.QL` query { node(id:"4") { id name hometown { ${defer(fragment)} } } } `; const queryNode = getNode(node); const {required, deferred} = splitDeferredRelayQueries(queryNode); // required part expect(required.getName()).toBe(queryNode.getName()); expect(required).toEqualQueryRoot( getNode(RelayClassic.QL`query{node(id:"4"){hometown{id},id,name}}`), ); expect( required .getFieldByStorageKey('hometown') .getFieldByStorageKey('id') .isRefQueryDependency(), ).toBe(true); expect(required.getID()).toBe('q1'); // deferred part expect(deferred.length).toBe(1); expect(deferred[0].required.getName()).toBe(queryNode.getName()); expect(deferred[0].required).toEqualQueryRoot( filterGeneratedRootFields( getRefNode( RelayClassic.QL` query { nodes(ids:$ref_q1) { ${RelayClassic.QL`fragment on Page{id,profilePicture{uri}}`} } } `, {path: '$.*.hometown.id'}, ), ), ); expect(deferred[0].required.getID()).toBe('q2'); expect(deferred[0].required.isDeferred()).toBe(true); // nested deferred part expect(deferred[0].deferred.length).toBe(1); expect(deferred[0].deferred[0].required.getName()).toBe( queryNode.getName(), ); expect(deferred[0].deferred[0].required).toEqualQueryRoot( filterGeneratedRootFields( getRefNode( RelayClassic.QL` query { nodes(ids:$ref_q2) { ${nestedFragment} } } `, {path: '$.*.hometown.id'}, ), ), ); expect(deferred[0].deferred[0].required.getID()).toBe('q3'); expect(deferred[0].deferred[0].required.isDeferred()).toBe(true); // no nested nested deferreds expect(deferred[0].deferred[0].deferred).toEqual([]); }); it('drops the required portion if it is empty', () => { const fragment = RelayClassic.QL` fragment on Viewer { newsFeed(first: 10) { edges { node { id actorCount } } } } `; const node = RelayClassic.QL` query { viewer { ${defer(fragment)} } } `; const queryNode = getNode(node); const {required, deferred} = splitDeferredRelayQueries(queryNode); // required part expect(required).toBe(null); // deferred part expect(deferred.length).toBe(1); expect(deferred[0].required.getName()).toBe(queryNode.getName()); expect(deferred[0].required).toEqualQueryRoot( getNode( RelayClassic.QL` query { viewer { ${fragment} } } `, ), ); expect(deferred[0].required.isDeferred()).toBe(true); // no nested deferred part expect(deferred[0].deferred).toEqual([]); }); it('handles a nested defer with no required part', () => { const nestedFragment = RelayClassic.QL`fragment on Viewer{primaryEmail}`; const fragment = RelayClassic.QL` fragment on Viewer { ${defer(nestedFragment)} } `; const node = RelayClassic.QL` query { viewer { isFbEmployee ${defer(fragment)} } } `; const queryNode = getNode(node); const {required, deferred} = splitDeferredRelayQueries(queryNode); // required part expect(required.getName()).toBe(queryNode.getName()); expect(required).toEqualQueryRoot( getNode( RelayClassic.QL` query { viewer{isFbEmployee} } `, ), ); // deferred part expect(deferred.length).toBe(1); expect(deferred[0].required).toBe(null); // nested deferred part expect(deferred[0].deferred.length).toBe(1); expect(deferred[0].deferred[0].required.getName()).toBe( queryNode.getName(), ); expect(deferred[0].deferred[0].required).toEqualQueryRoot( getNode( RelayClassic.QL` query { viewer { ${nestedFragment} } } `, ), ); expect(deferred[0].deferred[0].required.isDeferred()).toBe(true); // no nested nested deferreds expect(deferred[0].deferred[0].deferred).toEqual([]); }); it('handles a nested ref query defer with no required part', () => { const nestedFragment = RelayClassic.QL`fragment on Actor{hometown{name}}`; const fragment = RelayClassic.QL` fragment on Viewer { ${defer(nestedFragment)} } `; const node = RelayClassic.QL` query { viewer { actor { name ${defer(fragment)} } } } `; const queryNode = getNode(node); const {required, deferred} = splitDeferredRelayQueries(queryNode); // required part expect(required.getName()).toBe(queryNode.getName()); expect(required).toEqualQueryRoot( getNode( RelayClassic.QL` query { viewer{actor{id,name}} } `, ), ); expect(required.getID()).toBe('q1'); expect( required .getFieldByStorageKey('actor') .getFieldByStorageKey('id') .isRefQueryDependency(), ).toBe(true); // deferred part expect(deferred.length).toBe(1); expect(deferred[0].required).toBe(null); // nested deferred part expect(deferred[0].deferred.length).toBe(1); expect(deferred[0].deferred[0].required.getName()).toBe( queryNode.getName(), ); expect(deferred[0].deferred[0].required).toEqualQueryRoot( filterGeneratedRootFields( getRefNode( RelayClassic.QL` query { nodes(ids:$ref_q1) { ${nestedFragment} } } `, {path: '$.*.actor.id'}, ), ), ); expect(deferred[0].deferred[0].required.getID()).toBe('q2'); expect(deferred[0].deferred[0].required.isDeferred()).toBe(true); // no nested nested deferreds expect(deferred[0].deferred[0].deferred).toEqual([]); }); it('handles paths with plural fields', () => { const fragment = RelayClassic.QL`fragment on Actor{name}`; const node = RelayClassic.QL` query { node(id:"123") { actors { id ${defer(fragment)} } } } `; const queryNode = getNode(node); const {required, deferred} = splitDeferredRelayQueries(queryNode); // required part expect(required.getName()).toBe(queryNode.getName()); expect(required).toEqualQueryRoot( getNode( RelayClassic.QL` query { node(id:"123") { actors { id } } } `, ), ); expect(required.getID()).toBe('q1'); // deferred part expect(deferred.length).toBe(1); expect(deferred[0].required.getName()).toBe(queryNode.getName()); expect(deferred[0].required).toEqualQueryRoot( filterGeneratedRootFields( getRefNode( RelayClassic.QL` query { nodes(ids:$ref_q1) { ${fragment} } } `, {path: '$.*.actors.*.id'}, ), ), ); expect(deferred[0].required.getID()).toBe('q2'); expect(deferred[0].required.isDeferred()).toBe(true); // no nested deferreds expect(deferred[0].deferred).toEqual([]); }); it('works with nested node ancestors', () => { const fragment = RelayClassic.QL`fragment on Node{name}`; const node = RelayClassic.QL` query { viewer { actor { hometown { ${defer(fragment)} } } } } `; const queryNode = getNode(node); const {required, deferred} = splitDeferredRelayQueries(queryNode); // required part expect(required.getName()).toBe(queryNode.getName()); expect(required).toEqualQueryRoot( getNode( RelayClassic.QL` query { viewer { actor { hometown { id } } } } `, ), ); expect(required.getID()).toBe('q1'); // deferred part expect(deferred.length).toBe(1); expect(deferred[0].required.getName()).toBe(queryNode.getName()); expect(deferred[0].required).toEqualQueryRoot( filterGeneratedRootFields( getRefNode( RelayClassic.QL` query { nodes(ids:$ref_q1) { ${fragment} } } `, {path: '$.*.actor.hometown.id'}, ), ), ); expect(deferred[0].required.getID()).toBe('q2'); expect(deferred[0].required.isDeferred()).toBe(true); // no nested deferreds expect(deferred[0].deferred).toEqual([]); }); it('uses the auto-generated alias in ref query paths', () => { const fragment = RelayClassic.QL`fragment on User{firstName}`; const node = RelayClassic.QL` query { node(id:"4") { friends(first: 5) { edges { node { name ${defer(fragment)} } } } } } `; const queryNode = getNode(node); const {required, deferred} = splitDeferredRelayQueries(queryNode); // required part expect(required.getName()).toBe(queryNode.getName()); expect(required).toEqualQueryRoot( getNode( RelayClassic.QL` query { node(id:"4") { friends(first: 5) { edges { node { id name } } } } } `, ), ); expect(required.getID()).toBe('q1'); // deferred part const alias = generateRQLFieldAlias('friends.first(5)'); expect(deferred.length).toBe(1); expect(deferred[0].required.getName()).toBe(queryNode.getName()); expect(deferred[0].required).toEqualQueryRoot( filterGeneratedRootFields( getRefNode( RelayClassic.QL` query { nodes(ids:$ref_q1) { ${fragment} } } `, {path: '$.*.' + alias + '.edges.*.node.id'}, ), ), ); expect(deferred[0].required.getID()).toBe('q2'); expect(deferred[0].required.isDeferred()).toBe(true); // no nested deferreds expect(deferred[0].deferred).toEqual([]); }); it('correctly produces multi-level JSONPaths in ref queries', () => { const fragment = RelayClassic.QL`fragment on Actor{name}`; const node = RelayClassic.QL` query { node(id:"4") { friends(first: 5) { edges { node { ${defer(fragment)} } } } } } `; const queryNode = getNode(node); const {required, deferred} = splitDeferredRelayQueries(queryNode); // required part expect(required.getName()).toBe(queryNode.getName()); expect(required).toEqualQueryRoot( getNode( RelayClassic.QL` query { node(id:"4") { friends(first: 5) { edges { node { id } } } } } `, ), ); expect(required.getID()).toBe('q1'); // deferred part const alias = generateRQLFieldAlias('friends.first(5)'); expect(deferred.length).toBe(1); expect(deferred[0].required.getName()).toBe(queryNode.getName()); expect(deferred[0].required).toEqualQueryRoot( filterGeneratedRootFields( getRefNode( RelayClassic.QL` query { nodes(ids:$ref_q1) { ${fragment} } } `, {path: '$.*.' + alias + '.edges.*.node.id'}, ), ), ); expect(deferred[0].required.getID()).toBe('q2'); expect(deferred[0].required.isDeferred()).toBe(true); // no nested deferreds expect(deferred[0].deferred).toEqual([]); }); it('handles fragments that are not nodes', () => { const fragment = RelayClassic.QL`fragment on Image{uri}`; const node = RelayClassic.QL` query { node(id:"4") { id profilePicture(size: 100) { ${defer(fragment)} } } } `; const queryNode = getNode(node); const {required, deferred} = splitDeferredRelayQueries(queryNode); // required part expect(required.getName()).toBe(queryNode.getName()); expect(required).toEqualQueryRoot( getNode(RelayClassic.QL`query{node(id:"4"){id}}`), ); // deferred part expect(deferred.length).toBe(1); expect(deferred[0].required.getName()).toBe(queryNode.getName()); expect(deferred[0].required).toEqualQueryRoot( getNode( RelayClassic.QL` query { node(id:"4") { profilePicture(size: 100) { ${fragment} } } } `, ), ); expect(deferred[0].required.isDeferred()).toBe(true); // no nested deferreds expect(deferred[0].deferred).toEqual([]); }); it('omits required queries with only generated `id` fields', () => { const fragment = RelayClassic.QL`fragment on Node{name}`; const node = RelayClassic.QL` query { node(id:"4") { ${defer(fragment)} } } `; const queryNode = getNode(node); const {required, deferred} = splitDeferredRelayQueries(queryNode); // required part expect(required).toBe(null); // deferred part expect(deferred.length).toBe(1); expect(deferred[0].required.getName()).toBe(queryNode.getName()); expect(deferred[0].required).toEqualQueryRoot( getNode( RelayClassic.QL` query { node(id:"4") { ${fragment} } } `, ), ); expect(deferred[0].required.isDeferred()).toBe(true); // no nested deferreds expect(deferred[0].deferred).toEqual([]); }); it('does not omit "empty" required ref query dependencies', () => { // It isn't possible to produce an "empty" ref query dependency with // `RelayClassic.QL`, but in order to be future-proof against this possible edge // case, we create such a query by hand. const fragment = RelayClassic.QL`fragment on Node{name}`; const id = RelayQuery.Field.build({ fieldName: 'id', metadata: {isRequisite: true}, type: 'String', }); const typename = RelayQuery.Field.build({ fieldName: '__typename', metadata: {isRequisite: true}, type: 'String', }); let queryNode = RelayQuery.Root.build( 'splitDeferredRelayQueries', 'node', '4', [ id, typename, RelayQuery.Field.build({ fieldName: 'hometown', children: [id, getNode(defer(fragment))], metadata: { canHaveSubselections: true, isGenerated: true, inferredPrimaryKey: 'id', inferredRootCallName: 'node', }, type: 'Page', }), ], { identifyingArgName: 'id', }, ); queryNode = queryNode.clone( queryNode.getChildren().map((outerChild, ii) => { if (ii === 1) { return outerChild.clone( outerChild.getChildren().map((innerChild, jj) => { if (jj === 0) { return innerChild.cloneAsRefQueryDependency(); } else { return innerChild; } }), ); } else { return outerChild; } }), ); const {required, deferred} = splitDeferredRelayQueries(queryNode); // required part expect(deferred[0].required.getName()).toBe(queryNode.getName()); expect(required).toEqualQueryRoot( getNode( RelayClassic.QL` query { node(id:"4"){hometown{id},id} } `, ), ); expect(required.getID()).toBe('q1'); // deferred part expect(deferred.length).toBe(1); expect(deferred[0].required.getName()).toBe(queryNode.getName()); expect(deferred[0].required).toEqualQueryRoot( filterGeneratedRootFields( getRefNode( RelayClassic.QL` query { nodes(ids:$ref_q1) { ${fragment} } } `, {path: '$.*.hometown.id'}, ), ), ); expect(deferred[0].required.getID()).toBe('q2'); expect(deferred[0].required.isDeferred()).toBe(true); // no nested deferreds expect(deferred[0].deferred).toEqual([]); }); it('preserves required queries with only a non-generated `id` field', () => { const fragment = RelayClassic.QL`fragment on Node{name}`; const node = RelayClassic.QL` query { node(id:"4") { id ${defer(fragment)} } } `; const queryNode = getNode(node); const {required, deferred} = splitDeferredRelayQueries(queryNode); // required part expect(deferred[0].required.getName()).toBe(queryNode.getName()); expect(required).toEqualQueryRoot( getNode(RelayClassic.QL`query{node(id:"4"){id}}`), ); // deferred part expect(deferred.length).toBe(1); expect(deferred[0].required.getName()).toBe(queryNode.getName()); expect(deferred[0].required).toEqualQueryRoot( getNode( RelayClassic.QL` query { node(id:"4") { ${fragment} } } `, ), ); expect(deferred[0].required.isDeferred()).toBe(true); // no nested deferreds expect(deferred[0].deferred).toEqual([]); }); it('does not split empty fragments', () => { // null fragment could be caused by an `if`/`unless` call + a GK const nullFragment = RelayClassic.QL`fragment on Viewer{${null}}`; const fragment = RelayClassic.QL`fragment on Viewer{${nullFragment}}`; const node = RelayClassic.QL` query { viewer { primaryEmail ${defer(fragment)} } } `; const queryNode = getNode(node); const {required, deferred} = splitDeferredRelayQueries(queryNode); expect(required.getName()).toBe(queryNode.getName()); expect(required).toEqualQueryRoot( getNode( RelayClassic.QL` query { viewer{primaryEmail} } `, ), ); expect(deferred.length).toBe(0); }); it('does not flatten fragments when splitting root queries', () => { const fragment = RelayClassic.QL`fragment on Node{name}`; const query = getNode( RelayClassic.QL` query { node(id:"4") { ${defer(fragment)} } } `, ); const {deferred} = splitDeferredRelayQueries(query); expect(deferred.length).toBe(1); expect(deferred[0].required).toContainQueryNode(getNode(fragment)); }); it('does not flatten fragments when splitting ref queries', () => { const fragment = RelayClassic.QL`fragment on Feedback{likers{count}}`; const query = getNode( RelayClassic.QL` query { node(id:"STORY_ID") { feedback { ${defer(fragment)} } } } `, ); const {deferred} = splitDeferredRelayQueries(query); expect(deferred.length).toBe(1); expect(deferred[0].required).toContainQueryNode(getNode(fragment)); }); });
freiksenet/relay
packages/react-relay/classic/traversal/__tests__/splitDeferredRelayQueries-test.js
JavaScript
mit
32,018
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.Collections.Generic; using System.Data; using System.Data.SQLite; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using DotSpatial.Data; using DotSpatial.Plugins.SpatiaLite.Properties; using DotSpatial.Projections; using NetTopologySuite.IO; namespace DotSpatial.Plugins.SpatiaLite { /// <summary> /// Helper class with SpatiaLite specific operations. /// </summary> public class SpatiaLiteHelper { #region Fields private readonly bool _version4Plus; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="SpatiaLiteHelper"/> class. /// This is used to hide the default constructor because Open should be used so validation checks can be run before creating a SpatiaLiteHelper. /// </summary> private SpatiaLiteHelper() { } /// <summary> /// Initializes a new instance of the <see cref="SpatiaLiteHelper"/> class. /// </summary> /// <param name="connectionString">Connectionstring used to work with the database.</param> /// <param name="version4Plus">Indicates that the this is a spatialite database of version 4 or higher.</param> private SpatiaLiteHelper(string connectionString, bool version4Plus) : this() { ConnectionString = connectionString; _version4Plus = version4Plus; } #endregion #region Properties /// <summary> /// Gets the connection string of the connected database. /// </summary> public string ConnectionString { get; } #endregion #region Methods /// <summary> /// Trys to open the database of the given connection string. This fails if either the spatialite version or the geometry_columns table can't be found. /// </summary> /// <param name="connectionString">Connectionstring used to work with the database.</param> /// <param name="error">The variable that is used to return the error message. This is empty if there was no error.</param> /// <returns>Null on error otherwise the SpatiaLiteHelper connected to the database.</returns> public static SpatiaLiteHelper Open(string connectionString, out string error) { if (!CheckSpatiaLiteSchema(connectionString)) { error = Resources.CouldNotFindTheGeometryColumnsTable; return null; } bool version4Plus; if (!GetSpatialVersion(connectionString, out version4Plus)) { error = Resources.CouldNotFindTheSpatiaLiteVersion; return null; } error = string.Empty; return new SpatiaLiteHelper(connectionString, version4Plus); } /// <summary> /// Sets the environment variables so that SpatiaLite can find the dll's. /// </summary> /// <returns>true if successful.</returns> public static bool SetEnvironmentVars() { try { var pathVar = Environment.GetEnvironmentVariable("path", EnvironmentVariableTarget.User); var sqLitePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); if (sqLitePath == null) return false; var pathVariableExists = false; if (!string.IsNullOrEmpty(pathVar)) { if (pathVar.ToLower().Contains(sqLitePath.ToLower() + ";")) pathVariableExists = true; } if (!pathVariableExists) { pathVar = pathVar + ";" + sqLitePath; Environment.SetEnvironmentVariable("path", pathVar, EnvironmentVariableTarget.User); return true; } } catch (Exception ex) { Trace.WriteLine(ex.Message); return false; } return false; } /// <summary> /// Finds all column names in the database table. /// </summary> /// <param name="tableName">table name.</param> /// <returns>list of all column names.</returns> public List<string> GetColumnNames(string tableName) { var columnNameList = new List<string>(); var qry = $"PRAGMA table_info({tableName})"; using (var cmd = CreateCommand(ConnectionString, qry)) { cmd.Connection.Open(); var r = cmd.ExecuteReader(); while (r.Read()) { columnNameList.Add(r["name"].ToString()); } cmd.Connection.Close(); } return columnNameList; } /// <summary> /// Finds a list of all valid geometry columns in the database. /// </summary> /// <returns>the list of geometry columns.</returns> public List<GeometryColumnInfo> GetGeometryColumns() { if (_version4Plus) { var lst = new List<GeometryColumnInfo>(); var sql = "SELECT f_table_name, f_geometry_column, geometry_type, srid FROM geometry_columns"; using (var cmd = CreateCommand(ConnectionString, sql)) { cmd.Connection.Open(); var r = cmd.ExecuteReader(); while (r.Read()) { var gci = new GeometryColumnInfo { TableName = Convert.ToString(r["f_table_name"]), GeometryColumnName = Convert.ToString(r["f_geometry_column"]), Srid = Convert.ToInt32(r["srid"]), SpatialIndexEnabled = false }; int geometryType; if (int.TryParse(r["geometry_type"].ToString(), out geometryType)) { AssignGeometryTypeStringAndCoordDimension(geometryType, gci); } lst.Add(gci); } cmd.Connection.Close(); } return lst; } else { var lst = new List<GeometryColumnInfo>(); var sql = "SELECT f_table_name, f_geometry_column, type, coord_dimension, srid, spatial_index_enabled FROM geometry_columns"; using (var cmd = CreateCommand(ConnectionString, sql)) { cmd.Connection.Open(); var r = cmd.ExecuteReader(); while (r.Read()) { var gci = new GeometryColumnInfo { TableName = Convert.ToString(r["f_table_name"]), GeometryColumnName = Convert.ToString(r["f_geometry_column"]), GeometryType = Convert.ToString(r["type"]), Srid = Convert.ToInt32(r["srid"]), SpatialIndexEnabled = false }; try { gci.CoordDimension = Convert.ToInt32(r["coord_dimension"]); } catch (Exception) { var coords = Convert.ToString(r["coord_dimension"]); switch (coords) { case "XY": gci.CoordDimension = 2; break; case "XYZ": case "XYM": gci.CoordDimension = 3; break; case "XYZM": gci.CoordDimension = 4; break; } } lst.Add(gci); } cmd.Connection.Close(); } return lst; } } /// <summary> /// Finds all table names in the SpatiaLite database. /// </summary> /// <returns>a list of all table names.</returns> public List<string> GetTableNames() { var tableNameList = new List<string>(); using (var cnn = new SQLiteConnection(ConnectionString)) { var qry = "SELECT name FROM sqlite_master WHERE type = 'table'"; using (var cmd = new SQLiteCommand(qry, cnn)) { cmd.Connection.Open(); var r = cmd.ExecuteReader(); while (r.Read()) { tableNameList.Add(r[0].ToString()); } cmd.Connection.Close(); } } return tableNameList; } /// <summary> /// Reads the complete feature set from the database. /// </summary> /// <param name="featureSetInfo">information about the table.</param> /// <returns>the resulting feature set.</returns> public IFeatureSet ReadFeatureSet(GeometryColumnInfo featureSetInfo) { var sql = $"SELECT * FROM '{featureSetInfo.TableName}'"; return ReadFeatureSet(featureSetInfo, sql); } /// <summary> /// Reads the complete feature set from the database. /// </summary> /// <param name="featureSetInfo">information about the table.</param> /// <param name="sql">the sql query.</param> /// <returns>the resulting feature set.</returns> public IFeatureSet ReadFeatureSet(GeometryColumnInfo featureSetInfo, string sql) { var fType = GetGeometryType(featureSetInfo.GeometryType); SpatiaLiteFeatureSet fs = new SpatiaLiteFeatureSet(fType) { IndexMode = true, // setting the initial index mode.. Name = featureSetInfo.TableName, Filename = SqLiteHelper.GetSqLiteFileName(ConnectionString), LayerName = featureSetInfo.TableName }; using (var cmd = CreateCommand(ConnectionString, sql)) { cmd.Connection.Open(); var wkbr = new GaiaGeoReader(); var rdr = cmd.ExecuteReader(); var columnNames = PopulateTableSchema(fs, featureSetInfo.GeometryColumnName, rdr); while (rdr.Read()) { var wkb = rdr[featureSetInfo.GeometryColumnName] as byte[]; var geom = wkbr.Read(wkb); var newFeature = fs.AddFeature(geom); // populate the attributes foreach (var colName in columnNames) { newFeature.DataRow[colName] = rdr[colName]; } } cmd.Connection.Close(); // assign projection if (featureSetInfo.Srid > 0) { var proj = ProjectionInfo.FromEpsgCode(featureSetInfo.Srid); fs.Projection = proj; } return fs; } } /// <summary> /// Reads the feature set with the given name from the database. /// </summary> /// <param name="tableName">Name of the table whose content should be loaded.</param> /// <returns>Null if the table wasn't found otherwise the tables content.</returns> public IFeatureSet ReadFeatureSet(string tableName) { var geos = GetGeometryColumns(); var geo = geos.FirstOrDefault(_ => _.TableName == tableName); return geo == null ? null : ReadFeatureSet(geo); } /// <summary> /// Gets the GeometryType string and the CoordDimension from the given geometryTypeInt and assigns them to the given GeometryColumnInfo. /// </summary> /// <param name="geometryTypeInt">geometryTypeInt that indicates the GeometryType and CoordDimension that was used.</param> /// <param name="gci">The GeometryColumnInfo the values get assigned to.</param> private static void AssignGeometryTypeStringAndCoordDimension(int geometryTypeInt, GeometryColumnInfo gci) { var dimensionBase = geometryTypeInt / 1000; geometryTypeInt = geometryTypeInt - (dimensionBase * 1000); // get only the last number switch (geometryTypeInt) { case 1: gci.GeometryType = "point"; break; case 2: gci.GeometryType = "linestring"; break; case 3: gci.GeometryType = "polygon"; break; case 4: gci.GeometryType = "multipoint"; break; case 5: gci.GeometryType = "multilinestring"; break; case 6: gci.GeometryType = "multipolygon"; break; case 7: gci.GeometryType = "geometrycollection"; break; default: gci.GeometryType = "geometry"; break; } if (dimensionBase >= 3) { gci.CoordDimension = 4; } else if (dimensionBase >= 1) { gci.CoordDimension = 3; } else { gci.CoordDimension = 2; } } /// <summary> /// Returns true if the schema is a valid schema (has a geometry_columns table). /// </summary> /// <param name="connString">The connectionstring for the database.</param> /// <returns>True, if the schema has a geometry_columns table.</returns> private static bool CheckSpatiaLiteSchema(string connString) { var qry = "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'geometry_columns'"; using (var cmd = CreateCommand(connString, qry)) { var result = false; cmd.Connection.Open(); var obj = cmd.ExecuteScalar(); if (obj != null) result = true; cmd.Connection.Close(); return result; } } /// <summary> /// Creates a SQLite command. /// </summary> /// <param name="conString">connection string.</param> /// <param name="cmdText">command text.</param> /// <returns>the SpatiaLite command object.</returns> private static SQLiteCommand CreateCommand(string conString, string cmdText) { var con = new SQLiteConnection(conString); return new SQLiteCommand(cmdText, con); } private static FeatureType GetGeometryType(string geometryTypeStr) { switch (geometryTypeStr.ToLower()) { case "point": case "multipoint": return FeatureType.Point; case "linestring": case "multilinestring": return FeatureType.Line; case "polygon": case "multipolygon": return FeatureType.Polygon; default: return FeatureType.Unspecified; } } /// <summary> /// Gets the spatialite version. /// </summary> /// <param name="connectionString">The ConnectionString used to connect to the database.</param> /// <param name="version4Plus">Indicates whether this database has a structur belonging to version 4.0+.</param> /// <returns>True, if a version indicator could be found.</returns> private static bool GetSpatialVersion(string connectionString, out bool version4Plus) { bool retval = false; version4Plus = false; var qry = "PRAGMA table_info(geometry_columns)"; using (var cmd = CreateCommand(connectionString, qry)) { cmd.Connection.Open(); var r = cmd.ExecuteReader(); while (r.Read()) { if (r["name"].ToString() == "geometry_type") { version4Plus = true; retval = true; break; } if (r["name"].ToString() == "type") { retval = true; break; } } cmd.Connection.Close(); } return retval; } private static string[] PopulateTableSchema(IFeatureSet fs, string geomColumnName, SQLiteDataReader rdr) { var schemaTable = rdr.GetSchemaTable(); var columnNameList = new List<string>(); if (schemaTable != null) { foreach (DataRow r in schemaTable.Rows) { if (r["ColumnName"].ToString() != geomColumnName) { var colName = Convert.ToString(r["ColumnName"]); var colDataType = Convert.ToString(r["DataType"]); var t = Type.GetType(colDataType); if (t != null) { fs.DataTable.Columns.Add(colName, t); columnNameList.Add(colName); } } } } return columnNameList.ToArray(); } #endregion } }
DotSpatial/DotSpatial
Source/DotSpatial.Plugins.SpatiaLite/SpatiaLiteHelper.cs
C#
mit
19,148
var util = require('util'); var bleno = require('bleno'); var BlenoPrimaryService = bleno.PrimaryService; var ParkCharacteristic = require('./parkCharacteristic'); function DeviceInformationService() { DeviceInformationService.super_.call(this, { uuid: 'ec00', characteristics: [ new ParkCharacteristic() ] }); } util.inherits(DeviceInformationService, BlenoPrimaryService); module.exports = DeviceInformationService;
DriverCity/SPARK
src/smart_meter/src/BLENode/src/device-information-service.js
JavaScript
mit
444
#include "LayerView.h" #include "LayerWindow.h" #include "LayerItem.h" LayerView::LayerView (BRect frame, const char *name, CanvasView *_myView) : BView (frame, name, B_FOLLOW_ALL_SIDES, B_FRAME_EVENTS | B_WILL_DRAW) { fMyView = _myView; fFrame = frame; for (int i = 0; i < MAX_LAYERS; i++) layerItem[i] = NULL; } LayerView::~LayerView () { // printf ("~LayerView\n"); } void LayerView::setScrollBars (BScrollBar *_h, BScrollBar *_v) { mh = _h; mv = _v; mh->SetTarget (this); mv->SetTarget (this); } void LayerView::Draw (BRect updateRect) { inherited::Draw (updateRect); } void LayerView::AttachedToWindow () { // Yes I know this is rather blunt. Let's call this RAD and all is well. for (int i = 0; i < MAX_LAYERS; i++) { if (layerItem[i]) { RemoveChild (layerItem[i]); delete layerItem[i]; layerItem[i] = NULL; } } FrameResized (Bounds().Width(), Bounds().Height()); SetViewColor (B_TRANSPARENT_32_BIT); BRect layerItemRect = BRect (0, 0, LAYERITEMWIDTH, LAYERITEMHEIGHT); for (int i = fMyView->numLayers() - 1; i >= 0; i--) { layerItem[i] = new LayerItem (layerItemRect, "Layer Item", i, fMyView); AddChild (layerItem[i]); layerItemRect.OffsetBy (0, LAYERITEMHEIGHT); } } void LayerView::FrameResized (float width, float height) { float hmin, hmax, vmin, vmax; mh->GetRange (&hmin, &hmax); mv->GetRange (&vmin, &vmax); mh->SetRange (hmin, fFrame.Width() - width); mv->SetRange (vmin, fFrame.Height() - height); mh->SetProportion (width/fFrame.Width()); mv->SetProportion (height/fFrame.Height()); }
orangejua/Becasso
source/LayerView.cpp
C++
mit
1,559
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.iotcentral.generated; import com.azure.core.util.Context; import com.azure.resourcemanager.iotcentral.models.App; import com.azure.resourcemanager.iotcentral.models.SystemAssignedServiceIdentity; import com.azure.resourcemanager.iotcentral.models.SystemAssignedServiceIdentityType; /** Samples for Apps Update. */ public final class AppsUpdateSamples { /* * x-ms-original-file: specification/iotcentral/resource-manager/Microsoft.IoTCentral/stable/2021-06-01/examples/Apps_Update.json */ /** * Sample code: Apps_Update. * * @param manager Entry point to IotCentralManager. */ public static void appsUpdate(com.azure.resourcemanager.iotcentral.IotCentralManager manager) { App resource = manager.apps().getByResourceGroupWithResponse("resRg", "myIoTCentralApp", Context.NONE).getValue(); resource .update() .withIdentity( new SystemAssignedServiceIdentity().withType(SystemAssignedServiceIdentityType.SYSTEM_ASSIGNED)) .withDisplayName("My IoT Central App 2") .apply(); } }
Azure/azure-sdk-for-java
sdk/iotcentral/azure-resourcemanager-iotcentral/src/samples/java/com/azure/resourcemanager/iotcentral/generated/AppsUpdateSamples.java
Java
mit
1,304
--CREDITS-- Moritz Fromm <moritzgitfromm@gmail.com> --FILE-- <?php declare(strict_types=1); require 'vendor/autoload.php'; use Respect\Validation\Exceptions\IsbnException; use Respect\Validation\Exceptions\NestedValidationException; use Respect\Validation\Validator as v; try { v::isbn()->check('ISBN-12: 978-0-596-52068-7'); } catch (IsbnException $exception) { echo $exception->getMessage() . PHP_EOL; } try { v::not(v::isbn())->check('ISBN-13: 978-0-596-52068-7'); } catch (IsbnException $exception) { echo $exception->getMessage() . PHP_EOL; } try { v::isbn()->assert('978 10 596 52068 7'); } catch (NestedValidationException $exception) { echo $exception->getFullMessage() . PHP_EOL; } try { v::not(v::isbn())->assert('978 0 596 52068 7'); } catch (NestedValidationException $exception) { echo $exception->getFullMessage() . PHP_EOL; } ?> --EXPECT-- "ISBN-12: 978-0-596-52068-7" must be a ISBN "ISBN-13: 978-0-596-52068-7" must not be a ISBN - "978 10 596 52068 7" must be a ISBN - "978 0 596 52068 7" must not be a ISBN
Respect/Validation
tests/integration/rules/isbn.phpt
PHP
mit
1,065
from django.core.management.base import BaseCommand, CommandError from ship_data.models import GpggaGpsFix import datetime from main import utils import csv import os from django.db.models import Q import glob from main.management.commands import findgpsgaps gps_bridge_working_intervals = None # This file is part of https://github.com/cpina/science-cruise-data-management # # This project was programmed in a hurry without any prior Django experience, # while circumnavigating the Antarctic on the ACE expedition, without proper # Internet access, with 150 scientists using the system and doing at the same # cruise other data management and system administration tasks. # # Sadly there aren't unit tests and we didn't have time to refactor the code # during the cruise, which is really needed. # # Carles Pina (carles@pina.cat) and Jen Thomas (jenny_t152@yahoo.co.uk), 2016-2017. class Command(BaseCommand): help = 'Outputs the track in CSV format.' def add_arguments(self, parser): parser.add_argument('output_directory', type=str, help="Will delete existing files that started on the same start date") parser.add_argument('start', type=str, help="Start of the GPS data. Format: YYYYMMDD") parser.add_argument('end', type=str, help="End of the GPS data. Format: YYYYMMDD or 'yesterday'") def handle(self, *args, **options): generate_all_tracks(options['output_directory'], options['start'], options['end']) def generate_all_tracks(output_directory, start, end): global gps_bridge_working_intervals gps_gaps = findgpsgaps.FindDataGapsGps("GPS Bridge1", start, end) gps_bridge_working_intervals = gps_gaps.find_gps_missings() generate_fast(output_directory, 3600, "1hour", start, end) generate_fast(output_directory, 300, "5min", start, end) generate_fast(output_directory, 60, "1min", start, end) generate_fast(output_directory, 1, "1second", start, end) def generate_fast(output_directory, seconds, file_suffix, start, end): """ This method uses Mysql datetime 'ends with' instead of doing individual queries for each 'seconds'. It's faster but harder to find gaps in the data. """ first_date = datetime.datetime.strptime(start, "%Y%m%d") first_date = utils.set_utc(first_date) if end == "yesterday": last_date = utils.last_midnight() else: last_date = datetime.datetime.strptime(end, "%Y%m%d") last_date = utils.set_utc(last_date) starts_file_format = first_date.strftime("%Y%m%d") ends_file_format = last_date.strftime("%Y%m%d") filename = "track_{}_{}_{}.csv".format(starts_file_format, ends_file_format, file_suffix) files_to_delete = glob.glob(os.path.join(output_directory, "track_{}_*_{}.csv".format(starts_file_format, file_suffix))) print("Will start processing:", filename) file_path = os.path.join(output_directory, filename) if file_path in files_to_delete: files_to_delete.remove(file_path) # In case that this script is re-generating the file file = open(file_path + ".tmp", "w") csv_writer = csv.writer(file) csv_writer.writerow(["date_time", "latitude", "longitude"]) one_day = datetime.timedelta(days=1) current_day = first_date while current_day <= last_date: process_day(current_day, seconds, csv_writer) current_day += one_day delete_files(files_to_delete) file.close() os.rename(file_path + ".tmp", file_path) def process_day(date_time_process, seconds, csv_writer): date_time_process_tomorrow = date_time_process + datetime.timedelta(days=1) today_filter = Q(date_time__gte=date_time_process) & Q(date_time__lt=date_time_process_tomorrow) if seconds == 1: query_set = GpggaGpsFix.objects.filter(today_filter).order_by('date_time') elif seconds == 60: query_set = GpggaGpsFix.objects.filter(today_filter).filter(date_time__contains=':01.').order_by('date_time') elif seconds == 300: query_set = GpggaGpsFix.objects.filter(today_filter).filter(Q(date_time__contains=':00:01.') | Q(date_time__contains=':05:01.') | Q(date_time__contains=':10:01.') | Q(date_time__contains=':15:01.') | Q(date_time__contains=':20:01.') | Q(date_time__contains=':25:01.') | Q(date_time__contains=':30:01.') | Q(date_time__contains=':35:01.') | Q(date_time__contains=':40:01.') | Q(date_time__contains=':45:01.') | Q(date_time__contains=':50:01.') | Q(date_time__contains=':55:01.')).order_by('date_time') elif seconds == 3600: query_set = GpggaGpsFix.objects.filter(today_filter).filter(date_time__contains=':00:01').order_by('date_time') else: assert False # need to add a if case for this # 64: GPS Bridge # 63: GPS Trimble query_set = query_set.filter(utils.filter_out_bad_values()) previous_date_time_string = "" for gps_info in query_set.iterator(): date_time_string = gps_info.date_time.strftime("%Y-%m-%d %H:%M:%S") if date_time_string == previous_date_time_string: continue if which_gps(date_time_string) == "GPS Bridge1": if gps_info.device_id == 64: l = [gps_info.date_time.strftime("%Y-%m-%d %H:%M:%S"), "{:.4f}".format(gps_info.latitude), "{:.4f}".format(gps_info.longitude)] # print(l) csv_writer.writerow(l) previous_date_time_string = date_time_string else: if gps_info.device_id == 63: l = [gps_info.date_time.strftime("%Y-%m-%d %H:%M:%S"), "{:.4f}".format(gps_info.latitude), "{:.4f}".format(gps_info.longitude)] # print(l) csv_writer.writerow(l) previous_date_time_string = date_time_string def delete_files(files): for file in files: print("Deleting file:", file) os.remove(file) def generate_method_1(output_directory, seconds, file_suffix): """ This method does a query every 'seconds'. Very slow, could be used to find gaps easily on the data. As it is now it is difficult to decide which GPS the get comes from. """ time_delta = datetime.timedelta(seconds=seconds) first_date = GpggaGpsFix.objects.earliest().date_time last_date = GpggaGpsFix.objects.latest().date_time filename = "track_{}_{}_{}.csv".format(first_date.strftime("%Y%m%d"), last_date.strftime("%Y%m%d"), file_suffix) print("Will start processing:", filename) file_path = os.path.join(output_directory, filename) file = open(file_path, "w") csv_writer = csv.writer(file) csv_writer.writerow(["date_time", "latitude", "longitude"]) current_date = first_date previous_date = current_date while current_date < last_date: location = utils.ship_location(current_date) if location.date_time != previous_date: if location.date_time is not None and location.latitude is not None and location.longitude is not None: csv_writer.writerow([location.date_time.strftime("%Y-%m-%d %H:%M:%S"), "{:.4f}".format(location.latitude), "{:.4f}".format(location.longitude)]) if location.date_time is None: print("No data for:", current_date) if previous_date.day != current_date.day: print("Generating CSV GPS info:", current_date) previous_date = current_date current_date = current_date + time_delta def which_gps(date_time_str): for interval in gps_bridge_working_intervals: if interval['starts'] < date_time_str <= interval['stops']: # if date_time_str > interval['starts'] and date_time_str <= interval['stops']: return "GPS Bridge1" return "Trimble GPS"
cpina/science-cruise-data-management
ScienceCruiseDataManagement/main/management/commands/exportgpstracks.py
Python
mit
8,461
<?php namespace DoctrineProxies\__CG__\Entity; /** * DO NOT EDIT THIS FILE - IT WAS CREATED BY DOCTRINE'S PROXY GENERATOR */ class User extends \Entity\User implements \Doctrine\ORM\Proxy\Proxy { /** * @var \Closure the callback responsible for loading properties in the proxy object. This callback is called with * three parameters, being respectively the proxy object to be initialized, the method that triggered the * initialization process and an array of ordered parameters that were passed to that method. * * @see \Doctrine\Common\Persistence\Proxy::__setInitializer */ public $__initializer__; /** * @var \Closure the callback responsible of loading properties that need to be copied in the cloned object * * @see \Doctrine\Common\Persistence\Proxy::__setCloner */ public $__cloner__; /** * @var boolean flag indicating if this object was already initialized * * @see \Doctrine\Common\Persistence\Proxy::__isInitialized */ public $__isInitialized__ = false; /** * @var array properties to be lazy loaded, with keys being the property * names and values being their default values * * @see \Doctrine\Common\Persistence\Proxy::__getLazyProperties */ public static $lazyPropertiesDefaults = array(); /** * @param \Closure $initializer * @param \Closure $cloner */ public function __construct($initializer = null, $cloner = null) { $this->__initializer__ = $initializer; $this->__cloner__ = $cloner; } /** * * @return array */ public function __sleep() { if ($this->__isInitialized__) { return array('__isInitialized__', 'id', 'username', 'password', 'email', 'group'); } return array('__isInitialized__', 'id', 'username', 'password', 'email', 'group'); } /** * */ public function __wakeup() { if ( ! $this->__isInitialized__) { $this->__initializer__ = function (User $proxy) { $proxy->__setInitializer(null); $proxy->__setCloner(null); $existingProperties = get_object_vars($proxy); foreach ($proxy->__getLazyProperties() as $property => $defaultValue) { if ( ! array_key_exists($property, $existingProperties)) { $proxy->$property = $defaultValue; } } }; } } /** * */ public function __clone() { $this->__cloner__ && $this->__cloner__->__invoke($this, '__clone', array()); } /** * Forces initialization of the proxy */ public function __load() { $this->__initializer__ && $this->__initializer__->__invoke($this, '__load', array()); } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific loading logic */ public function __isInitialized() { return $this->__isInitialized__; } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific loading logic */ public function __setInitialized($initialized) { $this->__isInitialized__ = $initialized; } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific loading logic */ public function __setInitializer(\Closure $initializer = null) { $this->__initializer__ = $initializer; } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific loading logic */ public function __getInitializer() { return $this->__initializer__; } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific loading logic */ public function __setCloner(\Closure $cloner = null) { $this->__cloner__ = $cloner; } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific cloning logic */ public function __getCloner() { return $this->__cloner__; } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific loading logic * @static */ public function __getLazyProperties() { return self::$lazyPropertiesDefaults; } /** * {@inheritDoc} */ public function setGroup(\Entity\UserGroup $group) { $this->__initializer__ && $this->__initializer__->__invoke($this, 'setGroup', array($group)); return parent::setGroup($group); } /** * {@inheritDoc} */ public function setPassword($password) { $this->__initializer__ && $this->__initializer__->__invoke($this, 'setPassword', array($password)); return parent::setPassword($password); } /** * {@inheritDoc} */ public function hashPassword($password) { $this->__initializer__ && $this->__initializer__->__invoke($this, 'hashPassword', array($password)); return parent::hashPassword($password); } /** * {@inheritDoc} */ public function setUsername($username) { $this->__initializer__ && $this->__initializer__->__invoke($this, 'setUsername', array($username)); return parent::setUsername($username); } /** * {@inheritDoc} */ public function setEmail($email) { $this->__initializer__ && $this->__initializer__->__invoke($this, 'setEmail', array($email)); return parent::setEmail($email); } /** * {@inheritDoc} */ public function getId() { if ($this->__isInitialized__ === false) { return (int) parent::getId(); } $this->__initializer__ && $this->__initializer__->__invoke($this, 'getId', array()); return parent::getId(); } /** * {@inheritDoc} */ public function getUsername() { $this->__initializer__ && $this->__initializer__->__invoke($this, 'getUsername', array()); return parent::getUsername(); } /** * {@inheritDoc} */ public function getEmail() { $this->__initializer__ && $this->__initializer__->__invoke($this, 'getEmail', array()); return parent::getEmail(); } /** * {@inheritDoc} */ public function getPassword() { $this->__initializer__ && $this->__initializer__->__invoke($this, 'getPassword', array()); return parent::getPassword(); } /** * {@inheritDoc} */ public function getGroup() { $this->__initializer__ && $this->__initializer__->__invoke($this, 'getGroup', array()); return parent::getGroup(); } }
vihoangson/SachHay
application/models/Proxies/__CG__EntityUser.php
PHP
mit
7,013
using System.Collections.ObjectModel; using System.ComponentModel; namespace FG5eParserModels.Utility_Modules { public class ReferenceManual : INotifyPropertyChanged { private string ChapterName { get; set; } public ObservableCollection<string> SubchapterNameList { get; set; } public ObservableCollection<ReferenceNote> ReferenceNoteList { get; set; } public string _ChapterName { get { return ChapterName; } set { ChapterName = value; OnPropertyChanged("_ChapterName"); } } //constructor public ReferenceManual() { ReferenceNoteList = new ObservableCollection<ReferenceNote>(); SubchapterNameList = new ObservableCollection<string>(); } #region PROPERTY CHANGES // Declare the interface event public event PropertyChangedEventHandler PropertyChanged; // Create the OnPropertyChanged method to raise the event public void OnPropertyChanged(string name) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(name)); } } #endregion } public class ReferenceNote : INotifyPropertyChanged { private string Title { get; set; } private string Details { get; set; } private string SubchapterName { get; set; } public string _Title { get { return Title; } set { Title = value; OnPropertyChanged("_Title"); } } public string _Details { get { return Details; } set { Details = value; OnPropertyChanged("_Details"); } } public string _SubchapterName { get { return SubchapterName; } set { SubchapterName = value; OnPropertyChanged("_SubchapterName"); } } #region PROPERTY CHANGES // Declare the interface event public event PropertyChangedEventHandler PropertyChanged; // Create the OnPropertyChanged method to raise the event public void OnPropertyChanged(string name) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(name)); } } #endregion } }
kay9911/FG5EParser
FG5eParserModels/Utility Modules/ReferenceManual.cs
C#
mit
2,850
const expect = require('chai').expect const includeMimeType = require('../src/file').includeMimeType const findInFile = require('../src/file').findInFile describe('file : includeMimeType', () => { it('MIME_TYPES_IGNORED contain this mime type', () => { expect(includeMimeType('test/directoryTest/file2.png')).to.be.true }) it('MIME_TYPES_IGNORED not contain this mime type', () => { expect(includeMimeType('test/directoryTest/file1.js')).to.be.false }) }) describe('file : findInFile', () => { it('will some results (string)', () => { const results = findInFile('foo', 'test/directoryTest/file1.js') expect(results).to.be.eql({ 1: [5], 2: [12], 3: [5, 18] }) }) it('will some results (regExp)', () => { const results = findInFile(/foo/, 'test/directoryTest/file1.js') expect(results).to.be.eql({ 1: [5], 2: [12], 3: [5, 18] }) }) it('will nothing (string)', () => { const results = findInFile('nothing', 'test/directoryTest/file1.js') expect(results).to.be.eql({}) }) it('will nothing (regExp)', () => { const results = findInFile(/nothing/, 'test/directoryTest/file1.js') expect(results).to.be.eql({}) }) })
arncet/position-in-file
test/file.spec.js
JavaScript
mit
1,224
var fs = require('fs'); var assert = require('assert'); var JSZip = require('jszip'); var path = require('path') var compareWorkbooks = require('./util/compareworkbooks.js') var excelbuilder = require('..'); describe('It generates a simple workbook', function () { it('generates a ZIP file we can save', function (done) { var workbook = excelbuilder.createWorkbook(); var table = [ [1, 2, "", 4, 5], [2, 4, null, 16, 20], [1, 4, NaN, 16, 25], [4, 8, undefined, 16, 20] ] var sheet1 = workbook.createSheet('sheet1', table[0].length, table.length); table.forEach(function (row, rowIdx) { row.forEach(function (val, colIdx) { sheet1.set(colIdx + 1, rowIdx + 1, val) }) }) workbook.generate(function (err, zip) { if (err) throw err; zip.generateAsync({type: "nodebuffer"}).then(function (buffer) { var OUTFILE = './test/out/example.xlsx'; fs.writeFile(OUTFILE, buffer, function (err) { console.log('open \"' + OUTFILE + "\""); compareWorkbooks('./test/files/example.xlsx', OUTFILE, function (err, result) { if (err) throw err; // assert(result) done(err); }); }); }); }); }); });
protobi/msexcel-builder
test/na.js
JavaScript
mit
1,273
# frozen_string_literal: true class Dummy::Atom::Documents < Folio::Atom::Base ATTACHMENTS = %i[documents] STRUCTURE = { title: :string, } ASSOCIATIONS = {} validates :document_placements, presence: true def self.molecule_cell_name "dummy/molecule/documents" end def self.console_icon :insert_drive_file end end # == Schema Information # # Table name: folio_atoms # # id :bigint(8) not null, primary key # type :string # position :integer # created_at :datetime not null # updated_at :datetime not null # placement_type :string # placement_id :bigint(8) # locale :string # data :jsonb # associations :jsonb # data_for_search :text # # Indexes # # index_folio_atoms_on_placement_type_and_placement_id (placement_type,placement_id) #
sinfin/folio
test/dummy/app/models/dummy/atom/documents.rb
Ruby
mit
885
<?php /** * Created by PhpStorm. * User: juan2ramos * Date: 13/08/15 * Time: 23:43 */ class Code_model extends CI_Model { function __construct() { parent::__construct(); $this->load->database(); } function getCodes() { $query = $this->db->get('codes'); return $query->result_array();; } function getCodeWhere($code) { $this->db->where('code',$code); $this->db->where('status','0'); $query = $this->db->get('codes'); return ($query->num_rows() > 0)?true:false; } function getCode($id) { $this->db->where('id',$id); $query = $this->db->get('codes'); return $query->result_array();; } function updateCode($postData, $code ) { $this->db->where('code', $code); return $this->db->update('codes', $postData); } function addCode($postData){ $this->db->insert('code', $postData); } }
juan2ramos/panama
application/models/Code_model.php
PHP
mit
951
var Cat = require('../src/Cat'); require('chai').should(); describe('This should pass if mutated', function(){ it('yes it should', function(){ var name = Math.random(); true.should.equal(true); }); });
TeamSentinaught/sentinaught
integration-tests/fails/rubbishTests.js
JavaScript
mit
208
<?php class Empresa extends DataMapper { var $db_params = 'default'; var $table = 'empresa'; public $model = 'empresa'; var $has_one = array('atividade','uf'); var $has_many = array('setor','historico','contato'); var $CI; var $validation = array( 'nome' => array( 'rules' => array( 'required', 'trim', 'unique', 'min_length'=>3, 'max_length' => 200 ) ), 'atividade_id' => array( 'rules' => array('required') ) ); var $default_order_by = array('nome' => 'asc'); /**********************************************************************/ function __construct($id = NULL){ $this->CI =& get_instance(); parent::__construct(); if($id!=NULL){ $this->get_by_id($id); } } /**********************************************************************/ /**********************************************************************/ /**********************************************************************/ } /* End of file empresa.php */ /* Location: ./application/models/macaetec/empresa.php */
coutinho2004/macaetec
application/models/macaetec/empresa.php
PHP
mit
1,033
<?php session_start(); include '../php/config.php'; ?> <!DOCTYPE html> <html lang="en"> <head> <link rel="shortcut icon" href="../img/favicon.ico"> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>Sahakit System</title> <link href="../vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <link href="../vendor/metisMenu/metisMenu.min.css" rel="stylesheet"> <link href="../dist/css/sb-admin-2.css" rel="stylesheet"> <link href="../vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <?php $status = null; if (isset($_SESSION['status'])) { $status = $_SESSION['status']; } ?> </head> <body> <?php include 'menu_index.php'?> <div id="page-wrapper"> <div class="row"> <div class="col-lg-12"> <div class="panel panel-default"> <!-- .panel-heading --> <div class="panel-body"> <font color="red">สร้างเมื่อ วันพฤหัสบดี, 10 พฤศจิกายน 2559 20:28</font><br> <p>สหกิจศึกษาคืออะไร<br>&nbsp;&nbsp;&nbsp;&nbsp; ในสภาวะการณ์ปัจจุบันใน ตลาดแรงงานมีการแข่งขันและลักษณะของบัณฑิตที่ตลาดแรงงานมีความต้องการได้พัฒนาไป ความต้องการของสถานประกอบการที่ต้องการให้มีในตัวบัณฑิต ได้แก่ การเป็นผู้ที่ไว้วางใจได้ในด้านการงาน ความคิดริเริ่ม ระเบียบวินัย จริยธรรม ศีลธรรม การสื่อสารข้อมูล การเป็นผู้นำ เป็นต้น สิ่งที่ท้าทายสำหรับบัณฑิตในปัจจุบัน คือ การได้มีโอกาสสร้างความเข้าใจและคุ้นเคยกับโลกแห่งความจริงของการทำงานและ การเรียนรู้ เพื่อให้ได้มาซึ่งทักษะของงานอาชีพและทักษะด้าน พัฒนาตนเอง นอกเหนือไปจากทักษะด้านวิชาการ ทักษะเหล่านี้จะเรียนรู้และพัฒนาได้โดยเร็วเมื่อนักศึกษาได้มีโอกาสไป ปฏิบัติงานจริง ในสถานประกอบการต่างๆ</p> <p>หลักการและเหตุผล<br>&nbsp;&nbsp;&nbsp;&nbsp; สหกิจศึกษา (Cooperative Education) เป็นแผนการศึกษาโดยมีจุดมุ่งหมายให้นักศึกษาได้มีประสบการณ์ปฏิบัติงานจริง ในสถานประกอบการอย่างมีประสิทธิภาพ โดยเน้นให้นักศึกษาได้นำเอาวิชาการทั้งทางภาคทฤษฎีและปฏิบัติต่างๆ ที่ได้ศึกษามาแล้ว นำไปปฏิบัติในสถานประกอบการให้ได้ผลดี ทำให้นักศึกษาสามารถเรียนรู้ประสบการณ์จากการไปปฏิบัติงาน และทำให้นักศึกษามีคุณภาพตรงตามวัตถุประสงค์ที่สถานประกอบการต้องการมากที่ สุด เพื่อเป็นการส่งเสริมความสัมพันธ์และความร่วมมืออันดีระหว่างมหาวิทยาลัย เทคโนโลยีราชมงคลกรุงเทพ กับสถานประกอบการที่นักศึกษาได้ไปปฏิบัติงาน อีกทั้งเป็นการเผยแพร่เกียรติคุณ ของมหาวิทยาลัยเทคโนโลยีราชมงคลกรุงเทพที่มุ่งเน้นผลิตบัณฑิตนักปฏิบัติการ ต่อบุคคลและหน่วยงานต่างๆ ที่อยู่ภายนอก</p> <p>ปรัชญา "มหาวิทยาลัยชีวิต เริ่มต้นที่สหกิจศึกษา "</p> <p>ภารกิจหลัก<br>&nbsp;&nbsp;&nbsp;&nbsp; คัดเลือกนักศึกษาและจัดหาสถานประกอบการเพื่อให้นักศึกษาออกไปปฏิบัติงาน ณ สถานประกอบการ</p> <p>วัตถุประสงค์<br>&nbsp;&nbsp;&nbsp;&nbsp; 1. เพื่อเปิดโอกาสให้นักศึกษาได้รับประสบการณ์ตรงเกี่ยวกับการ ทำงานจริงในสถานประกอบการ<br>&nbsp;&nbsp;&nbsp;&nbsp; 2. ศึกษาเรียนรู้เรื่องการจัดและบริหารงานในสถานประกอบการ อย่างละเอียด<br>&nbsp;&nbsp;&nbsp;&nbsp; 3. ได้พบเห็นปัญหาต่างๆ ที่แท้จริงของสถานประกอบการและ คิดค้นวิธีแก้ปัญหาเฉพาะหน้า <br>&nbsp;&nbsp;&nbsp;&nbsp; 4. ศึกษาเกี่ยวกับบุคลากรส่วนต่างๆ ของผู้ร่วมปฏิบัติงานสถานประกอบการทั้งด้านบุคลิกภาพ</p> <p>หน้าที่ความรับผิดชอบการทำงานร่วมกันและการปฏิบัติงานเฉพาะทาง<br>&nbsp;&nbsp;&nbsp;&nbsp; 5. รู้จักปรับตัวให้เข้ากับสังคมในสถานประกอบการ การเป็นผู้นำและเป็นผู้ตามที่เหมาะสม<br>&nbsp;&nbsp;&nbsp;&nbsp; 6. เพื่อส่งเสริมความสัมพันธ์อันดีระหว่างมหาวิทยาลัย กับ สถาน ประกอบการที่นักศึกษาไปปฏิบัติงาน</p> <p>สหกิจศึกษา<br>&nbsp;&nbsp;&nbsp;&nbsp; 7. เพื่อเผยแพร่ชื่อเสียงของมหาวิทยาลัยเทคโนโลยีราชมงคลกรุงเทพต่อบุคคลและ สถาบันต่างๆที่อยู่</p> <p>ภายนอก</p> <p>หลักสูตรที่เข้าร่วมสหกิจศึกษา<br>&nbsp;&nbsp;&nbsp;&nbsp; มหาวิทยาลัย เทคโนโลยีราชมงคลกรุงเทพได้จัดระบบการศึกษาเพื่อเป็น ระบบทวิภาค โดยใน 1 ปีการศึกษา จะประกอบด้วย 2 ภาคการศึกษา (1 ภาคการศึกษามีระยะเวลา 17 สัปดาห์) และ 1 ภาคการศึกษาสหกิจศึกษามีระยะเวลาเท่ากับ 17 สัปดาห์</p> <p>หลักสูตรสหกิจศึกษามีลักษณะดังนี้<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 1. เป็นหลักสูตรบังคับสำหรับนักศึกษาหลักสูตรวิศวกรรมศาสตร์และหลักสูตรอื่นๆ ที่เข้าร่วมสหกิจศึกษา โดยที่สาขาวิชาต้นสังกัดของนักศึกษาจะเป็นผู้รับผิดชอบ คัดเลือกนักศึกษาที่มีคุณสมบัติครบถ้วนเข้าร่วมสหกิจศึกษา<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 2. จัดภาคการศึกษาสหกิจศึกษาไว้ในภาคการศึกษาที่ 2 ของปีที่ 3 ( ภาคสมทบ) และภาคการศึกษาที่ 1 ของปีที่ 4 ( ภาคปกติ)<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 3. ภาคการศึกษาสหกิจศึกษามีค่าเท่ากับ 6 หน่วยกิต การประเมินผลเป็น S และ U<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 4. กำหนดให้นักศึกษาจะต้องไปปฏิบัติงานอย่างน้อย 1 ภาคการศึกษา โดยจะต้องมีระยะเวลาการปฏิบัติงานตามที่กำหนด ทั้งนี้ไม่ต่ำกว่า 17 สัปดาห์</p> <p>หน่วยงานและบุคลากรที่รับผิดชอบ<br>&nbsp;&nbsp;&nbsp;&nbsp; มหาวิทยาลัย เทคโนโลยีราชมงคลกรุงเทพ ได้จัดตั้งหน่วยงานที่เรียกว่า สำนักงานสหกิจศึกษา (Office of Cooperative Education : OCE) ภายใต้การกำกับของอธิการบดี เพื่อทำหน้าที่พัฒนารูปแบบระบบการศึกษาแบบสหกิจศึกษาให้เหมาะสม และ รับผิดชอบการประสานงาน ระหว่างนักศึกษา คณาจารย์และสถานประกอบการ ในการเตรียมความพร้อมนักศึกษาสำหรับการปฏิบัติงาน ณ สถานประกอบการ</p> <p>1. เจ้าหน้าที่สหกิจศึกษา (OCE Coordinator)<br>&nbsp;&nbsp;&nbsp;&nbsp; บุคลากร ที่สังกัดสำนักงานสหกิจศึกษาเป็นผู้รับผิดชอบในการจัดเก็บข้อมูล ประสานงานและอำนวยความสะดวกแก่สถานประกอบการ อาจารย์ที่ปรึกษาสหกิจศึกษา และนักศึกษาสหกิจศึกษา ในส่วนที่เกี่ยวข้องกับสหกิจศึกษา ในฝ่ายต่างๆ<br>2. อาจารย์ที่ปรึกษาสหกิจศึกษา (OCE Advisor)<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ทำหน้าที่เป็นผู้ประสานงานด้านสหกิจศึกษาภายในสาขาวิชา ดังนี้ <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; • ชี้แจงสถานการณ์ที่นักศึกษาจะต้องประสบและเสนอแนะวิธีการแก้ปัญหาที่อาจจะเกิดขึ้นใน</p> <p>สถานประกอบการ<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; • นิเทศงาน อย่างน้อย 2 ครั้งต่อนักศึกษา 1 คน <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; • ให้คำปรึกษาแก่สถานประกอบการเพื่อช่วยแก้ปัญหาในการทำงาน ผ่านการปฏิบัติงานของ</p> <p>นักศึกษาสหกิจศึกษา<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; • พบปะร่วมปรึกษากับพนักงานที่ปรึกษา และผู้บริหารสถานประกอบการที่นักศึกษาฝึกงาน</p> <p>เพื่อรับฟังความคิดเห็น และข้อเสนอแนะต่างๆ <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; • สร้างความสัมพันธ์อันดีต่อคณะผู้บริหาร และผู้ร่วมงานในสถานประกอบการที่ไปนิเทศนัก</p> <p>ศึกษาสหกิจศึกษา<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; • เข้าร่วมในการปฐมนิเทศ ปัจฉิมนิเทศ และกิจกรรมที่สำนักงานสหกิจศึกษาจัดขึ้น<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; • พิจารณาผลการปฏิบัติงานสหกิจศึกษา เพื่อประเมินผลการออกปฏิบัติงานสหกิจศึกษา ของนักศึกษาสหกิจศึกษาตามวันและเวลาที่กำหนด</p> <p>ลักษณะงานสหกิจศึกษา ( ในส่วนของนักศึกษาที่ไปปฏิบัติการในสถานประกอบการ)<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 1. เสมือนหนึ่งเป็นพนักงานชั่วคราว<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 2. มีหน้าที่รับผิดชอบแน่นอน ( งานมีคุณภาพ)<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 3. ทำงานเต็มเวลา (Full Time)<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 4. ระยะเวลาการปฏิบัติงานเต็ม 1 ภาคการศึกษา ( ประมาณ 17 สัปดาห์)</p> </div> </div> </div> </div> </div> <!-- jQuery --> <script src="../vendor/jquery/jquery.min.js"></script> <!-- Bootstrap Core JavaScript --> <script src="../vendor/bootstrap/js/bootstrap.min.js"></script> <!-- Metis Menu Plugin JavaScript --> <script src="../vendor/metisMenu/metisMenu.min.js"></script> <!-- Morris Charts JavaScript --> <script src="../vendor/raphael/raphael.min.js"></script> <script src="../vendor/morrisjs/morris.min.js"></script> <script src="../data/morris-data.js"></script> <!-- Custom Theme JavaScript --> <script src="../dist/js/sb-admin-2.js"></script> </body> </html>
joesoftheart/Sahakit
pages/whit_sahakit.php
PHP
mit
16,811
var today = new Date(); var birthday = new Date(1981, 1, 16); var age = today.getTime() - birthday.getTime(); alert(age); // alert(age / 1000 / 60 / 60 / 24/ 365.25);
TheHagueUniversity/2017_1.1_programming-extended-course
wk2exercises/wk2exercise06/scripts/main.js
JavaScript
mit
172
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyCompany("Aliencube Community")] [assembly: AssemblyProduct("ConfigurationEncryptor")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("Aliencube")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
aliencube/Configuration-Encryptor
Documents/Properties/SharedAssemblyInfo.cs
C#
mit
1,179
# MAB ~/megauni/templates/en-us/mab/Club_Control_hearts.rb # SASS ~/megauni/templates/en-us/sass/Club_Control_hearts.sass # NAME Club_Control_hearts class Club_Control_hearts < Club_Control_Base_View def title 'The Hearts Club' end end # === Club_Control_hearts
da99/mu_mongo
views/Club_Control_hearts.rb
Ruby
mit
279
<?php class Default_ErrorController extends Zend_Controller_Action { public function errorAction() { $errors = $this->_getParam('error_handler'); if (!$errors || !$errors instanceof ArrayObject) { $this->view->message = 'You have reached the error page'; return; } switch ($errors->type) { case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE: case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER: case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION: // 404 error -- controller or action not found $this->getResponse()->setHttpResponseCode(404); $priority = Zend_Log::NOTICE; $this->view->message = 'Page not found'; break; default: // application error $this->getResponse()->setHttpResponseCode(500); $priority = Zend_Log::CRIT; $this->view->message = 'Application error'; break; } // Log exception, if logger available if ($log = $this->getLog()) { $log->log($this->view->message, $priority, $errors->exception); $log->log('Request Parameters', $priority, $errors->request->getParams()); } // conditionally display exceptions if ($this->getInvokeArg('displayExceptions') == true) { $this->view->exception = $errors->exception; } $this->view->request = $errors->request; } public function getLog() { $bootstrap = $this->getInvokeArg('bootstrap'); if (!$bootstrap->hasResource('Log')) { return false; } $log = $bootstrap->getResource('Log'); return $log; } }
scottyadean/socialWorks
application/modules/default/controllers/ErrorController.php
PHP
mit
1,879
/* * Datagrid.js */ function dg_send(url, grid, form, page, tamano, orderby, orderdirection) { var oForm = $("#"+form); var oGrid = $("#"+grid); var oLoader = $("#loader_"+grid); $('#Form_'+grid+'_page').val(page); $('#Form_'+grid+'_tamano').val(tamano); $('#Form_'+grid+'_orderby').val(orderby); $('#Form_'+grid+'_orderdirection').val(orderdirection); $(oLoader).width($(oGrid).width()) $(oLoader).height($(oGrid).height()) jQuery(oLoader).show(); $.ajax({ type: "POST", url: Routing.generate(url), data: ($(oForm).serialize()+'&datagrid='+grid), success: function(data){ data = data.replace(/^\s*|\s*$/g,""); $(oGrid).html(data); }, error: function(XMLHttpRequest, textStatus, errorThrown){ jQuery(oLoader).hide(); $("#dialog-modal").html("Error: "+XMLHttpRequest.status + ' ' + XMLHttpRequest.statusText); $("#dialog-modal").dialog("open"); } }); } function dg_delitem(urlreload, urldelete, grid, form, deletekey) { if (confirm("¿Está seguro que desea eliminar?")) { var oForm = $("#"+form); var oGrid = $("#"+grid); var oLoader = $("#loader_"+grid); $('#Form_'+grid+'_deletekey').val(deletekey); $(oLoader).width($(oGrid).width()) $(oLoader).height($(oGrid).height()) jQuery(oLoader).show(); $.ajax({ type: "POST", url: Routing.generate(urldelete), data: $(oForm).serialize(), success: function(data){ data = data.replace(/^\s*|\s*$/g,""); if(data == 'OK'){ dg_reload(urlreload, grid, form); }else{ jQuery(oLoader).hide(); $("#dialog-modal").html(data); $("#dialog-modal").dialog("open"); } }, error: function(XMLHttpRequest, textStatus, errorThrown){ jQuery(oLoader).hide(); $("#dialog-modal").html("Error: "+XMLHttpRequest.status + ' ' + XMLHttpRequest.statusText); $("#dialog-modal").dialog("open"); } }); } } function dg_reload(url, grid, form) { dg_send(url, grid, form, $('#Form_'+grid+'_page').val(), $('#Form_'+grid+'_tamano').val(), $('#Form_'+grid+'_orderby').val(), $('#Form_'+grid+'_orderdirection').val() ); }
wiccano/Symfony2-SoftwareFreedomDay2012
src/Admin/DashboardBundle/Resources/public/js/components/datagrid.js
JavaScript
mit
2,133
"use strict"; exports.buttonEvent = function(id) { return function(cb) { return function() { var el = document.getElementById(id); el.addEventListener('click', function(ev) { cb(); }); } }; }; exports.keydownEvent = function(el) { return function(cb) { return function() { window.addEventListener('keydown', function(ev) { cb(ev)(); }); } }; }; exports.resizeEvent = function(cb) { return function() { var resizeDelay = 250; // ms delay before running resize logic var resizeTimeout = null; var throttled = function() { if (resizeTimeout) { clearTimeout(resizeTimeout); } resizeTimeout = setTimeout(function() { resizeTimeout = null; cb(exports.windowInnerSize())(); }, resizeDelay); }; window.addEventListener('resize', throttled, false); }; }; exports.windowInnerSize = function() { var w = window.innerWidth; var h = window.innerHeight; return { width: w, height: h }; }; exports.setWindow = function(k) { return function(v) { return function() { window[k] = v; }; }; }; exports.setElementContents = function(el) { return function(html) { return function() { el.innerHTML = html; }; }; }; var debugDivId = "debugDiv"; exports.initDebugDiv = function(radius) { return function() { var view = document.getElementById("browser"); var div = document.getElementById(debugDivId); if (!div) { div = document.createElement("div"); view.appendChild(div); } div.id = debugDivId; div.style['position'] = "relative"; div.style['left'] = "0.0"; div.style['top'] = "0.0"; div.style['border-radius'] = "50%"; div.style['width'] = (radius * 2.0) + "px"; div.style['height'] = (radius * 2.0) + "px"; div.style['z-index'] = "100"; div.style['backgroundColor'] = "red"; div.style['pointer-events'] = "none"; div.style['display'] = "inline-block"; div.style['visibility'] = "hidden"; div.dataset.radius = radius; return div; }; }; var getDebugDiv = function() { var div = document.getElementById(debugDivId); if (!div) { return initDebugDiv(10.0)(); } else { return div; } }; exports.setDebugDivVisibility = function(s) { return function() { var div = getDebugDiv(); div.style['visibility'] = s; }; }; exports.setDebugDivPoint = function(p) { return function() { var div = getDebugDiv(); var r = div.dataset.radius | 1.0; var x = p.x - r; var y = p.y - r * 2.0; // var y = p.y; div.style['left'] = x + "px"; div.style['top'] = y + "px"; }; };
chfi/purescript-genetics-browser
src/Genetics/Browser/UI.js
JavaScript
mit
2,967
<?php // There's no way the below can be a complete whitelist - just to be clear ;) $real_url_endings = array( 'jpg', 'png', 'jpeg', 'js', 'zip', 'mp4', 'mp3', 'css', 'json', 'xml', 'html', 'gif' ); $path = urldecode(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)); $ext = pathinfo($path, PATHINFO_EXTENSION); if(in_array($ext, $real_url_endings) || ($path !== '/' && file_exists($_SERVER['DOCUMENT_ROOT'] . ltrim($path, "/")))){ // let the PHP server handle this return false; }else{ if($ext === "php"){ if(function_exists('http_response_code')){ http_response_code(403); }else{ header(sprintf('%s %s %s',$_SERVER['SERVER_PROTOCOL'], '403', 'Forbidden')); } echo "</h2>Jollof - Forbidden</h2>"; exit; } /*file_put_contents("php://stdout", sprintf("[%s] %s:%s [%s]: %sn", date("D M j H:i:s Y"), $_SERVER['REMOTE_ADDR'], $_SERVER['REMOTE_PORT'], "", $_SERVER['REQUEST_URI']));*/ require_once __DIR__ . '/public/index.php'; } ?>
isocroft/Jollof
raw.router.php
PHP
mit
1,010
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Sunglasses { class Program { static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); Console.WriteLine("{0}{1}{2}", new string('*', 2*n), new string(' ', n), new string('*', 2 * n)); for (int i = 1; i <= n - 2; i++) { Console.Write("*"); Console.Write(new string('/', (2*n) - 2)); Console.Write("*"); int middle = (n - 1) / 2 ; if (i == middle) { Console.Write(new string('|', n)); } else { Console.Write(new string(' ', n)); } Console.Write("*"); Console.Write(new string('/', (2 * n) - 2)); Console.Write("*"); Console.WriteLine(); } Console.WriteLine("{0}{1}{2}", new string('*', 2 * n), new string(' ', n), new string('*', 2 * n)); } } }
Shtereva/Fundamentals-with-CSharp
Draw-with-loops/Sunglasses/Program.cs
C#
mit
1,162
package com.wordsaretoys.quencher.common; import android.app.Activity; import android.content.res.Resources; import android.os.Bundle; import android.preference.Preference; import android.preference.Preference.OnPreferenceChangeListener; import android.preference.PreferenceFragment; import android.view.View; import android.widget.Toast; import com.wordsaretoys.quencher.R; public class SettingsActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); View view = getLayoutInflater().inflate(R.layout.settings_main, null); setContentView(view); getActionBar().setTitle(R.string.prefsTitle); } public static class SettingsFragment extends PreferenceFragment { public SettingsFragment() {} @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); Resources res = getResources(); // set up range checks for preferences Preference tuningReference = findPreference("pref_tuning_reference"); tuningReference.setOnPreferenceChangeListener( new RangeCheckListener( 261.63f, 523.25f, res.getString(R.string.prefsTuningReferenceRange))); Preference tuningFrequency = findPreference("pref_tuning_frequency"); tuningFrequency.setOnPreferenceChangeListener( new RangeCheckListener( 220, 880, res.getString(R.string.prefsTuningFrequencyRange))); Preference audioLatency = findPreference("pref_audio_latency"); audioLatency.setOnPreferenceChangeListener( new RangeCheckListener( 1, 1000, res.getString(R.string.prefsAudioLatencyRange))); } class RangeCheckListener implements OnPreferenceChangeListener { String errMsg; float lower; float upper; /** * ctor * * @param l lower bound * @param h upper bound * @param msg error message if range check fails */ public RangeCheckListener(float l, float h, String msg) { lower = l; upper = h; errMsg = msg; } @Override public boolean onPreferenceChange(Preference preference, Object newValue) { float f = -1; try { f = Float.valueOf( (String) newValue); } catch (Exception e) { f = -1; } if (f < lower || f > upper) { Toast.makeText(getActivity(), errMsg, Toast.LENGTH_LONG).show(); return false; } return true; } } } }
wordsaretoys/quencher
app/src/main/java/com/wordsaretoys/quencher/common/SettingsActivity.java
Java
mit
2,489
window.appConf = { author: 'React Drive CMS', dashboardId: '1-on_GfmvaEcOk7HcWfKb8B6KFRv166RkLN2YmDEtDn4', sendContactMessageUrlId: 'AKfycbyL4vW1UWs4mskuDjLoLmf1Hjan1rTLEca6i2Hi2H_4CtKUN84d', shortname: 'easydrivecms', root: 'react-drive-cms', }
misterfresh/react-drive-cms
conf.js
JavaScript
mit
274
using System; using System.Diagnostics.CodeAnalysis; using System.Net.Http; using Microsoft.Owin; using Microsoft.Owin.Security; using OAuthClientExt.MailRu.Provider; using OAuthClientExt.VKontakte; using OAuthClientExt.VKontakte.Provider; namespace OAuthClientExt.MailRu { /// <summary> /// Configuration options for <see cref="VkAuthenticationMiddleware"/> /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "VkontakteMiddleware.VkAuthenticationOptions.set_Caption(System.String)", Justification = "Not localizable.")] public class MailRuAuthenticationOptions : AuthenticationOptions { /// <summary> /// Initializes a new <see cref="VkAuthenticationOptions"/> /// </summary> public MailRuAuthenticationOptions() : base("MailRu") { Caption = "MailRu"; CallbackPath = new PathString("/signin-mailru"); AuthenticationMode = AuthenticationMode.Passive; Scope = ""; Version = "5.31"; BackchannelTimeout = TimeSpan.FromSeconds(60); } /// <summary> /// Gets or sets the appId /// </summary> public string AppId { get; set; } /// <summary> /// Gets or sets the app secret /// </summary> public string AppSecret { get; set; } /// <summary> /// Gets or sets the a pinned certificate validator to use to validate the endpoints used /// in back channel communications belong to Vkontakte. /// </summary> /// <value> /// The pinned certificate validator. /// </value> /// <remarks>If this property is null then the default certificate checks are performed, /// validating the subject name and if the signing chain is a trusted party.</remarks> public ICertificateValidator BackchannelCertificateValidator { get; set; } /// <summary> /// Gets or sets timeout value in milliseconds for back channel communications with Vkontakte. /// </summary> /// <value> /// The back channel timeout in milliseconds. /// </value> public TimeSpan BackchannelTimeout { get; set; } /// <summary> /// The HttpMessageHandler used to communicate with Vkontakte. /// This cannot be set at the same time as BackchannelCertificateValidator unless the value /// can be downcast to a WebRequestHandler. /// </summary> public HttpMessageHandler BackchannelHttpHandler { get; set; } /// <summary> /// Get or sets the text that the user can display on a sign in user interface. /// </summary> public string Caption { get { return Description.Caption; } set { Description.Caption = value; } } /// <summary> /// The request path within the application's base path where the user-agent will be returned. /// The middleware will process this request when it arrives. /// Default value is "/signin-vkontakte". /// </summary> public PathString CallbackPath { get; set; } /// <summary> /// Gets or sets the name of another authentication middleware which will be responsible for actually issuing a user <see cref="System.Security.Claims.ClaimsIdentity"/>. /// </summary> public string SignInAsAuthenticationType { get; set; } /// <summary> /// Gets or sets the <see cref="IVkAuthenticationProvider"/> used to handle authentication events. /// </summary> public IMailRuAuthenticationProvider Provider { get; set; } /// <summary> /// Gets or sets the type used to secure data handled by the middleware. /// </summary> public ISecureDataFormat<AuthenticationProperties> StateDataFormat { get; set; } /// <summary> /// Gets or sets the site redirect url after login /// </summary> public string StoreState { get; set; } /// <summary> /// A list of permissions to request. /// Can be something like that "audio,video,pages" and etc. More info http://vk.com/dev/permissions /// </summary> public string Scope { get; set; } /// <summary> /// Get or set vk.com api version. /// </summary> public string Version { get; set; } } }
unby/MTAHR
OAuthClientExt/MailRu/MailRuAuthenticationOptions.cs
C#
mit
4,495
using System; using System.IO; using Serenity.IO; #if !COREFX using System.Drawing; using System.Drawing.Imaging; #endif namespace Serenity.Web { public class UploadProcessor { #if !COREFX public UploadProcessor() { ThumbBackColor = Color.Empty; } public int ThumbWidth { get; set; } public int ThumbHeight { get; set; } public Color ThumbBackColor { get; set; } public ImageScaleMode ThumbScaleMode { get; set; } public int ThumbQuality { get; set; } public string ThumbFile { get; private set; } public string ThumbUrl { get; private set; } public int ImageWidth { get; private set; } public int ImageHeight { get; private set; } #endif public ImageCheckResult CheckResult { get; private set; } public string ErrorMessage { get; private set; } public long FileSize { get; private set; } public string FilePath { get; private set; } public string FileUrl { get; private set; } public bool IsImage { get; private set; } private bool IsImageExtension(string extension) { return extension.EndsWith(".jpg") || extension.EndsWith(".jpeg") || extension.EndsWith(".png") || extension.EndsWith(".gif"); } private bool IsDangerousExtension(string extension) { return extension.EndsWith(".exe") || extension.EndsWith(".bat") || extension.EndsWith(".cmd") || extension.EndsWith(".dll") || extension.EndsWith(".jar") || extension.EndsWith(".jsp") || extension.EndsWith(".htaccess") || extension.EndsWith(".htpasswd") || extension.EndsWith(".lnk") || extension.EndsWith(".vbs") || extension.EndsWith(".vbe") || extension.EndsWith(".aspx") || extension.EndsWith(".ascx") || extension.EndsWith(".config") || extension.EndsWith(".com") || extension.EndsWith(".asmx") || extension.EndsWith(".asax") || extension.EndsWith(".compiled") || extension.EndsWith(".php"); } public bool ProcessStream(Stream fileContent, string extension) { extension = extension.TrimToEmpty().ToLowerInvariant(); if (IsDangerousExtension(extension)) { ErrorMessage = "Unsupported file extension!"; return false; } CheckResult = ImageCheckResult.InvalidImage; ErrorMessage = null; #if !COREFX ImageWidth = 0; ImageHeight = 0; #endif IsImage = false; var success = false; var temporaryPath = UploadHelper.TemporaryPath; Directory.CreateDirectory(temporaryPath); TemporaryFileHelper.PurgeDirectoryDefault(temporaryPath); string baseFileName = System.IO.Path.Combine(temporaryPath, Guid.NewGuid().ToString("N")); try { try { if (IsImageExtension(extension)) { #if COREFX IsImage = true; success = true; FilePath = baseFileName + extension; fileContent.Seek(0, SeekOrigin.Begin); using (FileStream fs = new FileStream(FilePath, FileMode.Create)) fileContent.CopyTo(fs); #else success = ProcessImageStream(fileContent, extension); #endif } else { FilePath = baseFileName + extension; fileContent.Seek(0, SeekOrigin.Begin); using (FileStream fs = new FileStream(FilePath, FileMode.Create)) fileContent.CopyTo(fs); success = true; } } catch (Exception ex) { ErrorMessage = ex.Message; success = false; return success; } } finally { if (!success) { #if !COREFX if (!ThumbFile.IsNullOrEmpty()) TemporaryFileHelper.TryDelete(ThumbFile); #endif if (!FilePath.IsNullOrEmpty()) TemporaryFileHelper.TryDelete(FilePath); } fileContent.Dispose(); } return success; } #if !COREFX private bool ProcessImageStream(Stream fileContent, string extension) { Image image = null; var imageChecker = new ImageChecker(); CheckResult = imageChecker.CheckStream(fileContent, true, out image); try { FileSize = imageChecker.DataSize; ImageWidth = imageChecker.Width; ImageHeight = imageChecker.Height; if (CheckResult != ImageCheckResult.JPEGImage && CheckResult != ImageCheckResult.GIFImage && CheckResult != ImageCheckResult.PNGImage) { ErrorMessage = imageChecker.FormatErrorMessage(CheckResult); return false; } else { IsImage = true; extension = (CheckResult == ImageCheckResult.PNGImage ? ".png" : (CheckResult == ImageCheckResult.GIFImage ? ".gif" : ".jpg")); var temporaryPath = UploadHelper.TemporaryPath; Directory.CreateDirectory(temporaryPath); TemporaryFileHelper.PurgeDirectoryDefault(temporaryPath); string baseFileName = System.IO.Path.Combine(temporaryPath, Guid.NewGuid().ToString("N")); FilePath = baseFileName + extension; fileContent.Seek(0, SeekOrigin.Begin); using (FileStream fs = new FileStream(FilePath, FileMode.Create)) fileContent.CopyTo(fs); if (ThumbWidth > 0 || ThumbHeight > 0) { using (System.Drawing.Image thumbImage = ThumbnailGenerator.Generate(image, ThumbWidth, ThumbHeight, ThumbScaleMode, ThumbBackColor)) { ThumbFile = baseFileName + "_t.jpg"; if (ThumbQuality != 0) { var p = new System.Drawing.Imaging.EncoderParameters(1); p.Param[0] = new EncoderParameter(Encoder.Quality, ThumbQuality); ImageCodecInfo jpegCodec = null; ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders(); // Find the correct image codec for (int i = 0; i < codecs.Length; i++) if (codecs[i].MimeType == "image/jpeg") jpegCodec = codecs[i]; thumbImage.Save(ThumbFile, jpegCodec, p); } else thumbImage.Save(ThumbFile, System.Drawing.Imaging.ImageFormat.Jpeg); ThumbHeight = thumbImage.Width; ThumbWidth = thumbImage.Height; } } return true; } } finally { if (image != null) { image.Dispose(); image = null; } } } #endif } }
dfaruque/Serenity
Serenity.Web/Upload/UploadProcessor.cs
C#
mit
8,413
package org.whiskeysierra.process; import com.google.common.io.ByteSource; import java.io.IOException; import java.nio.file.Path; import java.util.Map; // TODO specify IOException as exception of choice?! public interface ManagedProcess { // TODO find better name ManagedProcess setExecutable(Path executable); // TODO find better name ManagedProcess setCommand(String command); // TODO specify defensive-copy? ManagedProcess parameterize(Object... arguments); // TODO specify defensive-copy? ManagedProcess parameterize(Iterable<?> arguments); ManagedProcess in(Path directory); ManagedProcess with(String variable, String value); ManagedProcess with(Map<String, String> properties); // TODO IAE on illegal combinations (input -> redirect to, output -> redirect from, output -> stderr) ManagedProcess redirect(Stream stream, Redirection redirect); ManagedProcess allow(int exitValue); // TODO specify whether defensive copy or not ManagedProcess allow(int... exitValues); RunningProcess call() throws IOException; ByteSource read() throws IOException; }
whiskeysierra/primal
src/main/java/org/whiskeysierra/process/ManagedProcess.java
Java
mit
1,143
module.exports = flatten([ require("./base/dualfilter"), require("./base/filter"), require("./base/mirrorBlocks"), require("./base/overlayMask"), require("./base/split"), require("./base/splitMask"), require("./colourset/lerp"), require("./colourset/distinct"), require("./colourset/chunks"), require("./colourset/alpha"), require("./extras/swatch"), require("./extras/text"), require("./filter/bevel"), require("./filter/disolve"), require("./filter/roughen"), require("./filter/sharpen"), require("./filter/splash"), require("./lines/straight"), require("./lines/curve"), require("./lines/scribble"), require("./mask/halfmask"), require("./overlay/lines"), require("./overlay/network"), require("./overlay/shapes"), require("./overlay/sparkles"), require("./pallete/monochrome"), require("./pallete/hightlightAndMidtone"), require("./pallete/bicolor"), require("./pointset/static"), require("./pointset/linear"), require("./pointset/circular"), require("./pointset/grid"), require("./pointset/spiral"), require("./pointset/tree"), require("./shapes/polygon"), require("./shapes/stars"), require("./shapes/ring"), require("./shapes/circle"), require("./simple/blockColor"), require("./simple/blockOverlay"), require("./spacial/radial"), require("./spacial/chaos"), require("./spacial/linear"), require("./tiles/squares"), require("./tiles/triangles"), ]) function flatten( m ){ var retval = []; for ( var id in m ){ if ( m[id].push ){ retval = retval.concat(m[id]); }else{ retval.push(m[id]); } } return retval; }
chris-j-major/unique-wallpaper
parts/all.js
JavaScript
mit
1,651
namespace MockingData.Generators.Extensions.Interfaces { public interface IPersonInitiator : IExtensionInitiator { IPersonGenerator Create(); } }
JohanOhlin/MockingData
src/MockingData/Generators/Extensions/Interfaces/IPersonInitiator.cs
C#
mit
169
using System; namespace Mail.Library.Configuration { /// <summary> /// Section /// </summary> [AttributeUsage(AttributeTargets.Class)] public class IniSectionAttribute : Attribute { /// <summary> /// Section name. /// Valid characters: alphabet, numeric, underscore, space. /// </summary> public string Name { get; set; } /// <summary> /// Additional comment /// </summary> public string Comment { get; set; } /// <summary> /// Initialize section attribute /// </summary> /// <param name="name">Section name, valid characters: alphabet, numeric, underscore, space.</param> public IniSectionAttribute(string name) { if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name)); Name = name; } } }
fakhrulhilal/MailClient
Mail.Library/Configuration/IniSectionAttribute.cs
C#
mit
785
# Copyright (c) 2014 Sean Vig # Copyright (c) 2014, 2019 zordsdavini # Copyright (c) 2014 Alexandr Kriptonov # Copyright (c) 2014 Tycho Andersen # # 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. import imaplib import re from libqtile.log_utils import logger from libqtile.widget import base class GmailChecker(base.ThreadPoolText): """A simple gmail checker. If 'status_only_unseen' is True - set 'fmt' for one argument, ex. 'unseen: {0}'""" orientations = base.ORIENTATION_HORIZONTAL defaults = [ ("update_interval", 30, "Update time in seconds."), ("username", None, "username"), ("password", None, "password"), ("email_path", "INBOX", "email_path"), ("display_fmt", "inbox[{0}],unseen[{1}]", "Display format"), ("status_only_unseen", False, "Only show unseen messages"), ] def __init__(self, **config): base.ThreadPoolText.__init__(self, "", **config) self.add_defaults(GmailChecker.defaults) def poll(self): self.gmail = imaplib.IMAP4_SSL('imap.gmail.com') self.gmail.login(self.username, self.password) answer, raw_data = self.gmail.status(self.email_path, '(MESSAGES UNSEEN)') if answer == "OK": dec = raw_data[0].decode() messages = int(re.search(r'MESSAGES\s+(\d+)', dec).group(1)) unseen = int(re.search(r'UNSEEN\s+(\d+)', dec).group(1)) if(self.status_only_unseen): return self.display_fmt.format(unseen) else: return self.display_fmt.format(messages, unseen) else: logger.exception( 'GmailChecker UNKNOWN error, answer: %s, raw_data: %s', answer, raw_data) return "UNKNOWN ERROR"
ramnes/qtile
libqtile/widget/gmail_checker.py
Python
mit
2,825
<?php namespace Horus\SiteBundle\Repository; use Doctrine\ORM\EntityRepository; use Horus\SiteBundle\Entity\Category; /** * Class CartRepository * @package Horus\SiteBundle\Repository */ class CartRepository extends EntityRepository { }
HorusCMF/Shop
src/Horus/SiteBundle/Repository/CartRepository.php
PHP
mit
243
using CharacterMap.Core; using CharacterMap.Models; using System; using System.Collections.Generic; using Windows.UI.Xaml.Controls; namespace CharacterMap.Provider { public class VBDevProvider : DevProviderBase { public VBDevProvider(CharacterRenderingOptions r, Character c) : base(r, c) { DisplayName = "VB (UWP)"; } protected override DevProviderType GetDevProviderType() => DevProviderType.VisualBasic; protected override IReadOnlyList<DevOption> OnGetContextOptions() => Inflate(); protected override IReadOnlyList<DevOption> OnGetOptions() => Inflate(); IReadOnlyList<DevOption> Inflate() { var v = Options.Variant; var c = Character; bool hasSymbol = FontFinder.IsSystemSymbolFamily(v) && Enum.IsDefined(typeof(Symbol), (int)c.UnicodeIndex); var hex = c.UnicodeIndex.ToString("x4").ToUpper(); string pathIconData = GetOutlineGeometry(c, Options); string glyph = c.UnicodeIndex > 0xFFFF ? $"ChrW(&H{$"{c.UnicodeIndex:x8}".ToUpper()})" : $"ChrW(&H{hex})"; var ops = new List<DevOption>() { new ("TxtXamlCode/Header", glyph), new ("TxtFontIcon/Header", $"New FontIcon With {{ .FontFamily = New Windows.UI.Xaml.Media.FontFamily(\"{v?.XamlFontSource}\"), .Glyph = {glyph} }}"), }; if (!string.IsNullOrWhiteSpace(pathIconData)) ops.Add(new DevOption("TxtPathIcon/Text", $"New PathIcon With {{.Data = TryCast(Windows.UI.Xaml.Markup.XamlBindingHelper.ConvertValue(GetType(Windows.UI.Xaml.Media.Geometry), \"{pathIconData}\"), Windows.UI.Xaml.Media.Geometry), .HorizontalAlignment = HorizontalAlignment.Center, .VerticalAlignment = VerticalAlignment.Center}}", supportsTypography: true)); if (hasSymbol) ops.Add(new DevOption("TxtSymbolIcon/Header", $"New SymbolIcon With {{ .Symbol = Symbol.{(Symbol)c.UnicodeIndex} }}")); return ops; } } }
EdiWang/UWP-CharacterMap
CharacterMap/CharacterMap/Provider/VBDevProvider.cs
C#
mit
2,093
package fi.mkuokkanen.webproto.quarkus; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; @Path("/test") public class QResource { @Path("/hello") @GET @Produces(MediaType.TEXT_PLAIN) public String getHello() { return "hello world"; } @Path("/json") @GET @Produces(MediaType.APPLICATION_JSON) public Person getJson(@DefaultValue("Matti") @QueryParam("name") String name, @DefaultValue("36") @QueryParam("age") int age) { return new Person(name, age); } }
mkuokkanen/rest-freemarker-protos
quarkus/src/main/java/fi/mkuokkanen/webproto/quarkus/QResource.java
Java
mit
667
using System; namespace AltairStudios.Core.Orm { public class EncryptedAttribute : TemplatizeAttribute { protected EncryptationType method; public EncryptationType Method { get { return method; } set { method = value; } } public EncryptedAttribute() : this(EncryptationType.MD5) { } public EncryptedAttribute(EncryptationType type) { this.method = type; this.templatize = true; } } }
altairstudios/AltairStudios.Core
AltairStudios.Core/Orm/EncryptedAttribute.cs
C#
mit
437
def gpio_init(pin, output): try: with open(f"/sys/class/gpio/gpio{pin}/direction", 'wb') as f: f.write(b"out" if output else b"in") except Exception as e: print(f"Failed to set gpio {pin} direction: {e}") def gpio_set(pin, high): try: with open(f"/sys/class/gpio/gpio{pin}/value", 'wb') as f: f.write(b"1" if high else b"0") except Exception as e: print(f"Failed to set gpio {pin} value: {e}")
commaai/openpilot
common/gpio.py
Python
mit
432
'use strict'; angular.module('myApp').directive('loginDirective',function(){ return{ templateUrl:'partials/tpl/login.tpl.html' } });
jaygood/angular-sessions
app/js/directives/loginDrc.js
JavaScript
mit
145
# vim: fileencoding=utf-8 """ AppHtml settings @author Toshiya NISHIO(http://www.toshiya240.com) """ defaultTemplate = { '1) 小さいボタン': '${badgeS}', '2) 大きいボタン': '${badgeL}', '3) テキストのみ': '${textonly}', "4) アイコン付き(小)": u"""<span class="appIcon"><img class="appIconImg" height="60" src="${icon60url}" style="float:left;margin: 0px 15px 15px 5px;"></span> <span class="appName"><strong><a href="${url}" target="itunes_store">${name}</a></strong></span><br> <span class="appCategory">カテゴリ: ${category}</span><br> <span class="badgeS" style="display:inline-block; margin:6px">${badgeS}</span><br style="clear:both;"> """, "5) アイコン付き(大)": u"""<span class="appIcon"><img class="appIconImg" height="100" src="${icon100url}" style="float:left;;margin: 0px 15px 15px 5px;"></span> <span class="appName"><strong><a href="${url}" target="itunes_store">${name}</a></strong></span><br> <span class="appCategory">カテゴリ: ${category}</span><br> <span class="badgeL" style="display:inline-block; margin:4px">${badgeL}</span><br style="clear:both;"> """ } settings = { 'phg': "", 'cnt': 8, 'scs': { 'iphone': 320, 'ipad': 320, 'mac': 480 }, 'template': { 'software': defaultTemplate, 'iPadSoftware': defaultTemplate, 'macSoftware': defaultTemplate, 'song': defaultTemplate, 'album': defaultTemplate, 'movie': defaultTemplate, 'ebook': defaultTemplate } }
connect1ngdots/AppHtmlME
AppHtmlME.workflow/Scripts/apphtml_settings.py
Python
mit
1,540
import { createLogger, stdSerializers } from "bunyan"; import { resolve } from 'path'; export function makeLogger(ledeHome, level = "info") { return createLogger({ name: "LedeLogger", serializers: { err: stdSerializers.err }, streams: [ { level: level, stream: process.stdout }, { level: "debug", path: resolve(ledeHome, "logs", "lede.log") } ] }) }
tbtimes/ledeTwo
src/cli/logger.ts
TypeScript
mit
437
using System; namespace Ack.Web.Models.WebApi.Errors { public class Error { public string Message { get; set; } } }
rbwestmoreland/ACK
src/Ack.Web/Models/WebApi/Errors/Error.cs
C#
mit
139
function Rook(loc, isWhite, asset){ Piece.call(this, loc, isWhite, asset); this.name = "Rook"; } Rook.prototype = Object.create(Piece.prototype); Rook.prototype.constructor = Rook; Rook.prototype.getValidMoveSet = function(board) { var result = []; var currentX = this.loc.x+1; var currentY = this.loc.y; var currentSpeculation = new Point(currentX, currentY); //moving right while(board.inBounds(currentSpeculation) && !board.locOccupied(currentSpeculation)){ result.push(currentSpeculation); currentX += 1; currentSpeculation = new Point(currentX, currentY); } var cap = board.getPieceAt(currentSpeculation); if(cap){ if(cap.isWhite() !== this.white){ result.push(currentSpeculation); } } //moving left currentX = this.loc.x-1; currentY = this.loc.y; currentSpeculation = new Point(currentX, currentY); while(board.inBounds(currentSpeculation) && !board.locOccupied(currentSpeculation)){ result.push(currentSpeculation); currentX -= 1; currentSpeculation = new Point(currentX, currentY); } cap = board.getPieceAt(currentSpeculation); if(cap){ if(cap.isWhite() !== this.white){ result.push(currentSpeculation); } } //moving up currentX = this.loc.x; currentY = this.loc.y-1; currentSpeculation = new Point(currentX, currentY); while(board.inBounds(currentSpeculation) && !board.locOccupied(currentSpeculation)){ result.push(currentSpeculation); currentY -= 1; currentSpeculation = new Point(currentX, currentY); } cap = board.getPieceAt(currentSpeculation); if(cap){ if(cap.isWhite() !== this.white){ result.push(currentSpeculation); } } //moving down currentX = this.loc.x; currentY = this.loc.y+1; currentSpeculation = new Point(currentX, currentY); while(board.inBounds(currentSpeculation) && !board.locOccupied(currentSpeculation)){ result.push(currentSpeculation); currentY += 1; currentSpeculation = new Point(currentX, currentY); } cap = board.getPieceAt(currentSpeculation); if(cap){ if(cap.isWhite() !== this.white){ result.push(currentSpeculation); } } return result; };
xLeachimx/ChessCast
webapp/cast-receiver/javascript/rook.js
JavaScript
mit
2,168
var dir_72c031272133aec1d916095cf903ecf1 = [ [ "HTTP", "dir_7e5fd1ff9265fa651882e3ad4d93cc88.html", "dir_7e5fd1ff9265fa651882e3ad4d93cc88" ], [ "Module", "dir_10705d0e5b4538c0e815cbe3b6497638.html", "dir_10705d0e5b4538c0e815cbe3b6497638" ] ];
SaltAPI/SaltAPI.github.io
Doxygen/html/dir_72c031272133aec1d916095cf903ecf1.js
JavaScript
mit
250
#pragma once #include <utki/span.hpp> #include <r4/vector.hpp> #include <morda/render/vertex_buffer.hpp> #include "opengl_buffer.hpp" namespace morda{ namespace render_opengl2{ class vertex_buffer : public morda::vertex_buffer, public opengl_buffer{ public: const GLint numComponents; const GLenum type; vertex_buffer(utki::span<const r4::vector4<float>> vertices); vertex_buffer(utki::span<const r4::vector3<float>> vertices); vertex_buffer(utki::span<const r4::vector2<float>> vertices); vertex_buffer(utki::span<const float> vertices); vertex_buffer(const vertex_buffer&) = delete; vertex_buffer& operator=(const vertex_buffer&) = delete; private: void init(GLsizeiptr size, const GLvoid* data); }; }}
igagis/morda
tests/harness/opengl2/morda/render/opengl2/vertex_buffer.hpp
C++
mit
732
#!/usr/bin/env python3 import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "houseofdota.production_settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
lucashanke/houseofdota
manage.py
Python
mit
266
<?php /** * This file is part of the Taco Projects. * * Copyright (c) 2004, 2013 Martin Takáč (http://martin.takac.name) * * For the full copyright and license information, please view * the file LICENCE that was distributed with this source code. * * PHP version 5.3 * * @author Martin Takáč (martin@takac.name) */ require_once 'phing/Task.php'; /** * @package phing.tasks.taco */ class TacoAutoloadTask extends Task { /** * Autoload file. * @var PhingFile */ protected $file; /** * Whether to log returned output as MSG_INFO instead of MSG_VERBOSE * @var boolean */ protected $logOutput = false; /** * Logging level for status messages * @var integer */ protected $logLevel = Project::MSG_INFO; /** * Set level of log messages generated (default = verbose) * * @param string $level Log level * * @return void */ public function setLevel($level) { switch ($level) { case 'error': $this->logLevel = Project::MSG_ERR; break; case 'warning': $this->logLevel = Project::MSG_WARN; break; case 'info': $this->logLevel = Project::MSG_INFO; break; case 'verbose': $this->logLevel = Project::MSG_VERBOSE; break; case 'debug': $this->logLevel = Project::MSG_DEBUG; break; default: throw new BuildException( sprintf('Unknown log level "%s"', $level) ); } } /** * Specify the working directory for executing this command. * @param PhingFile $dir */ function setFile(PhingFile $dir) { $this->file = $dir; } /** * executes the Composer task */ public function main() { if (empty($this->file) || ! (string)$this->file->getCanonicalFile()) { throw new BuildException("'" . (string) $this->file . "' is not set."); } require_once $this->file->getCanonicalFile(); } }
tacoberu/phing-tasks
source/main/tasks/taco/TacoAutoloadTask.php
PHP
mit
2,055
class UsersTakeOver < ActiveRecord::Migration def change add_column :droom_invitations, :user_id, :integer add_column :droom_memberships, :user_id, :integer add_column :droom_personal_folders, :user_id, :integer add_column :droom_dropbox_documents, :user_id, :integer add_index :droom_invitations, :user_id add_index :droom_memberships, :user_id add_index :droom_personal_folders, :user_id add_index :droom_dropbox_documents, :user_id user_ids_by_person = Droom::Person.all.each_with_object({}) do |person, carrier| carrier[person.id] = person.user.id if person.user end Droom::Invitation.reset_column_information Droom::Invitation.all.each do |inv| inv.update_column :user_id, user_ids_by_person[inv.person_id] end Droom::Membership.reset_column_information Droom::Membership.all.each do |mem| mem.update_column :user_id, user_ids_by_person[mem.person_id] end Droom::PersonalFolder.reset_column_information Droom::PersonalFolder.all.each do |pf| pf.update_column :user_id, user_ids_by_person[pf.person_id] end Droom::DropboxDocument.reset_column_information Droom::DropboxDocument.all.each do |dd| dd.update_column :user_id, user_ids_by_person[dd.person_id] end end end
spanner/droom
db/migrate/20130627071938_users_take_over.rb
Ruby
mit
1,300
// Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <QApplication> #include "paymentserver.h" #include "guiconstants.h" #include "ui_interface.h" #include "util.h" #include <QByteArray> #include <QDataStream> #include <QDebug> #include <QFileOpenEvent> #include <QHash> #include <QLocalServer> #include <QLocalSocket> #include <QStringList> #if QT_VERSION < 0x050000 #include <QUrl> #endif using namespace boost; const int BITCOIN_IPC_CONNECT_TIMEOUT = 1000; // milliseconds const QString BITCOIN_IPC_PREFIX("PAPAFRANCESCOCoin:"); // // Create a name that is unique for: // testnet / non-testnet // data directory // static QString ipcServerName() { QString name("BitcoinQt"); // Append a simple hash of the datadir // Note that GetDataDir(true) returns a different path // for -testnet versus main net QString ddir(GetDataDir(true).string().c_str()); name.append(QString::number(qHash(ddir))); return name; } // // This stores payment requests received before // the main GUI window is up and ready to ask the user // to send payment. // static QStringList savedPaymentRequests; // // Sending to the server is done synchronously, at startup. // If the server isn't already running, startup continues, // and the items in savedPaymentRequest will be handled // when uiReady() is called. // bool PaymentServer::ipcSendCommandLine() { bool fResult = false; const QStringList& args = qApp->arguments(); for (int i = 1; i < args.size(); i++) { if (!args[i].startsWith(BITCOIN_IPC_PREFIX, Qt::CaseInsensitive)) continue; savedPaymentRequests.append(args[i]); } foreach (const QString& arg, savedPaymentRequests) { QLocalSocket* socket = new QLocalSocket(); socket->connectToServer(ipcServerName(), QIODevice::WriteOnly); if (!socket->waitForConnected(BITCOIN_IPC_CONNECT_TIMEOUT)) return false; QByteArray block; QDataStream out(&block, QIODevice::WriteOnly); out.setVersion(QDataStream::Qt_4_0); out << arg; out.device()->seek(0); socket->write(block); socket->flush(); socket->waitForBytesWritten(BITCOIN_IPC_CONNECT_TIMEOUT); socket->disconnectFromServer(); delete socket; fResult = true; } return fResult; } PaymentServer::PaymentServer(QApplication* parent) : QObject(parent), saveURIs(true) { // Install global event filter to catch QFileOpenEvents on the mac (sent when you click bitcoin: links) parent->installEventFilter(this); QString name = ipcServerName(); // Clean up old socket leftover from a crash: QLocalServer::removeServer(name); uriServer = new QLocalServer(this); if (!uriServer->listen(name)) qDebug() << tr("Cannot start PAPAFRANCESCOCoin: click-to-pay handler"); else connect(uriServer, SIGNAL(newConnection()), this, SLOT(handleURIConnection())); } bool PaymentServer::eventFilter(QObject *object, QEvent *event) { // clicking on bitcoin: URLs creates FileOpen events on the Mac: if (event->type() == QEvent::FileOpen) { QFileOpenEvent* fileEvent = static_cast<QFileOpenEvent*>(event); if (!fileEvent->url().isEmpty()) { if (saveURIs) // Before main window is ready: savedPaymentRequests.append(fileEvent->url().toString()); else emit receivedURI(fileEvent->url().toString()); return true; } } return false; } void PaymentServer::uiReady() { saveURIs = false; foreach (const QString& s, savedPaymentRequests) emit receivedURI(s); savedPaymentRequests.clear(); } void PaymentServer::handleURIConnection() { QLocalSocket *clientConnection = uriServer->nextPendingConnection(); while (clientConnection->bytesAvailable() < (int)sizeof(quint32)) clientConnection->waitForReadyRead(); connect(clientConnection, SIGNAL(disconnected()), clientConnection, SLOT(deleteLater())); QDataStream in(clientConnection); in.setVersion(QDataStream::Qt_4_0); if (clientConnection->bytesAvailable() < (int)sizeof(quint16)) { return; } QString message; in >> message; if (saveURIs) savedPaymentRequests.append(message); else emit receivedURI(message); }
PAPAFRANCESCOCoin/PAPAFRANCESCOCoin
src/qt/paymentserver.cpp
C++
mit
4,523
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2013.12.21 at 09:18:53 AM CST // package ca.ieso.reports.schema.daadequacy; import java.math.BigInteger; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.datatype.XMLGregorianCalendar; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element ref="{http://www.ieso.ca/schema}DocTitle"/> * &lt;element ref="{http://www.ieso.ca/schema}DocRevision"/> * &lt;element ref="{http://www.ieso.ca/schema}DocConfidentiality"/> * &lt;element ref="{http://www.ieso.ca/schema}CreatedAt"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "docTitle", "docRevision", "docConfidentiality", "createdAt" }) @XmlRootElement(name = "DocHeader") public class DocHeader { @XmlElement(name = "DocTitle", required = true) protected String docTitle; @XmlElement(name = "DocRevision", required = true) protected BigInteger docRevision; @XmlElement(name = "DocConfidentiality", required = true) protected DocConfidentiality docConfidentiality; @XmlElement(name = "CreatedAt", required = true) @XmlSchemaType(name = "dateTime") protected XMLGregorianCalendar createdAt; /** * Gets the value of the docTitle property. * * @return * possible object is * {@link String } * */ public String getDocTitle() { return docTitle; } /** * Sets the value of the docTitle property. * * @param value * allowed object is * {@link String } * */ public void setDocTitle(String value) { this.docTitle = value; } /** * Gets the value of the docRevision property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getDocRevision() { return docRevision; } /** * Sets the value of the docRevision property. * * @param value * allowed object is * {@link BigInteger } * */ public void setDocRevision(BigInteger value) { this.docRevision = value; } /** * Gets the value of the docConfidentiality property. * * @return * possible object is * {@link DocConfidentiality } * */ public DocConfidentiality getDocConfidentiality() { return docConfidentiality; } /** * Sets the value of the docConfidentiality property. * * @param value * allowed object is * {@link DocConfidentiality } * */ public void setDocConfidentiality(DocConfidentiality value) { this.docConfidentiality = value; } /** * Gets the value of the createdAt property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getCreatedAt() { return createdAt; } /** * Sets the value of the createdAt property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setCreatedAt(XMLGregorianCalendar value) { this.createdAt = value; } }
r24mille/IesoPublicReportBindings
src/main/java/ca/ieso/reports/schema/daadequacy/DocHeader.java
Java
mit
4,307
var flow = require('js-flow'), assert = require('assert'), tubes = require('evo-tubes'); describe('evo-states', function () { var TIMEOUT = 60000; var sandbox; beforeEach(function (done) { this.timeout(TIMEOUT); (sandbox = new tubes.Sandbox()) .add(new tubes.Environment({ nodes: 4 })) .add(new tubes.NeuronFactory()) .add(new tubes.Connector()) .add(new tubes.States()) .start(done); }); afterEach(function (done) { sandbox.cleanup(done); }); it('synchronize', function (done) { this.timeout(TIMEOUT); var connector = sandbox.res('evo-connector'); flow.steps() .next('clientsReady') .next(function (next) { flow.each([this.clients[0], this.clients[1]]) .keys() .do(function (index, client, next) { client.commit({ key: 'val' + index }, next); }) .run(next); }) .next(function (next) { this.waitForSync({ key: 'key' }, function (data, client, index) { return [0, 1].every(function (i) { var nodeVal = data.d[connector.clients[i].localId]; return nodeVal && nodeVal.d == 'val' + i; }); }, next); }) .with(sandbox.res('evo-states')) .run(done) }); });
evo-cloud/states
test/states-int-test.js
JavaScript
mit
1,527
module Vectra class Rules attr_accessor :target @target = "/rules" def self.all Vectra::API.pull(@target) end def each self.all.each do |host| yield host end end def self.get(id) unless id.is_a? Integer id = id.split("/").last end Vectra::API.pull("#{@target}/#{id}") end end end
mikemackintosh/ruby-vectra
lib/vectra/rules.rb
Ruby
mit
375
/** * @authors JayChenFE * @date 2017-03-21 11:17:13 * @version $1.0$ */ /** * 主要核心逻辑入口 **/ const fs = require('fs'); const path = require('path'); const staticServer = require('./static-server'); class App { constructor() { } initServer() { //方便增加别的逻辑 //返回一个函数 return (request, response) => { let { url } = request; let body = staticServer(url); response.writeHead(200, 'resolve ok', { 'X-Powered-By': 'Node.js' }); response.end(body); // const staticPrefix = path.resolve(process.cwd(), 'public'); // let staticFun = url => { // if (url == '/') { // url = '/index.html'; // } // let _path = getPath(url); // // fs.readFile(_path, 'binary', (error, data) => { // // if (error) { // // data="NOT FOUND"; // // } // // response.end(data,'binary'); // // }); // fs.readFile(_path, (error, data) => { // if (error) { // data = `NOT FOUND ${error.stack}`; // } // response.end(data); // }); // }; // staticFun(url); // if (url == '/css/index.css') { // fs.readFile('./public/css/index.css', 'utf-8', (error, data) => { // response.end(data); // }); // } // if (url == '/js/index.js') { // fs.readFile('./public/js/index.js', 'utf-8', (error, data) => { // response.end(data); // }); // } // if (url == '/') { // //第一个路径相对的是process.cwd(); // fs.readFile('./public/index.html', 'utf-8', (error, data) => { // response.end(data); // }); // } }; } } module.exports = App;
JayChenFE/pure-node-notebook
lesson2/app/index.js
JavaScript
mit
1,646
define('controllers/menuController',['jqueryui'],function($){ $('#faq').dialog({ modal:true, autoOpen: false, height:window.innerHeight * 0.75, width:window.innerWidth * 0.75, draggable:false }); $('#faq-button').click(function(event){ $('#faq').dialog('open'); }); $('#signin').dialog({ modal:true, autoOpen: false, height:window.innerHeight * 0.75, width:window.innerWidth * 0.75, draggable:false }); $('#signin-button').click(function(event){ $('#signin').dialog('open'); }); $('#facebook-login').click(function(event){ $(document).trigger('facebook-login'); }); });
harryphan/teachme
public/js/controllers/menuController.js
JavaScript
mit
742
require 'spec_helper' describe Allegro::WebApi::User do it 'gets my user data' do VCR.use_cassette('my_profile_data') do client = set_client user = Allegro::WebApi::User.new(client.login) user.do_get_my_data.wont_be_nil end end describe 'more specific info' do before do VCR.use_cassette('my_profile') do client = set_client @user = Allegro::WebApi::User.new(client.login) @user.do_get_my_data @user end end it 'gets user first name and last name' do @user.first_name.wont_be_nil @user.last_name.wont_be_nil end it 'gets email' do @user.email.wont_be_nil end it 'gets city' do @user.city.wont_be_nil end it 'gets phone' do @user.phone.wont_be_nil end it 'gets rating' do @user.rating.wont_be_nil end it 'gets id' do @user.id.wont_be_nil end it 'gets birth_date' do @user.birth_date.wont_be_nil end it 'gets address' do @user.address.wont_be_nil end it 'gets company' do @user.company.wont_be_nil end end end
Lackoftactics/allegro-webapi
spec/user_spec.rb
Ruby
mit
1,139
using System; using NetRuntimeSystem = System; using System.ComponentModel; using NetOffice.Attributes; namespace NetOffice.OutlookApi { /// <summary> /// DispatchInterface _DocumentItem /// SupportByVersion Outlook, 9,10,11,12,14,15,16 /// </summary> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] [EntityType(EntityType.IsDispatchInterface), BaseType] public class _DocumentItem : COMObject { #pragma warning disable #region Type Information /// <summary> /// Instance Type /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden] public override Type InstanceType { get { return LateBindingApiWrapperType; } } private static Type _type; [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public static Type LateBindingApiWrapperType { get { if (null == _type) _type = typeof(_DocumentItem); return _type; } } #endregion #region Ctor /// <param name="factory">current used factory core</param> /// <param name="parentObject">object there has created the proxy</param> /// <param name="proxyShare">proxy share instead if com proxy</param> public _DocumentItem(Core factory, ICOMObject parentObject, COMProxyShare proxyShare) : base(factory, parentObject, proxyShare) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> public _DocumentItem(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public _DocumentItem(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public _DocumentItem(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public _DocumentItem(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType) { } ///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public _DocumentItem(ICOMObject replacedObject) : base(replacedObject) { } [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public _DocumentItem() : base() { } /// <param name="progId">registered progID</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public _DocumentItem(string progId) : base(progId) { } #endregion #region Properties /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.Application"/> </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] [BaseResult] public NetOffice.OutlookApi._Application Application { get { return Factory.ExecuteBaseReferencePropertyGet<NetOffice.OutlookApi._Application>(this, "Application"); } } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.Class"/> </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] public NetOffice.OutlookApi.Enums.OlObjectClass Class { get { return Factory.ExecuteEnumPropertyGet<NetOffice.OutlookApi.Enums.OlObjectClass>(this, "Class"); } } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.Session"/> </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] [BaseResult] public NetOffice.OutlookApi._NameSpace Session { get { return Factory.ExecuteBaseReferencePropertyGet<NetOffice.OutlookApi._NameSpace>(this, "Session"); } } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// Get /// Unknown COM Proxy /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.Parent"/> </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16), ProxyResult] public object Parent { get { return Factory.ExecuteReferencePropertyGet(this, "Parent"); } } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.Actions"/> </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] public NetOffice.OutlookApi.Actions Actions { get { return Factory.ExecuteKnownReferencePropertyGet<NetOffice.OutlookApi.Actions>(this, "Actions", NetOffice.OutlookApi.Actions.LateBindingApiWrapperType); } } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.Attachments"/> </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] public NetOffice.OutlookApi.Attachments Attachments { get { return Factory.ExecuteKnownReferencePropertyGet<NetOffice.OutlookApi.Attachments>(this, "Attachments", NetOffice.OutlookApi.Attachments.LateBindingApiWrapperType); } } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.BillingInformation"/> </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] public string BillingInformation { get { return Factory.ExecuteStringPropertyGet(this, "BillingInformation"); } set { Factory.ExecuteValuePropertySet(this, "BillingInformation", value); } } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.Body"/> </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] public string Body { get { return Factory.ExecuteStringPropertyGet(this, "Body"); } set { Factory.ExecuteValuePropertySet(this, "Body", value); } } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.Categories"/> </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] public string Categories { get { return Factory.ExecuteStringPropertyGet(this, "Categories"); } set { Factory.ExecuteValuePropertySet(this, "Categories", value); } } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.Companies"/> </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] public string Companies { get { return Factory.ExecuteStringPropertyGet(this, "Companies"); } set { Factory.ExecuteValuePropertySet(this, "Companies", value); } } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.ConversationIndex"/> </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] public string ConversationIndex { get { return Factory.ExecuteStringPropertyGet(this, "ConversationIndex"); } } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.ConversationTopic"/> </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] public string ConversationTopic { get { return Factory.ExecuteStringPropertyGet(this, "ConversationTopic"); } } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.CreationTime"/> </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] public DateTime CreationTime { get { return Factory.ExecuteDateTimePropertyGet(this, "CreationTime"); } } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.EntryID"/> </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] public string EntryID { get { return Factory.ExecuteStringPropertyGet(this, "EntryID"); } } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.FormDescription"/> </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] public NetOffice.OutlookApi.FormDescription FormDescription { get { return Factory.ExecuteKnownReferencePropertyGet<NetOffice.OutlookApi.FormDescription>(this, "FormDescription", NetOffice.OutlookApi.FormDescription.LateBindingApiWrapperType); } } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.GetInspector"/> </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] [BaseResult] public NetOffice.OutlookApi._Inspector GetInspector { get { return Factory.ExecuteBaseReferencePropertyGet<NetOffice.OutlookApi._Inspector>(this, "GetInspector"); } } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.Importance"/> </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] public NetOffice.OutlookApi.Enums.OlImportance Importance { get { return Factory.ExecuteEnumPropertyGet<NetOffice.OutlookApi.Enums.OlImportance>(this, "Importance"); } set { Factory.ExecuteEnumPropertySet(this, "Importance", value); } } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.LastModificationTime"/> </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] public DateTime LastModificationTime { get { return Factory.ExecuteDateTimePropertyGet(this, "LastModificationTime"); } } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// Get /// Unknown COM Proxy /// </summary> [SupportByVersion("Outlook", 9,10,11,12,14,15,16), ProxyResult] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public object MAPIOBJECT { get { return Factory.ExecuteReferencePropertyGet(this, "MAPIOBJECT"); } } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.MessageClass"/> </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] public string MessageClass { get { return Factory.ExecuteStringPropertyGet(this, "MessageClass"); } set { Factory.ExecuteValuePropertySet(this, "MessageClass", value); } } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.Mileage"/> </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] public string Mileage { get { return Factory.ExecuteStringPropertyGet(this, "Mileage"); } set { Factory.ExecuteValuePropertySet(this, "Mileage", value); } } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.NoAging"/> </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] public bool NoAging { get { return Factory.ExecuteBoolPropertyGet(this, "NoAging"); } set { Factory.ExecuteValuePropertySet(this, "NoAging", value); } } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.OutlookInternalVersion"/> </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] public Int32 OutlookInternalVersion { get { return Factory.ExecuteInt32PropertyGet(this, "OutlookInternalVersion"); } } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.OutlookVersion"/> </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] public string OutlookVersion { get { return Factory.ExecuteStringPropertyGet(this, "OutlookVersion"); } } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.Saved"/> </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] public bool Saved { get { return Factory.ExecuteBoolPropertyGet(this, "Saved"); } } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.Sensitivity"/> </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] public NetOffice.OutlookApi.Enums.OlSensitivity Sensitivity { get { return Factory.ExecuteEnumPropertyGet<NetOffice.OutlookApi.Enums.OlSensitivity>(this, "Sensitivity"); } set { Factory.ExecuteEnumPropertySet(this, "Sensitivity", value); } } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.Size"/> </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] public Int32 Size { get { return Factory.ExecuteInt32PropertyGet(this, "Size"); } } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.Subject"/> </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] public string Subject { get { return Factory.ExecuteStringPropertyGet(this, "Subject"); } set { Factory.ExecuteValuePropertySet(this, "Subject", value); } } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.UnRead"/> </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] public bool UnRead { get { return Factory.ExecuteBoolPropertyGet(this, "UnRead"); } set { Factory.ExecuteValuePropertySet(this, "UnRead", value); } } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.UserProperties"/> </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] public NetOffice.OutlookApi.UserProperties UserProperties { get { return Factory.ExecuteKnownReferencePropertyGet<NetOffice.OutlookApi.UserProperties>(this, "UserProperties", NetOffice.OutlookApi.UserProperties.LateBindingApiWrapperType); } } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] public NetOffice.OutlookApi.Links Links { get { return Factory.ExecuteKnownReferencePropertyGet<NetOffice.OutlookApi.Links>(this, "Links", NetOffice.OutlookApi.Links.LateBindingApiWrapperType); } } /// <summary> /// SupportByVersion Outlook 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.DownloadState"/> </remarks> [SupportByVersion("Outlook", 10,11,12,14,15,16)] public NetOffice.OutlookApi.Enums.OlDownloadState DownloadState { get { return Factory.ExecuteEnumPropertyGet<NetOffice.OutlookApi.Enums.OlDownloadState>(this, "DownloadState"); } } /// <summary> /// SupportByVersion Outlook 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.ItemProperties"/> </remarks> [SupportByVersion("Outlook", 10,11,12,14,15,16)] public NetOffice.OutlookApi.ItemProperties ItemProperties { get { return Factory.ExecuteKnownReferencePropertyGet<NetOffice.OutlookApi.ItemProperties>(this, "ItemProperties", NetOffice.OutlookApi.ItemProperties.LateBindingApiWrapperType); } } /// <summary> /// SupportByVersion Outlook 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.MarkForDownload"/> </remarks> [SupportByVersion("Outlook", 10,11,12,14,15,16)] public NetOffice.OutlookApi.Enums.OlRemoteStatus MarkForDownload { get { return Factory.ExecuteEnumPropertyGet<NetOffice.OutlookApi.Enums.OlRemoteStatus>(this, "MarkForDownload"); } set { Factory.ExecuteEnumPropertySet(this, "MarkForDownload", value); } } /// <summary> /// SupportByVersion Outlook 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.IsConflict"/> </remarks> [SupportByVersion("Outlook", 10,11,12,14,15,16)] public bool IsConflict { get { return Factory.ExecuteBoolPropertyGet(this, "IsConflict"); } } /// <summary> /// SupportByVersion Outlook 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.AutoResolvedWinner"/> </remarks> [SupportByVersion("Outlook", 11,12,14,15,16)] public bool AutoResolvedWinner { get { return Factory.ExecuteBoolPropertyGet(this, "AutoResolvedWinner"); } } /// <summary> /// SupportByVersion Outlook 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.Conflicts"/> </remarks> [SupportByVersion("Outlook", 11,12,14,15,16)] public NetOffice.OutlookApi.Conflicts Conflicts { get { return Factory.ExecuteKnownReferencePropertyGet<NetOffice.OutlookApi.Conflicts>(this, "Conflicts", NetOffice.OutlookApi.Conflicts.LateBindingApiWrapperType); } } /// <summary> /// SupportByVersion Outlook 12, 14, 15, 16 /// Get /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.PropertyAccessor"/> </remarks> [SupportByVersion("Outlook", 12,14,15,16)] public NetOffice.OutlookApi.PropertyAccessor PropertyAccessor { get { return Factory.ExecuteKnownReferencePropertyGet<NetOffice.OutlookApi.PropertyAccessor>(this, "PropertyAccessor", NetOffice.OutlookApi.PropertyAccessor.LateBindingApiWrapperType); } } #endregion #region Methods /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.Close(method)"/> </remarks> /// <param name="saveMode">NetOffice.OutlookApi.Enums.OlInspectorClose saveMode</param> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] public void Close(NetOffice.OutlookApi.Enums.OlInspectorClose saveMode) { Factory.ExecuteMethod(this, "Close", saveMode); } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.Copy"/> </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] public object Copy() { return Factory.ExecuteVariantMethodGet(this, "Copy"); } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.Delete"/> </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] public void Delete() { Factory.ExecuteMethod(this, "Delete"); } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.Display"/> </remarks> /// <param name="modal">optional object modal</param> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] public void Display(object modal) { Factory.ExecuteMethod(this, "Display", modal); } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.Display"/> </remarks> [CustomMethod] [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] public void Display() { Factory.ExecuteMethod(this, "Display"); } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.Move"/> </remarks> /// <param name="destFldr">NetOffice.OutlookApi.MAPIFolder destFldr</param> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] public object Move(NetOffice.OutlookApi.MAPIFolder destFldr) { return Factory.ExecuteVariantMethodGet(this, "Move", destFldr); } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.PrintOut"/> </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] public void PrintOut() { Factory.ExecuteMethod(this, "PrintOut"); } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.Save"/> </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] public void Save() { Factory.ExecuteMethod(this, "Save"); } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.SaveAs"/> </remarks> /// <param name="path">string path</param> /// <param name="type">optional object type</param> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] public void SaveAs(string path, object type) { Factory.ExecuteMethod(this, "SaveAs", path, type); } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.SaveAs"/> </remarks> /// <param name="path">string path</param> [CustomMethod] [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] public void SaveAs(string path) { Factory.ExecuteMethod(this, "SaveAs", path); } /// <summary> /// SupportByVersion Outlook 10, 11, 12, 14, 15, 16 /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Outlook.DocumentItem.ShowCategoriesDialog"/> </remarks> [SupportByVersion("Outlook", 10,11,12,14,15,16)] public void ShowCategoriesDialog() { Factory.ExecuteMethod(this, "ShowCategoriesDialog"); } #endregion #pragma warning restore } }
NetOfficeFw/NetOffice
Source/Outlook/DispatchInterfaces/_DocumentItem.cs
C#
mit
25,897
class FakeGithub RECORDER = File.expand_path(File.join('..', '..', 'tmp', 'hub_commands'), File.dirname(__FILE__)) def initialize(args) @args = args end def run! File.open(RECORDER, 'a') do |file| file.write @args.join(' ') end end def self.clear! FileUtils.rm_rf RECORDER end def self.has_created_repo?(repo_name) File.read(RECORDER) == "create #{repo_name}" end def self.has_created_private_repo?(repo_name) File.read(RECORDER) == "create -p #{repo_name}" end end
platanus/potassium
spec/support/fake_github.rb
Ruby
mit
523
const _ = require("lodash"); const Path = require("path-parser"); const { URL } = require("url"); const mongoose = require("mongoose"); const requireSignIn = require("../middlewares/requireSignIn"); const requireCredits = require("../middlewares/requireCredits"); const Mailer = require("../services/Mailer"); const surveyTemplate = require("../services/templates/surveyTemplate"); const Survey = mongoose.model("surveys"); module.exports = app => { app.get("/api/surveys", requireSignIn, async (req, res) => { const surveys = await Survey.find({ _user: req.user.id }).select({ recipients: false }); res.send(surveys); }); app.get("/api/surveys/:surveyID/:choice", (req, res) => { res.send("Thank you for your response."); }); app.post("/api/surveys/webhooks", (req, res) => { const parsedURL = new Path("/api/surveys/:surveyID/:choice"); _.chain(req.body) .map(({ email, url }) => { //do not destructure because match can be null const match = parsedURL.test(new URL(url).pathname); if (match) { return { email, surveyID: match.surveyID, choice: match.choice }; } }) .compact() .uniqBy("email", "surveyID") .each(({ surveyID, email, choice }) => { Survey.updateOne( { _id: surveyID, recipients: { $elemMatch: { email: email, responded: false } } }, { $inc: { [choice]: 1 }, $set: { "recipients.$.responded": true }, lastResponded: new Date() } ).exec(); }) .value(); res.send({}); }); app.post("/api/surveys", requireSignIn, requireCredits, async (req, res) => { const { title, subject, body, recipients } = req.body; const survey = new Survey({ title, subject, body, recipients: recipients.split(",").map(email => ({ email: email.trim() })), _user: req.user.id, dateSent: Date.now() }); const mailer = new Mailer(survey, surveyTemplate(survey)); try { await mailer.send(); await survey.save(); req.user.credits -= 1; const user = await req.user.save(); res.send(user); } catch (err) { res.status(422).send(err); } }); };
ibramos/The-Feed
server/routes/surveyRoutes.js
JavaScript
mit
2,308
#ifndef KALAH_BOARD_H #define KALAH_BOARD_H #include <vector> #include "houseContainer.hpp" #include "storeContainer.hpp" using namespace std; class kalahBoard { public: kalahBoard(unsigned int numberOfHousesIn); void fillHouses(vector<unsigned int> homeHouseInitialSeedCount, vector<unsigned int> awayHouseInitialSeedCount); unsigned int getNumberOfHouses(); vector<houseContainer> homeHouses; vector<houseContainer> awayHouses; storeContainer homeStore; storeContainer awayStore; private: void assignContainerRefs(); unsigned int numberOfHouses; }; #endif
chadvoegele/kalah-ncurses
src/kalahBoard.hpp
C++
mit
590
package interpreter import ( "fmt" "github.com/Azer0s/Hummus/parser" ) // NodeType a variable type type NodeType uint8 // Node a variable node type Node struct { Value interface{} NodeType NodeType } const ( // NODETYPE_INT int variable type NODETYPE_INT NodeType = 0 // NODETYPE_FLOAT float variable type NODETYPE_FLOAT NodeType = 1 // NODETYPE_STRING string variable type NODETYPE_STRING NodeType = 2 // NODETYPE_BOOL bool variable type NODETYPE_BOOL NodeType = 3 // NODETYPE_ATOM atom variable type NODETYPE_ATOM NodeType = 4 // NODETYPE_FN function literal NODETYPE_FN NodeType = 5 // NODETYPE_LIST list type NODETYPE_LIST NodeType = 6 // NODETYPE_MAP map type NODETYPE_MAP NodeType = 7 // NODETYPE_STRUCT struct type NODETYPE_STRUCT NodeType = 8 ) // FnLiteral a function literal (block) type FnLiteral struct { Parameters []string Body []parser.Node Context map[string]Node } // ListNode a list value type ListNode struct { Values []Node } // MapNode a map node type MapNode struct { Values map[string]Node } // StructDef struct definition type StructDef struct { Parameters []string } // Smaller < operator for Node func (node *Node) Smaller(compareTo Node) bool { if node.NodeType != compareTo.NodeType { panic("Can't compare nodes of two different types!") } switch node.NodeType { case NODETYPE_INT: return node.Value.(int) < compareTo.Value.(int) case NODETYPE_FLOAT: return node.Value.(float64) < compareTo.Value.(float64) case NODETYPE_STRING: return node.Value.(string) < compareTo.Value.(string) case NODETYPE_ATOM: return node.Value.(string) < compareTo.Value.(string) default: panic(fmt.Sprintf("Nodetype %d cannot be compared!", node.NodeType)) } } // Bigger > operator for Node func (node *Node) Bigger(compareTo Node) bool { if node.NodeType != compareTo.NodeType { panic("Can't compare nodes of two different types!") } switch node.NodeType { case NODETYPE_INT: return node.Value.(int) > compareTo.Value.(int) case NODETYPE_FLOAT: return node.Value.(float64) > compareTo.Value.(float64) case NODETYPE_STRING: return node.Value.(string) > compareTo.Value.(string) case NODETYPE_ATOM: return node.Value.(string) > compareTo.Value.(string) default: panic(fmt.Sprintf("Nodetype %d cannot be compared!", node.NodeType)) } } // OptionalNode return an optional node func OptionalNode(val interface{}, nodeType NodeType, err bool) Node { return Node{ Value: MapNode{Values: map[string]Node{ "value": { Value: val, NodeType: nodeType, }, "error": { Value: err, NodeType: NODETYPE_BOOL, }, }}, NodeType: NODETYPE_MAP, } }
Azer0s/LBox
interpreter/node.go
GO
mit
2,670
// Geometry building functions import Vector from '../vector'; import Geo from '../geo'; import earcut from 'earcut'; var Builders; export default Builders = {}; Builders.debug = false; Builders.tile_bounds = [ { x: 0, y: 0}, { x: Geo.tile_scale, y: -Geo.tile_scale } // TODO: correct for flipped y-axis? ]; // Re-scale UVs from [0, 1] range to a smaller area within the image Builders.scaleTexcoordsToSprite = function (uv, area_origin, area_size, tex_size) { var area_origin_y = tex_size[1] - area_origin[1] - area_size[1]; var suv = []; suv[0] = (uv[0] * area_size[0] + area_origin[0]) / tex_size[0]; suv[1] = (uv[1] * area_size[1] + area_origin_y) / tex_size[1]; return suv; }; Builders.getTexcoordsForSprite = function (area_origin, area_size, tex_size) { return [ Builders.scaleTexcoordsToSprite([0, 0], area_origin, area_size, tex_size), Builders.scaleTexcoordsToSprite([1, 1], area_origin, area_size, tex_size) ]; }; // Tesselate a flat 2D polygon // x & y coordinates will be set as first two elements of provided vertex_template Builders.buildPolygons = function ( polygons, vertex_data, vertex_template, { texcoord_index, texcoord_scale, texcoord_normalize }) { if (texcoord_index) { texcoord_normalize = texcoord_normalize || 1; var [[min_u, min_v], [max_u, max_v]] = texcoord_scale || [[0, 0], [1, 1]]; } var num_polygons = polygons.length; for (var p=0; p < num_polygons; p++) { var polygon = polygons[p]; // Find polygon extents to calculate UVs, fit them to the axis-aligned bounding box if (texcoord_index) { var [min_x, min_y, max_x, max_y] = Geo.findBoundingBox(polygon); var span_x = max_x - min_x; var span_y = max_y - min_y; var scale_u = (max_u - min_u) / span_x; var scale_v = (max_v - min_v) / span_y; } // Tessellate var vertices = Builders.triangulatePolygon(polygon); // Add vertex data var num_vertices = vertices.length; for (var v=0; v < num_vertices; v++) { var vertex = vertices[v]; vertex_template[0] = vertex[0]; vertex_template[1] = vertex[1]; // Add UVs if (texcoord_index) { vertex_template[texcoord_index + 0] = ((vertex[0] - min_x) * scale_u + min_u) * texcoord_normalize; vertex_template[texcoord_index + 1] = ((vertex[1] - min_y) * scale_v + min_v) * texcoord_normalize; } vertex_data.addVertex(vertex_template); } } }; // Tesselate and extrude a flat 2D polygon into a simple 3D model with fixed height and add to GL vertex buffer Builders.buildExtrudedPolygons = function ( polygons, z, height, min_height, vertex_data, vertex_template, normal_index, normal_normalize, { texcoord_index, texcoord_scale, texcoord_normalize }) { // Top var min_z = z + (min_height || 0); var max_z = z + height; vertex_template[2] = max_z; Builders.buildPolygons(polygons, vertex_data, vertex_template, { texcoord_index, texcoord_scale, texcoord_normalize }); // Walls // Fit UVs to wall quad if (texcoord_index) { texcoord_normalize = texcoord_normalize || 1; var [[min_u, min_v], [max_u, max_v]] = texcoord_scale || [[0, 0], [1, 1]]; var texcoords = [ [min_u, max_v], [min_u, min_v], [max_u, min_v], [max_u, min_v], [max_u, max_v], [min_u, max_v] ]; } var num_polygons = polygons.length; for (var p=0; p < num_polygons; p++) { var polygon = polygons[p]; for (var q=0; q < polygon.length; q++) { var contour = polygon[q]; for (var w=0; w < contour.length - 1; w++) { // Two triangles for the quad formed by each vertex pair, going from bottom to top height var wall_vertices = [ // Triangle [contour[w+1][0], contour[w+1][1], max_z], [contour[w+1][0], contour[w+1][1], min_z], [contour[w][0], contour[w][1], min_z], // Triangle [contour[w][0], contour[w][1], min_z], [contour[w][0], contour[w][1], max_z], [contour[w+1][0], contour[w+1][1], max_z] ]; // Calc the normal of the wall from up vector and one segment of the wall triangles var normal = Vector.cross( [0, 0, 1], Vector.normalize([contour[w+1][0] - contour[w][0], contour[w+1][1] - contour[w][1], 0]) ); // Update vertex template with current surface normal vertex_template[normal_index + 0] = normal[0] * normal_normalize; vertex_template[normal_index + 1] = normal[1] * normal_normalize; vertex_template[normal_index + 2] = normal[2] * normal_normalize; for (var wv=0; wv < wall_vertices.length; wv++) { vertex_template[0] = wall_vertices[wv][0]; vertex_template[1] = wall_vertices[wv][1]; vertex_template[2] = wall_vertices[wv][2]; if (texcoord_index) { vertex_template[texcoord_index + 0] = texcoords[wv][0] * texcoord_normalize; vertex_template[texcoord_index + 1] = texcoords[wv][1] * texcoord_normalize; } vertex_data.addVertex(vertex_template); } } } } }; // Build tessellated triangles for a polyline Builders.buildPolylines = function ( lines, width, vertex_data, vertex_template, { closed_polygon, remove_tile_edges, tile_edge_tolerance, texcoord_index, texcoord_scale, texcoord_normalize, scaling_index, scaling_normalize, join, cap }) { var cornersOnCap = (cap === "square") ? 2 : ((cap === "round") ? 3 : 0); // Butt is the implicit default var trianglesOnJoin = (join === "bevel") ? 1 : ((join === "round") ? 3 : 0); // Miter is the implicit default // Build variables texcoord_normalize = texcoord_normalize || 1; var [[min_u, min_v], [max_u, max_v]] = texcoord_scale || [[0, 0], [1, 1]]; // Values that are constant for each line and are passed to helper functions var constants = { vertex_data, vertex_template, halfWidth: width/2, vertices: [], scaling_index, scaling_normalize, scalingVecs: scaling_index && [], texcoord_index, texcoords: texcoord_index && [], texcoord_normalize, min_u, min_v, max_u, max_v, nPairs: 0 }; for (var ln = 0; ln < lines.length; ln++) { var line = lines[ln]; var lineSize = line.length; // Ignore non-lines if (lineSize < 2) { continue; } // Initialize variables var coordPrev = [0, 0], // Previous point coordinates coordCurr = [0, 0], // Current point coordinates coordNext = [0, 0]; // Next point coordinates var normPrev = [0, 0], // Right normal to segment between previous and current m_points normCurr = [0, 0], // Right normal at current point, scaled for miter joint normNext = [0, 0]; // Right normal to segment between current and next m_points var isPrev = false, isNext = true; // Add vertices to buffer according to their index indexPairs(constants); // Do this with the rest (except the last one) for (let i = 0; i < lineSize ; i++) { // There is a next one? isNext = i+1 < lineSize; if (isPrev) { // If there is a previous one, copy the current (previous) values on *Prev coordPrev = coordCurr; normPrev = Vector.normalize(Vector.perp(coordPrev, line[i])); } else if (i === 0 && closed_polygon === true) { // If it's the first point and is a closed polygon var needToClose = true; if (remove_tile_edges) { if(Builders.isOnTileEdge(line[i], line[lineSize-2], { tolerance: tile_edge_tolerance })) { needToClose = false; } } if (needToClose) { coordPrev = line[lineSize-2]; normPrev = Vector.normalize(Vector.perp(coordPrev, line[i])); isPrev = true; } } // Assign current coordinate coordCurr = line[i]; if (isNext) { coordNext = line[i+1]; } else if (closed_polygon === true) { // If it's the last point in a closed polygon coordNext = line[1]; isNext = true; } if (isNext) { // If it's not the last one get next coordinates and calculate the right normal normNext = Vector.normalize(Vector.perp(coordCurr, coordNext)); if (remove_tile_edges) { if (Builders.isOnTileEdge(coordCurr, coordNext, { tolerance: tile_edge_tolerance })) { normCurr = Vector.normalize(Vector.perp(coordPrev, coordCurr)); if (isPrev) { addVertexPair(coordCurr, normCurr, i/lineSize, constants); constants.nPairs++; // Add vertices to buffer acording their index indexPairs(constants); } isPrev = false; continue; } } } // Compute current normal if (isPrev) { // If there is a PREVIOUS ... if (isNext) { // ... and a NEXT ONE, compute previous and next normals (scaled by the angle with the last prev) normCurr = Vector.normalize(Vector.add(normPrev, normNext)); var scale = 2 / (1 + Math.abs(Vector.dot(normPrev, normCurr))); normCurr = Vector.mult(normCurr,scale*scale); } else { // ... and there is NOT a NEXT ONE, copy the previous next one (which is the current one) normCurr = Vector.normalize(Vector.perp(coordPrev, coordCurr)); } } else { // If there is NO PREVIOUS ... if (isNext) { // ... and a NEXT ONE, normNext = Vector.normalize(Vector.perp(coordCurr, coordNext)); normCurr = normNext; } else { // ... and NO NEXT ONE, nothing to do (without prev or next one this is just a point) continue; } } if (isPrev || isNext) { // If it's the BEGINNING of a LINE if (i === 0 && !isPrev && !closed_polygon) { addCap(coordCurr, normCurr, cornersOnCap, true, constants); } // If it's a JOIN if(trianglesOnJoin !== 0 && isPrev && isNext) { addJoin([coordPrev, coordCurr, coordNext], [normPrev,normCurr, normNext], i/lineSize, trianglesOnJoin, constants); } else { addVertexPair(coordCurr, normCurr, i/(lineSize-1), constants); } if (isNext) { constants.nPairs++; } isPrev = true; } } // Add vertices to buffer according to their index indexPairs(constants); // If it's the END of a LINE if(!closed_polygon) { addCap(coordCurr, normCurr, cornersOnCap , false, constants); } } }; // Add to equidistant pairs of vertices (internal method for polyline builder) function addVertex(coord, normal, uv, { halfWidth, vertices, scalingVecs, texcoords }) { if (scalingVecs) { // a. If scaling is on add the vertex (the currCoord) and the scaling Vecs (normals pointing where to extrude the vertices) vertices.push(coord); scalingVecs.push(normal); } else { // b. Add the extruded vertices vertices.push([coord[0] + normal[0] * halfWidth, coord[1] + normal[1] * halfWidth]); } // c) Add UVs if they are enabled if (texcoords) { texcoords.push(uv); } } // Add to equidistant pairs of vertices (internal method for polyline builder) function addVertexPair (coord, normal, v_pct, constants) { addVertex(coord, normal, [constants.max_u, (1-v_pct)*constants.min_v + v_pct*constants.max_v], constants); addVertex(coord, Vector.neg(normal), [constants.min_u, (1-v_pct)*constants.min_v + v_pct*constants.max_v], constants); } // Tessalate a FAN geometry between points A B // using their normals from a center \ . . / // and interpolating their UVs \ p / // \./ // C function addFan (coord, nA, nC, nB, uA, uC, uB, signed, numTriangles, constants) { if (numTriangles < 1) { return; } // Add previous vertices to buffer and clear the buffers and index pairs // because we are going to add more triangles. indexPairs(constants); var normCurr = Vector.set(nA); var normPrev = [0,0]; var angle_delta = Vector.dot(nA, nB); if (angle_delta < -1) { angle_delta = -1; } angle_delta = Math.acos(angle_delta)/numTriangles; if (!signed) { angle_delta *= -1; } var uvCurr = Vector.set(uA); var uv_delta = Vector.div(Vector.sub(uB,uA), numTriangles); // Add the FIRST and CENTER vertex // The triangles will be composed in a FAN style around it addVertex(coord, nC, uC, constants); // Add first corner addVertex(coord, normCurr, uA, constants); // Iterate through the rest of the corners for (var t = 0; t < numTriangles; t++) { normPrev = Vector.normalize(normCurr); normCurr = Vector.rot( Vector.normalize(normCurr), angle_delta); // Rotate the extrusion normal if (numTriangles === 4 && (t === 0 || t === numTriangles - 2)) { var scale = 2 / (1 + Math.abs(Vector.dot(normPrev, normCurr))); normCurr = Vector.mult(normCurr, scale*scale); } uvCurr = Vector.add(uvCurr,uv_delta); addVertex(coord, normCurr, uvCurr, constants); // Add computed corner } for (var i = 0; i < numTriangles; i++) { if (signed) { addIndex(i+2, constants); addIndex(0, constants); addIndex(i+1, constants); } else { addIndex(i+1, constants); addIndex(0, constants); addIndex(i+2, constants); } } // Clear the buffer constants.vertices = []; if (constants.scalingVecs) { constants.scalingVecs = []; } if (constants.texcoords) { constants.texcoords = []; } } // Add special joins (not miter) types that require FAN tessellations // Using http://www.codeproject.com/Articles/226569/Drawing-polylines-by-tessellation as reference function addJoin (coords, normals, v_pct, nTriangles, constants) { var T = [Vector.set(normals[0]), Vector.set(normals[1]), Vector.set(normals[2])]; var signed = Vector.signed_area(coords[0], coords[1], coords[2]) > 0; var nA = T[0], // normal to point A (aT) nC = Vector.neg(T[1]), // normal to center (-vP) nB = T[2]; // normal to point B (bT) var uA = [constants.max_u, (1-v_pct)*constants.min_v + v_pct*constants.max_v], uC = [constants.min_u, (1-v_pct)*constants.min_v + v_pct*constants.max_v], uB = [constants.max_u, (1-v_pct)*constants.min_v + v_pct*constants.max_v]; if (signed) { addVertex(coords[1], nA, uA, constants); addVertex(coords[1], nC, uC, constants); } else { nA = Vector.neg(T[0]); nC = T[1]; nB = Vector.neg(T[2]); uA = [constants.min_u, (1-v_pct)*constants.min_v + v_pct*constants.max_v]; uC = [constants.max_u, (1-v_pct)*constants.min_v + v_pct*constants.max_v]; uB = [constants.min_u, (1-v_pct)*constants.min_v + v_pct*constants.max_v]; addVertex(coords[1], nC, uC, constants); addVertex(coords[1], nA, uA, constants); } addFan(coords[1], nA, nC, nB, uA, uC, uB, signed, nTriangles, constants); if (signed) { addVertex(coords[1], nB, uB, constants); addVertex(coords[1], nC, uC, constants); } else { addVertex(coords[1], nC, uC, constants); addVertex(coords[1], nB, uB, constants); } } // Function to add the vertex need for line caps, // because re-use the buffers needs to be at the end function addCap (coord, normal, numCorners, isBeginning, constants) { if (numCorners < 1) { return; } // UVs var uvA = [constants.min_u,constants.min_v], // Beginning angle UVs uvC = [constants.min_u+(constants.max_u-constants.min_u)/2, constants.min_v], // center point UVs uvB = [constants.max_u,constants.min_v]; // Ending angle UVs if (!isBeginning) { uvA = [constants.min_u,constants.max_v], // Begining angle UVs uvC = [constants.min_u+(constants.max_u-constants.min_u)/2, constants.max_v], // center point UVs uvB = [constants.max_u,constants.max_v]; } addFan( coord, Vector.neg(normal), [0, 0], normal, uvA, uvC, uvB, isBeginning, numCorners*2, constants); } // Add a vertex based on the index position into the VBO (internal method for polyline builder) function addIndex (index, { vertex_data, vertex_template, halfWidth, vertices, scaling_index, scaling_normalize, scalingVecs, texcoord_index, texcoords, texcoord_normalize }) { // Prevent access to undefined vertices if (index >= vertices.length) { return; } // set vertex position vertex_template[0] = vertices[index][0]; vertex_template[1] = vertices[index][1]; // set UVs if (texcoord_index) { vertex_template[texcoord_index + 0] = texcoords[index][0] * texcoord_normalize; vertex_template[texcoord_index + 1] = texcoords[index][1] * texcoord_normalize; } // set Scaling vertex (X, Y normal direction + Z halfwidth as attribute) if (scaling_index) { vertex_template[scaling_index + 0] = scalingVecs[index][0] * scaling_normalize; vertex_template[scaling_index + 1] = scalingVecs[index][1] * scaling_normalize; vertex_template[scaling_index + 2] = halfWidth; } // Add vertex to VBO vertex_data.addVertex(vertex_template); } // Add the index vertex to the VBO and clean the buffers function indexPairs (constants) { // Add vertices to buffer acording their index for (var i = 0; i < constants.nPairs; i++) { addIndex(2*i+2, constants); addIndex(2*i+1, constants); addIndex(2*i+0, constants); addIndex(2*i+2, constants); addIndex(2*i+3, constants); addIndex(2*i+1, constants); } constants.nPairs = 0; // Clean the buffer constants.vertices = []; if (constants.scalingVecs) { constants.scalingVecs = []; } if (constants.texcoords) { constants.texcoords = []; } } // Build a billboard sprite quad centered on a point. Sprites are intended to be drawn in screenspace, and have // properties for width, height, angle, and a scale factor that can be used to interpolate the screenspace size // of a sprite between two zoom levels. Builders.buildQuadsForPoints = function ( points, width, height, angle, scale, vertex_data, vertex_template, scaling_index, { texcoord_index, texcoord_scale, texcoord_normalize }) { let w2 = width / 2; let h2 = height / 2; let scaling = [ [-w2, -h2], [w2, -h2], [w2, h2], [-w2, -h2], [w2, h2], [-w2, h2] ]; let texcoords; if (texcoord_index) { texcoord_normalize = texcoord_normalize || 1; let [[min_u, min_v], [max_u, max_v]] = texcoord_scale || [[0, 0], [1, 1]]; texcoords = [ [min_u, min_v], [max_u, min_v], [max_u, max_v], [min_u, min_v], [max_u, max_v], [min_u, max_v] ]; } let num_points = points.length; for (let p=0; p < num_points; p++) { let point = points[p]; for (let pos=0; pos < 6; pos++) { // Add texcoords if (texcoord_index) { vertex_template[texcoord_index + 0] = texcoords[pos][0] * texcoord_normalize; vertex_template[texcoord_index + 1] = texcoords[pos][1] * texcoord_normalize; } vertex_template[0] = point[0]; vertex_template[1] = point[1]; vertex_template[scaling_index + 0] = scaling[pos][0]; vertex_template[scaling_index + 1] = scaling[pos][1]; vertex_template[scaling_index + 2] = angle; vertex_template[scaling_index + 3] = scale; vertex_data.addVertex(vertex_template); } } }; /* Utility functions */ // Triangulation using earcut // https://github.com/mapbox/earcut Builders.triangulatePolygon = function (contours) { return earcut(contours); }; // Tests if a line segment (from point A to B) is nearly coincident with the edge of a tile Builders.isOnTileEdge = function (pa, pb, options) { options = options || {}; var tolerance_function = options.tolerance_function || Builders.valuesWithinTolerance; var tolerance = options.tolerance || 1; var tile_min = Builders.tile_bounds[0]; var tile_max = Builders.tile_bounds[1]; var edge = null; if (tolerance_function(pa[0], tile_min.x, tolerance) && tolerance_function(pb[0], tile_min.x, tolerance)) { edge = 'left'; } else if (tolerance_function(pa[0], tile_max.x, tolerance) && tolerance_function(pb[0], tile_max.x, tolerance)) { edge = 'right'; } else if (tolerance_function(pa[1], tile_min.y, tolerance) && tolerance_function(pb[1], tile_min.y, tolerance)) { edge = 'top'; } else if (tolerance_function(pa[1], tile_max.y, tolerance) && tolerance_function(pb[1], tile_max.y, tolerance)) { edge = 'bottom'; } return edge; }; Builders.valuesWithinTolerance = function (a, b, tolerance) { tolerance = tolerance || 1; return (Math.abs(a - b) < tolerance); };
rosamcgee/tangram
src/styles/builders.js
JavaScript
mit
23,298
#target "InDesign" #include "../datetimef.js" var today = new Date(2014, 2, 8, 13, 23, 46, 300); // => Sat Mar 08 2014 13:23:46 GMT+0900 var ret = []; var t = function(done, expect) { done_str = done; if (done === expect) { ret.push("[Passed]: return => " + expect); } else { ret.push("[Failed]: expect " + expect + ", but return => " + done); } } // tests t( datetimef(today)+"", Error("No Format")+""); t( datetimef(today, 123)+"", Error("No Format")+""); t( datetimef(today, ""), ""); t( datetimef(today, "%X"), "%X"); t( datetimef("today", "%Y")+"", Error("Not Date")+""); t( datetimef(today, "%Y"), "2014"); t( datetimef(today, "%y"), "14"); t( datetimef(today, "%m"), "03"); t( datetimef(today, "%B"), "March"); t( datetimef(today, "%b"), "Mar"); t( datetimef(today, "%d"), "08"); t( datetimef(today, "%e"), " 8"); t( datetimef(today, "%j"), "67"); t( datetimef(today, "%H"), "13"); t( datetimef(today, "%k"), "13"); t( datetimef(today, "%I"), "01"); t( datetimef(today, "%l"), " 1"); t( datetimef(today, "%p"), "PM"); t( datetimef(today, "%P"), "pm"); t( datetimef(today, "%M"), "23"); t( datetimef(today, "%S"), "46"); t( datetimef(today, "%L"), "300"); t( datetimef(today, "%z"), "-0900"); t( datetimef(today, "%A"), "Saturday"); t( datetimef(today, "%a"), "Sat"); t( datetimef(today, "%u"), "7"); t( datetimef(today, "%w"), "6"); t( datetimef(today, "%s"), "1394252626300"); t( datetimef(today, "%Y%m%d"), "20140308" ); t( datetimef(today, "%F"), "2014-03-08" ); t( datetimef(today, "%Y-%m"), "2014-03" ); t( datetimef(today, "%Y"), "2014" ); t( datetimef(today, "%Y%j"), "201467" ); t( datetimef(today, "%Y-%j"), "2014-67" ); t( datetimef(today, "%H%M%S"), "132346" ); t( datetimef(today, "%T"), "13:23:46" ); t( datetimef(today, "%H%M"), "1323" ); t( datetimef(today, "%H:%M"), "13:23" ); t( datetimef(today, "%H"), "13" ); t( datetimef(today, "%H%M%S,%L"), "132346,300" ); t( datetimef(today, "%T,%L"), "13:23:46,300" ); t( datetimef(today, "%H%M%S.%L"), "132346.300" ); t( datetimef(today, "%T.%L"), "13:23:46.300" ); t( datetimef(today, "%H%M%S%z"), "132346-0900" ); t( datetimef(today, "%Y%m%dT%H%M%S%z"), "20140308T132346-0900" ); t( datetimef(today, "%Y%jT%H%M%S%z"), "201467T132346-0900" ); t( datetimef(today, "%Y%m%dT%H%M"), "20140308T1323" ); t( datetimef(today, "%FT%R"), "2014-03-08T13:23" ); t( datetimef(today, "%Y%jT%H%MZ"), "201467T1323Z" ); t( datetimef(today, "%Y-%jT%RZ"), "2014-67T13:23Z" ); $.writeln(ret.join("\n")); /* toString,toSource [Passed]: return => エラー: No Format [Passed]: return => エラー: No Format [Passed]: return => [Passed]: return => %X [Passed]: return => エラー: Not Date [Passed]: return => 2014 [Passed]: return => 14 [Passed]: return => 03 [Passed]: return => March [Passed]: return => Mar [Passed]: return => 08 [Passed]: return =>  8 [Passed]: return => 67 [Passed]: return => 13 [Passed]: return => 13 [Passed]: return => 01 [Passed]: return =>  1 [Passed]: return => PM [Passed]: return => pm [Passed]: return => 23 [Passed]: return => 46 [Passed]: return => 300 [Passed]: return => -0900 [Passed]: return => Saturday [Passed]: return => Sat [Passed]: return => 7 [Passed]: return => 6 [Passed]: return => 1394252626300 [Passed]: return => 20140308 [Passed]: return => 2014-03-08 [Passed]: return => 2014-03 [Passed]: return => 2014 [Passed]: return => 201467 [Passed]: return => 2014-67 [Passed]: return => 132346 [Passed]: return => 13:23:46 [Passed]: return => 1323 [Passed]: return => 13:23 [Passed]: return => 13 [Passed]: return => 132346,300 [Passed]: return => 13:23:46,300 [Passed]: return => 132346.300 [Passed]: return => 13:23:46.300 [Passed]: return => 132346-0900 [Passed]: return => 20140308T132346-0900 [Passed]: return => 201467T132346-0900 [Passed]: return => 20140308T1323 [Passed]: return => 2014-03-08T13:23 [Passed]: return => 201467T1323Z [Passed]: return => 2014-67T13:23Z */
milligramme/datetimef.js
test/datetimef_test.js
JavaScript
mit
3,900
import { all } from 'redux-saga/effects'; import WatchUsers from 'sagas/users'; export default function *WatchSagas() { yield all([ WatchUsers() ]); }
donofkarma/react-starter
app/sagas/index.js
JavaScript
mit
169
package com.fxexperience.javafx.animation; import javafx.animation.KeyFrame; import javafx.animation.KeyValue; import javafx.animation.TimelineBuilder; import javafx.scene.Node; import javafx.util.Duration; /** * Animate a bounce in right big effect on a node * * Port of BounceInRightBig from Animate.css http://daneden.me/animate by Dan Eden * * {@literal @}keyframes bounceInRight { * 0% { * opacity: 0; * -webkit-transform: translateX(2000px); * } * 60% { * opacity: 1; * -webkit-transform: translateX(-30px); * } * 80% { * -webkit-transform: translateX(10px); * } * 100% { * -webkit-transform: translateX(0); * } * } * * @author Jasper Potts */ public class BounceInRightTransition extends CachedTimelineTransition { /** * Create new BounceInRightBigTransition * * @param node The node to affect */ public BounceInRightTransition(final Node node) { super(node, null); setCycleDuration(Duration.seconds(1)); setDelay(Duration.seconds(0.2)); } @Override protected void starting() { double startX = node.getScene().getWidth() - node.localToScene(0, 0).getX(); timeline = TimelineBuilder.create() .keyFrames( new KeyFrame(Duration.millis(0), new KeyValue(node.opacityProperty(), 0, WEB_EASE), new KeyValue(node.translateXProperty(), startX, WEB_EASE) ), new KeyFrame(Duration.millis(600), new KeyValue(node.opacityProperty(), 1, WEB_EASE), new KeyValue(node.translateXProperty(), -30, WEB_EASE) ), new KeyFrame(Duration.millis(800), new KeyValue(node.translateXProperty(), 10, WEB_EASE) ), new KeyFrame(Duration.millis(1000), new KeyValue(node.translateXProperty(), 0, WEB_EASE) ) ) .build(); super.starting(); } }
adv0r/botcoin
Botcoin-javafx/src/com/fxexperience/javafx/animation/BounceInRightTransition.java
Java
mit
2,122
""" Django settings for plasystem project. Generated by 'django-admin startproject' using Django 1.10.5. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ from local_settings import * # Application definition INSTALLED_APPS = [ 'flat_responsive', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'productores', 'organizaciones', 'subsectores', 'lugar', 'resultados', 'reportes', 'smart_selects', 'multiselectfield', #'nested_admin', 'nested_inline', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'plasystem.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'plasystem.wsgi.application' # Password validation # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.10/topics/i18n/ LANGUAGE_CODE = 'es-ni' TIME_ZONE = 'America/Managua' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.10/howto/static-files MEDIA_ROOT = os.environ.get('MEDIA_ROOT', os.path.join(BASE_DIR, 'media')) MEDIA_URL = '/media/' STATIC_ROOT = os.environ.get('STATIC_ROOT', os.path.join(BASE_DIR, 'static')) STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static_media"), ) LOGIN_URL = '/login/' LOGIN_REDIRECT_URL = '/' SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'
CARocha/plasystem
plasystem/settings.py
Python
mit
3,017
// // MonsterManager.cpp // LuoBoGuard // // Created by jwill on 16/2/26. // // #include "MonsterManager.hpp" #include "PointConvertCtrl.hpp" MonsterManager* MonsterManager::s_sharedMonsterManager = nullptr; MonsterManager* MonsterManager::getInstance() { if (s_sharedMonsterManager == nullptr) { s_sharedMonsterManager = new (std::nothrow) MonsterManager(); if(!s_sharedMonsterManager->init()) { delete s_sharedMonsterManager; s_sharedMonsterManager = nullptr; CCLOG("ERROR: Could not init MonsterManager"); } } return s_sharedMonsterManager; } void MonsterManager::destroyInstance() { CC_SAFE_DELETE(s_sharedMonsterManager); } MonsterManager::MonsterManager(){ loadMonster(); } MonsterManager::~MonsterManager(){ SpriteFrameCache::getInstance()->removeUnusedSpriteFrames(); } bool MonsterManager::init() { return true; } void MonsterManager::loadRoute(__Array* mapArr){ _mapArr=mapArr; _mapArr->retain(); } void MonsterManager::loadMonster(){ SpriteFrameCache::getInstance()->addSpriteFramesWithFile("Resource/Monsters01.plist", "Resource/Monsters01.png"); char missonName[20]; int randomI=1+floor(rand_0_1()*2); sprintf(missonName,"land_nima0%d.png",randomI); SpriteFrame *spf=SpriteFrameCache::getInstance()->getSpriteFrameByName(missonName); _monster=MonsterSprite::createWithSF(spf); _monster->setActionName("land_nima0"); _monster->setCurPointId(0); } Point MonsterManager::getStartPoint(){ __String *firstPS=(__String*)_mapArr->getObjectAtIndex(0); Point firstP=PointFromString(firstPS->getCString()); return firstP; } void MonsterManager::startGo(){ long mapCount=_mapArr->count()-1; if (_monster->getCurPointId()<mapCount) { _monster->move(); int nextId=_monster->getCurPointId()+1; __String *pointStr=(__String*)_mapArr->getObjectAtIndex(nextId); Point nextP_fake=PointFromString(pointStr->getCString()); Point nextp_real=PointConvertCtrl::getInstance()->convertFakePoint(nextP_fake); log("->(%.2f,%.2f)",nextp_real.x,nextp_real.y); // auto callFunc = CallFunc::create(this,callfunc_selector(MonsterManager::startGo)); auto callFunc=CallFunc::create(CC_CALLBACK_0(MonsterManager::startGo, this)); auto moveTo = MoveTo::create(2, nextp_real); auto action = Sequence::create(moveTo,callFunc,NULL); _monster->setCurPointId(nextId); _monster->runAction(action); }else{ _monster->stop(); log("arrived"); } } //void MonsterManager::endGo(){ // log("next"); // long mapCount=_mapArr->count(); // if (_monster->getCurPointId()<mapCount) { // int nextId=_monster->getCurPointId()+1; // __String *pointStr=(__String*)_mapArr->getObjectAtIndex(nextId); // Point nextP_fake=PointFromString(pointStr->getCString()); // Point nextp_real=PointConvertCtrl::getInstance()->convertFakePoint(nextP_fake); // // auto callFunc = CallFunc::create(this,callfunc_selector(MonsterManager::startGo)); // auto callFunc=CallFunc::create(CC_CALLBACK_0(MonsterManager::endGo, this)); // auto moveTo = MoveTo::create(2, nextp_real); // auto action = Sequence::create(moveTo,callFunc,NULL); // _monster->runAction(action); // }else{ // log("arrived"); // } //}
cjddny/cocos2d_guardCarrot
Classes/MonsterManager.cpp
C++
mit
3,430
//initialize Settings. zsi.init({ baseURL : base_url ,errorUpdateURL : base_url + "common/errors_update" ,sqlConsoleName : "runsql" ,excludeAjaxWatch : ["checkDataExist","employe_search_json"] }); //check cookie and load user menus. var userInfo = readCookie("userinfo"); if(userInfo){ if(isLocalStorageSupport()) { userInfo = JSON.parse(localStorage.getItem("userinfo")); var menuInfo = localStorage.getItem("menuInfo"); if(menuInfo){ displayMenu( JSON.parse(menuInfo)); } }else{ loadMenu(); loadUserInfo(); } }else{ loadMenu(); loadUserInfo(); } function isLocalStorageSupport(){ if(typeof(Storage) !== "undefined") return true; else return false; } function loadMenu(){ $.getJSON(base_url + "menu_types/getdata_json",function(data){ if(isLocalStorageSupport()) { localStorage.setItem("menuInfo", JSON.stringify(data)); } displayMenu(data); }); } function loadUserInfo(){ $.getJSON(base_url + "users/getuserinfo",function(data){ createCookie("userinfo", "*",1); localStorage.setItem("userinfo", JSON.stringify(data)); userInfo = data; }); } function displayMenu(data){ var nav = $("#navbar-main"); var m = '<ul class="nav navbar-nav">'; $.each(data,function(){ var mlength= this.subMenus.length; m += '<li class="dropdown">'; m += '<a data-toggle="dropdown" class="dropdown-toggle" href="#">' + this.name + ( mlength >0 ? '<span class="caret"></span>':'') + '</a>'; if(mlength>0){ m +='<ul class="dropdown-menu">'; $.each(this.subMenus,function(){ m +='<li><a href="' + base_url + this.url + '">' + this.name + '</a></li>'; }); m +='</ul>'; } m += '</>'; }); m +='<url>'; nav.append(m); }
smager/app-ci01
assets/js/jsdb/zsi_init.js
JavaScript
mit
2,098
//using System; //using System.Collections.Generic; //using System.Text; //namespace Discord.Addons.Preconditions //{ // public sealed class CommandTimeout // { // public uint TimesInvoked { get; set; } // public DateTime FirstInvoke { get; } // public CommandTimeout(DateTime timeStarted) // { // FirstInvoke = timeStarted; // } // } //}
Joe4evr/Discord.Addons
src/Discord.Addons.Preconditions/Ratelimit/CommandTimeout.cs
C#
mit
399
// Copyright (c) 2013 Guillaume Lebur. All rights reserved. // // This software may be modified and distributed under the terms // of the MIT license. See the LICENSE file for details. using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace Ninteract.Engine { internal static class MethodFormatter { public static string GetShortFormattedMethodCall<T>(Expression<Action<T>> tellAction) where T : class { var tellMethodCall = ((MethodCallExpression)tellAction.Body); return GetShortFormattedMethodCall(tellMethodCall); } public static string GetShortFormattedMethodCall<T, TResult>(Expression<Func<T, TResult>> askFunction) where T : class { var askMethodCall = ((MethodCallExpression)askFunction.Body); return GetShortFormattedMethodCall(askMethodCall); } public static string GetShortFormattedMethodCall<T>(Expression<Predicate<T>> predicate) { return predicate.Body.ToString(); } public static string GetFormattedMethodCallWithReturnType<T, TResult>(Expression<Func<T, TResult>> askFunction) where T : class { var askMethodCall = ((MethodCallExpression)askFunction.Body); return GetFormattedMethodCallWithReturnType(askMethodCall); } public static string GetFormattedPropertyCall<T, TResult>(Expression<Func<T, TResult>> propertyCall) where T : class { var propertyAccess = ((MemberExpression)propertyCall.Body); return propertyAccess.Member.Name; } private static string GetShortFormattedMethodCall(MethodCallExpression methodCall) { var parameters = GetFormattedParameters(methodCall); var formattedMethodName = GetFormattedMethodName(methodCall); return string.Format("{0}({1})", formattedMethodName, String.Join(",", parameters)); } private static string GetFormattedMethodCallWithReturnType(MethodCallExpression methodCall) { return string.Format("{0} {1}", methodCall.Method.ReturnType.Name, GetShortFormattedMethodCall(methodCall)); } private static string GetFormattedMethodName(MethodCallExpression methodCall) { string formattedMethodName; if (methodCall.Method.IsGenericMethod) { formattedMethodName = string.Format("{0}<{1}>", methodCall.Method.Name, string.Join(",", methodCall.Method.GetGenericArguments() .Select(type => type.Name))); } else { formattedMethodName = methodCall.Method.Name; } return formattedMethodName; } private static IEnumerable<string> GetFormattedParameters(MethodCallExpression methodCall) { var parameters = new List<string>(); foreach (Expression argument in methodCall.Arguments) { if (argument == null) { parameters.Add("null"); } else if (argument.NodeType == ExpressionType.Call) { LambdaExpression lambda = Expression.Lambda(argument); parameters.Add(GetShortFormattedMethodCall((MethodCallExpression) lambda.Body)); } else { parameters.Add(argument.ToString()); } } return parameters; } } }
infosaurus/NInteract
Ninteract.Engine/MethodFormatter.cs
C#
mit
3,899
class CreateSourceFiles < ActiveRecord::Migration def change create_table :source_files do |t| t.string :name t.text :source t.text :coverage t.belongs_to :job t.timestamps end end end
xing/hardcover
db/migrate/20140912130759_create_source_files.rb
Ruby
mit
228
<?php header('Access-Control-Allow-Origin: https://dayhmk.github.io'); require '../utils.php'; $text = file_get_contents("http://www2.newton.k12.ma.us/~michael_moran/?OpenItemURL=S084A1442"); $text = util_split(REGEX_DAYS, $text, 1, 0); $text = util_split("/-----------------------/", $text, 0, 0); $text = util_split("/(english:|english)/i", $text, 1, 1); $text = util_split(REGEX_CLASSES, $text, 0, 0); $text = util_split("/(top of page)/i", $text, 0, SPLIT_ONE); echo_json(finalize($text), "http://www2.newton.k12.ma.us/~michael_moran/", "Mr.Moran's Website"); ?>
dayhmk/Homework-Proxy
web/sky/english.php
PHP
mit
578
var recLength = 0, recBuffers = [], sampleRate; this.onmessage = function(e){ switch(e.data.command){ case 'init': init(e.data.config); break; case 'record': record(e.data.buffer); break; case 'exportWAV': exportWAV(e.data.type); break; case 'getBuffer': getBuffer(); break; case 'clear': clear(); break; } }; function init(config){ sampleRate = config.sampleRate; } function record(inputBuffer){ var bufferL = inputBuffer[0]; var bufferR = inputBuffer[1]; var interleaved = interleave(bufferL, bufferR); recBuffers.push(interleaved); recLength += interleaved.length; } function exportWAV(type){ var buffer = mergeBuffers(recBuffers, recLength); var dataview = encodeWAV(buffer); var audioBlob = new Blob([dataview], { type: type }); this.postMessage(audioBlob); } function getBuffer() { var buffer = mergeBuffers(recBuffers, recLength) this.postMessage(buffer); } function clear(){ recLength = 0; recBuffers = []; } function mergeBuffers(recBuffers, recLength){ var result = new Float32Array(recLength); var offset = 0; for (var i = 0; i < recBuffers.length; i++){ result.set(recBuffers[i], offset); offset += recBuffers[i].length; } return result; } function interleave(inputL, inputR){ var length = inputL.length + inputR.length; var result = new Float32Array(length); var index = 0, inputIndex = 0; while (index < length){ result[index++] = inputL[inputIndex]; result[index++] = inputR[inputIndex]; inputIndex++; } return result; } function floatTo16BitPCM(output, offset, input){ for (var i = 0; i < input.length; i++, offset+=2){ var s = Math.max(-1, Math.min(1, input[i])); output.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7FFF, true); } } function writeString(view, offset, string){ for (var i = 0; i < string.length; i++){ view.setUint8(offset + i, string.charCodeAt(i)); } } function encodeWAV(samples){ var buffer = new ArrayBuffer(44 + samples.length * 2); var view = new DataView(buffer); /* RIFF identifier */ writeString(view, 0, 'RIFF'); /* file length */ view.setUint32(4, 32 + samples.length * 2, true); /* RIFF type */ writeString(view, 8, 'WAVE'); /* format chunk identifier */ writeString(view, 12, 'fmt '); /* format chunk length */ view.setUint32(16, 16, true); /* sample format (raw) */ view.setUint16(20, 1, true); /* channel count */ view.setUint16(22, 2, true); /* sample rate */ view.setUint32(24, sampleRate, true); /* byte rate (sample rate * block align) */ view.setUint32(28, sampleRate * 4, true); /* block align (channel count * bytes per sample) */ view.setUint16(32, 4, true); /* bits per sample */ view.setUint16(34, 16, true); /* data chunk identifier */ writeString(view, 36, 'data'); /* data chunk length */ view.setUint32(40, samples.length * 2, true); floatTo16BitPCM(view, 44, samples); return view; }
dgaspari/tonetrainer
client/scripts/app/recorder/recorderWorker.js
JavaScript
mit
3,005
class Api::MobileAppsController < ApplicationController respond_to :json def show @mobile_app = MobileApp.first render json: @mobile_app end end
LinkToMyApp/linktomyapp
app/controllers/api/mobile_apps_controller.rb
Ruby
mit
153
function dialogoCV() { var dialogo = getDiv(); var actualizarDialogoPsiquica = function() { var titulo; var contenido; var cvLibres = personaje_actual.getHabilidadDePersonaje(HB_CV).valorFinalActual() - personaje_actual.getCVGastados(); dialogo.empty(); /** * CVs, potencial psíquico e innatos */ dialogo.append(muestraSubtitulo(UI_CVS_POTENCIAL, false, false, [])); var divHabilidades = getDiv(); divHabilidades.append(muestraCabecerasBaseBonosFinal()); var divCVs = getDiv().append(muestraHabilidadPrimaria(HB_CV,_l(UI_CV),true)); var divCVsLibres = getDiv().append(muestraValorPuntual(0,_l(UI_CV_LIBRES),cvLibres,{})); var divPotencial = getDiv().append(muestraHabilidadPrimaria(HB_POTENCIAL_PSIQUICO,_l(UI_POTENCIAL_PSIQUICO),true)); var botonMasInnato = boton("small primary pretty btn",_l("+"),(cvLibres < 2)); var botonMenosInnato = boton("small secondary pretty btn",_l("-"),(personaje_actual.getInnatosPsiquicos() == 0)); var divBotones = getDiv().append(botonMasInnato).append(botonMenosInnato); var divInnatos = getDiv().append(muestraValorPuntual("2 CV",_l(UI_INNATO),personaje_actual.getInnatosPsiquicos(),{},divBotones)); botonMasInnato.on("click", {cantidad: 1}, comprarInnato); botonMenosInnato.on("click", {cantidad: -1}, comprarInnato); divHabilidades.append(divCVs).append(divCVsLibres).append(divPotencial).append(divInnatos); dialogo.append(divHabilidades); /** * Disciplinas y poderes */ dialogo.append(muestraSubtitulo(UI_DISCIPLINAS_DOMINADAS, false, false, [])); var botonAfinidadDisciplinaDisabled = false; if (cvLibres < 1) { botonAfinidadDisciplinaDisabled = true; } if (!personaje_actual.hasFlag(FLAG_PSIQUICO)) { botonAfinidadDisciplinaDisabled = true; } else if (!personaje_actual.hasFlag(FLAG_ACCESO_TODAS_DISCIPLINAS)) { if (personaje_actual.getDisciplinasPsiquicas().length == personaje_actual.getAccesoDisciplinas().length) { botonAfinidadDisciplinaDisabled = true; } } var divBotonNuevaDisciplina = muestraBotonPequeño(_l(UI_AFINIDAD_CON_NUEVA_DISCIPLINA) + "[1 " + _l(UI_CV) + "]",{},afinidadNuevaDisciplina,""); //boton("medium primary pretty btn",,botonAfinidadDisciplinaDisabled); dialogo.append(divBotonNuevaDisciplina); if (botonAfinidadDisciplinaDisabled) { disableButton(divBotonNuevaDisciplina); } var zonasDisciplinas = getDiv(); /** * * @type {DisciplinaPsiquicaAccedida[]} */ var disciplinasPsiquicas = personaje_actual.getDisciplinasPsiquicas(); for (var i = 0; i < disciplinasPsiquicas.length; i++) { titulo = $("<h3></h3>").append(_l(disciplinasPsiquicas[i].getNombre())); titulo.append(muestraBotonAnular(eliminarAfinidadDisciplina,{disciplina: disciplinasPsiquicas[i]})); contenido = getDiv().attr("id","disciplinaPsiquica" + disciplinasPsiquicas[i].getNombre().replace(/\s+/g, '')); appendPoderesPsiquicos(contenido,disciplinasPsiquicas[i].disciplina); zonasDisciplinas.append(titulo).append(contenido); } var poderesMatriciales = getDisciplina(DISCIPLINA_PODERES_MATRICIALES); titulo = $("<h3></h3>").append(_l(poderesMatriciales.getNombre())); contenido = getDiv().attr("id","disciplinaPsiquica" + poderesMatriciales.getNombre().replace(/\s+/g, '')); if (personaje_actual.hasFlag(FLAG_PSIQUICO)) { appendPoderesPsiquicos(contenido,poderesMatriciales); } zonasDisciplinas.append(titulo).append(contenido); zonasDisciplinas.accordion({ heightStyle: "content" }); dialogo.append(zonasDisciplinas); }; actualizarDialogoPsiquica(); dialogo.dialog({ modal: true, autoOpen: true, resizable: true, draggable: true, title: _l(DIAG_PODERES_PSIQUICOS), position: "center", width: ANCHO_DIALOGO, height: ALTO_DIALOGO, maxHeight: ALTO_DIALOGO, closeOnEscape: true }); dialogo.on("close",function( event, ui ) { dialogo.empty(); removeActualizador(EVENT_CHARACTER_SECCION_PSIQUICA,actualizarDialogoPsiquica); }); addActualizador(EVENT_CHARACTER_SECCION_PSIQUICA,actualizarDialogoPsiquica); } function appendPoderesPsiquicos(elemento, disciplinaPsiquica) { var poderesDominados = personaje_actual.getPoderesDominadosDisciplina(disciplinaPsiquica); var noQuedanCV = (personaje_actual.getHabilidadDePersonaje(HB_CV).valorFinalActual()-personaje_actual.getCVGastados() == 0); var nuevoPoder = muestraBotonPequeño(_l(UI_DOMINAR_NUEVO_PODER) + "[1 " + _l(UI_CV) + "]",{disciplina: disciplinaPsiquica},elegirPoderADominar,""); elemento.append(nuevoPoder); if (((poderesDominados.length == disciplinaPsiquica.getPoderesPsiquicos().length) || noQuedanCV)) { disableButton(nuevoPoder); } for (var i = 0; i < poderesDominados.length; i++) { var poder = poderesDominados[i]; var divPoder = getDiv(); var botonMas = boton("small primary pretty btn",_l("+"),((poder.getFortalecimiento() == 10) || noQuedanCV)); var botonMenos = boton("small primary pretty btn",_l("-"),(poder.getFortalecimiento() == 0)); var divBotones = getDiv().append(botonMas).append(botonMenos); var labelPoder = muestraValorPuntual(" " + _l(UI_NV) + ":" + poder.getPoder().getNivel() + " ",_l(poder.getPoder().getNombre()),poder.getFortalecimiento()*10,{descripcion:_l(UI_POTENCIAL)},divBotones); divPoder.append(labelPoder); botonMas.on("click", {disciplina: disciplinaPsiquica, poder: poder, cantidad: 1}, fortalecerPoderPsiquico); botonMenos.on("click", {disciplina: disciplinaPsiquica, poder: poder, cantidad: -1}, fortalecerPoderPsiquico); divPoder.append(botonMas).append(botonMenos).append(muestraBotonAnular(eliminarPoderDominado,{disciplina: disciplinaPsiquica, poder: poder})); elemento.append(divPoder); } } function elegirPoderADominar(event) { var disciplina = event.data.disciplina; var arrayOpciones = []; var poderesPsiquicos = disciplina.getPoderesPsiquicos(); for (var j = 0; j < poderesPsiquicos.length; j++) { var poder = poderesPsiquicos[j]; arrayOpciones.push(new OpcionMostrable(_l(poder.getNombre()),poder.getNombre(),"",_l(poder.getDescripcion()))); } muestraDialogoElegirOpciones(arrayOpciones, {disciplina: disciplina}, {principal: dominarPoder, isDisabled: noPuedeDominarPoder}, true); }
wwhere/animaunico
js/view/Psiquica_vw.js
JavaScript
mit
6,863
/* ** GENEREATED FILE - DO NOT MODIFY ** */ package com.wilutions.mslib.outlook; import com.wilutions.com.*; /** * OlFormatInteger. * */ @SuppressWarnings("all") @CoInterface(guid="{00000000-0000-0000-0000-000000000000}") public class OlFormatInteger implements ComEnum { static boolean __typelib__loaded = __TypeLib.load(); // Typed constants public final static OlFormatInteger olFormatIntegerPlain = new OlFormatInteger(1); public final static OlFormatInteger olFormatIntegerComputer1 = new OlFormatInteger(2); public final static OlFormatInteger olFormatIntegerComputer2 = new OlFormatInteger(3); public final static OlFormatInteger olFormatIntegerComputer3 = new OlFormatInteger(4); // Integer constants for bitsets and switch statements public final static int _olFormatIntegerPlain = 1; public final static int _olFormatIntegerComputer1 = 2; public final static int _olFormatIntegerComputer2 = 3; public final static int _olFormatIntegerComputer3 = 4; // Value, readonly field. public final int value; // Private constructor, use valueOf to create an instance. private OlFormatInteger(int value) { this.value = value; } // Return one of the predefined typed constants for the given value or create a new object. public static OlFormatInteger valueOf(int value) { switch(value) { case 1: return olFormatIntegerPlain; case 2: return olFormatIntegerComputer1; case 3: return olFormatIntegerComputer2; case 4: return olFormatIntegerComputer3; default: return new OlFormatInteger(value); } } public String toString() { switch(value) { case 1: return "olFormatIntegerPlain"; case 2: return "olFormatIntegerComputer1"; case 3: return "olFormatIntegerComputer2"; case 4: return "olFormatIntegerComputer3"; default: { StringBuilder sbuf = new StringBuilder(); sbuf.append("[").append(value).append("="); if ((value & 1) != 0) sbuf.append("|olFormatIntegerPlain"); if ((value & 2) != 0) sbuf.append("|olFormatIntegerComputer1"); if ((value & 3) != 0) sbuf.append("|olFormatIntegerComputer2"); if ((value & 4) != 0) sbuf.append("|olFormatIntegerComputer3"); return sbuf.toString(); } } } }
wolfgangimig/joa
java/joa/src-gen/com/wilutions/mslib/outlook/OlFormatInteger.java
Java
mit
2,302
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ if (file_exists($file = __DIR__.'/autoload.php')) { require_once $file; } elseif (file_exists($file = __DIR__.'/autoload.php.dist')) { require_once $file; }
songecko/legem-ecommerce
src/Sylius/Bundle/FlowBundle/Tests/bootstrap.php
PHP
mit
401
//-------------------------------------------------------------------------------------- // File: Game.cpp // // Developer unit test for DirectXTK GamePad // // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 //-------------------------------------------------------------------------------------- #include "pch.h" #include "Game.h" #ifdef GAMEINPUT #include <GameInput.h> #endif #define GAMMA_CORRECT_RENDERING #define USE_FAST_SEMANTICS #if defined(COREWINDOW) || defined(WGI) #include <Windows.UI.Core.h> #endif extern void ExitGame() noexcept; using namespace DirectX; using Microsoft::WRL::ComPtr; static_assert(std::is_nothrow_move_constructible<GamePad>::value, "Move Ctor."); static_assert(std::is_nothrow_move_assignable<GamePad>::value, "Move Assign."); static_assert(std::is_nothrow_move_constructible<GamePad::ButtonStateTracker>::value, "Move Ctor."); static_assert(std::is_nothrow_move_assignable<GamePad::ButtonStateTracker>::value, "Move Assign."); // Constructor. Game::Game() noexcept(false) : m_state{}, m_lastStr(nullptr) { #ifdef GAMMA_CORRECT_RENDERING const DXGI_FORMAT c_RenderFormat = DXGI_FORMAT_B8G8R8A8_UNORM_SRGB; #else const DXGI_FORMAT c_RenderFormat = DXGI_FORMAT_B8G8R8A8_UNORM; #endif // 2D only rendering #ifdef XBOX m_deviceResources = std::make_unique<DX::DeviceResources>( c_RenderFormat, DXGI_FORMAT_UNKNOWN, 2, DX::DeviceResources::c_Enable4K_UHD #ifdef USE_FAST_SEMANTICS | DX::DeviceResources::c_FastSemantics #endif ); #elif defined(UWP) m_deviceResources = std::make_unique<DX::DeviceResources>( c_RenderFormat, DXGI_FORMAT_UNKNOWN, 2, D3D_FEATURE_LEVEL_9_3, DX::DeviceResources::c_Enable4K_Xbox ); #else m_deviceResources = std::make_unique<DX::DeviceResources>(c_RenderFormat, DXGI_FORMAT_UNKNOWN); #endif #ifdef LOSTDEVICE m_deviceResources->RegisterDeviceNotify(this); #endif } // Initialize the Direct3D resources required to run. void Game::Initialize( #ifdef COREWINDOW IUnknown* window, #else HWND window, #endif int width, int height, DXGI_MODE_ROTATION rotation) { #ifdef XBOX UNREFERENCED_PARAMETER(rotation); UNREFERENCED_PARAMETER(width); UNREFERENCED_PARAMETER(height); m_deviceResources->SetWindow(window); #elif defined(UWP) m_deviceResources->SetWindow(window, width, height, rotation); #else UNREFERENCED_PARAMETER(rotation); m_deviceResources->SetWindow(window, width, height); #endif m_gamePad = std::make_unique<GamePad>(); #ifdef PC // Singleton test { bool thrown = false; try { auto gamePad2 = std::make_unique<GamePad>(); } catch (...) { thrown = true; } if (!thrown) { MessageBoxW(window, L"GamePad not acting like a singleton", L"GamePadTest", MB_ICONERROR); throw std::runtime_error("GamePad not acting like a singleton"); } } #endif #ifdef GAMEINPUT m_ctrlChanged.Attach(CreateEvent(nullptr, FALSE, FALSE, nullptr)); if (!m_ctrlChanged.IsValid()) { throw std::system_error(std::error_code(static_cast<int>(GetLastError()), std::system_category()), "CreateEvent"); } m_gamePad->RegisterEvents(m_ctrlChanged.Get()); #elif defined(COREWINDOW) m_ctrlChanged.Attach(CreateEvent(nullptr, FALSE, FALSE, nullptr)); m_userChanged.Attach(CreateEvent(nullptr, FALSE, FALSE, nullptr)); if (!m_ctrlChanged.IsValid() || !m_userChanged.IsValid()) { throw std::system_error(std::error_code(static_cast<int>(GetLastError()), std::system_category()), "CreateEvent"); } m_gamePad->RegisterEvents( m_ctrlChanged.Get(), m_userChanged.Get() ); #endif m_found.reset(new bool[GamePad::MAX_PLAYER_COUNT] ); memset(m_found.get(), 0, sizeof(bool) * GamePad::MAX_PLAYER_COUNT); m_deviceResources->CreateDeviceResources(); CreateDeviceDependentResources(); m_deviceResources->CreateWindowSizeDependentResources(); CreateWindowSizeDependentResources(); } #pragma region Frame Update // Executes the basic game loop. void Game::Tick() { m_timer.Tick([&]() { Update(m_timer); }); Render(); } // Updates the world. void Game::Update(DX::StepTimer const&) { m_state.connected = false; #ifdef GAMEINPUT if (WaitForSingleObject(m_ctrlChanged.Get(), 0) == WAIT_OBJECT_0) { OutputDebugStringA("EVENT: Controller changed\n"); } #elif defined(COREWINDOW) HANDLE events[2] = { m_ctrlChanged.Get(), m_userChanged.Get() }; switch (WaitForMultipleObjects(static_cast<DWORD>(std::size(events)), events, FALSE, 0)) { case WAIT_OBJECT_0: OutputDebugStringA("EVENT: Controller changed\n"); break; case WAIT_OBJECT_0 + 1: OutputDebugStringA("EVENT: User changed\n"); break; } #endif for (int j = 0; j < GamePad::MAX_PLAYER_COUNT; ++j) { auto state2 = m_gamePad->GetState(j); auto caps = m_gamePad->GetCapabilities(j); assert(state2.IsConnected() == caps.IsConnected()); if (state2.IsConnected()) { if (!m_found[size_t(j)]) { m_found[size_t(j)] = true; if (caps.IsConnected()) { #ifdef GAMEINPUT char idstr[128] = {}; for (size_t l = 0; l < APP_LOCAL_DEVICE_ID_SIZE; ++l) { sprintf_s(idstr + l * 2, 128 - l * 2, "%02x", caps.id.value[l]); } char buff[128] = {}; sprintf_s(buff, "Player %d -> connected (type %u, %04X/%04X, id %s)\n", j, caps.gamepadType, caps.vid, caps.pid, idstr); OutputDebugStringA(buff); { ComPtr<IGameInputDevice> idevice; m_gamePad->GetDevice(j, idevice.GetAddressOf()); if (!idevice) { OutputDebugStringA(" **ERROR** GetDevice failed unexpectedly\n"); } else { GameInputBatteryState battery; idevice->GetBatteryState(&battery); switch (battery.status) { case GameInputBatteryUnknown: break; case GameInputBatteryNotPresent: OutputDebugStringA(" Battery not present\n"); break; case GameInputBatteryDischarging: OutputDebugStringA(" Battery discharging\n"); break; case GameInputBatteryIdle: OutputDebugStringA(" Battery idle\n"); break; case GameInputBatteryCharging: OutputDebugStringA(" Battery charging\n"); break; } } } #elif defined(WGI) if (!caps.id.empty()) { using namespace Microsoft::WRL; using namespace Microsoft::WRL::Wrappers; using namespace ABI::Windows::Foundation; using namespace ABI::Windows::System; ComPtr<IUserStatics> statics; DX::ThrowIfFailed(GetActivationFactory(HStringReference(RuntimeClass_Windows_System_User).Get(), statics.GetAddressOf())); ComPtr<IUser> user; HString str; str.Set(caps.id.c_str(), static_cast<unsigned int>(caps.id.length())); HRESULT hr = statics->GetFromId(str.Get(), user.GetAddressOf()); if (SUCCEEDED(hr)) { UserType userType = UserType_RemoteUser; DX::ThrowIfFailed(user->get_Type(&userType)); char buff[1024] = {}; sprintf_s(buff, "Player %d -> connected (type %u, %04X/%04X, id \"%ls\" (user found))\n", j, caps.gamepadType, caps.vid, caps.pid, caps.id.c_str()); OutputDebugStringA(buff); } else { char buff[1024] = {}; sprintf_s(buff, "Player %d -> connected (type %u, %04X/%04X, id \"%ls\" (user fail %08X))\n", j, caps.gamepadType, caps.vid, caps.pid, caps.id.c_str(), static_cast<unsigned int>(hr)); OutputDebugStringA(buff); } } else { char buff[64] = {}; sprintf_s(buff, "Player %d -> connected (type %u, %04X/%04X, id is empty!)\n", j, caps.gamepadType, caps.vid, caps.pid); OutputDebugStringA(buff); } #else char buff[64] = {}; sprintf_s(buff, "Player %d -> connected (type %u, %04X/%04X, id %llu)\n", j, caps.gamepadType, caps.vid, caps.pid, caps.id); OutputDebugStringA(buff); #endif } } } else { if (m_found[size_t(j)]) { m_found[size_t(j)] = false; char buff[32]; sprintf_s(buff, "Player %d <- disconnected\n", j); OutputDebugStringA(buff); } } } m_state = m_gamePad->GetState(GamePad::c_MostRecent); if (m_state.IsConnected()) { m_tracker.Update(m_state); using ButtonState = GamePad::ButtonStateTracker::ButtonState; if (m_tracker.a == ButtonState::PRESSED) m_lastStr = L"Button A was pressed\n"; else if (m_tracker.a == ButtonState::RELEASED) m_lastStr = L"Button A was released\n"; else if (m_tracker.b == ButtonState::PRESSED) m_lastStr = L"Button B was pressed\n"; else if (m_tracker.b == ButtonState::RELEASED) m_lastStr = L"Button B was released\n"; else if (m_tracker.x == ButtonState::PRESSED) m_lastStr = L"Button X was pressed\n"; else if (m_tracker.x == ButtonState::RELEASED) m_lastStr = L"Button X was released\n"; else if (m_tracker.y == ButtonState::PRESSED) m_lastStr = L"Button Y was pressed\n"; else if (m_tracker.y == ButtonState::RELEASED) m_lastStr = L"Button Y was released\n"; else if (m_tracker.leftStick == ButtonState::PRESSED) m_lastStr = L"Button LeftStick was pressed\n"; else if (m_tracker.leftStick == ButtonState::RELEASED) m_lastStr = L"Button LeftStick was released\n"; else if (m_tracker.rightStick == ButtonState::PRESSED) m_lastStr = L"Button RightStick was pressed\n"; else if (m_tracker.rightStick == ButtonState::RELEASED) m_lastStr = L"Button RightStick was released\n"; else if (m_tracker.leftShoulder == ButtonState::PRESSED) m_lastStr = L"Button LeftShoulder was pressed\n"; else if (m_tracker.leftShoulder == ButtonState::RELEASED) m_lastStr = L"Button LeftShoulder was released\n"; else if (m_tracker.rightShoulder == ButtonState::PRESSED) m_lastStr = L"Button RightShoulder was pressed\n"; else if (m_tracker.rightShoulder == ButtonState::RELEASED) m_lastStr = L"Button RightShoulder was released\n"; else if (m_tracker.view == ButtonState::PRESSED) m_lastStr = L"Button BACK/VIEW was pressed\n"; else if (m_tracker.view == ButtonState::RELEASED) m_lastStr = L"Button BACK/VIEW was released\n"; else if (m_tracker.menu == ButtonState::PRESSED) m_lastStr = L"Button START/MENU was pressed\n"; else if (m_tracker.menu == ButtonState::RELEASED) m_lastStr = L"Button START/MENU was released\n"; else if (m_tracker.dpadUp == ButtonState::PRESSED) m_lastStr = L"Button DPAD UP was pressed\n"; else if (m_tracker.dpadUp == ButtonState::RELEASED) m_lastStr = L"Button DPAD UP was released\n"; else if (m_tracker.dpadDown == ButtonState::PRESSED) m_lastStr = L"Button DPAD DOWN was pressed\n"; else if (m_tracker.dpadDown == ButtonState::RELEASED) m_lastStr = L"Button DPAD DOWN was released\n"; else if (m_tracker.dpadLeft == ButtonState::PRESSED) m_lastStr = L"Button DPAD LEFT was pressed\n"; else if (m_tracker.dpadLeft == ButtonState::RELEASED) m_lastStr = L"Button DPAD LEFT was released\n"; else if (m_tracker.dpadRight == ButtonState::PRESSED) m_lastStr = L"Button DPAD RIGHT was pressed\n"; else if (m_tracker.dpadRight == ButtonState::RELEASED) m_lastStr = L"Button DPAD RIGHT was released\n"; else if (m_tracker.leftStickUp == ButtonState::PRESSED) m_lastStr = L"Button LEFT STICK was pressed UP\n"; else if (m_tracker.leftStickUp == ButtonState::RELEASED) m_lastStr = L"Button LEFT STICK was released from UP\n"; else if (m_tracker.leftStickDown == ButtonState::PRESSED) m_lastStr = L"Button LEFT STICK was pressed DOWN\n"; else if (m_tracker.leftStickDown == ButtonState::RELEASED) m_lastStr = L"Button LEFT STICK was released from DOWN\n"; else if (m_tracker.leftStickLeft == ButtonState::PRESSED) m_lastStr = L"Button LEFT STICK was pressed LEFT\n"; else if (m_tracker.leftStickLeft == ButtonState::RELEASED) m_lastStr = L"Button LEFT STICK was released from LEFT\n"; else if (m_tracker.leftStickRight == ButtonState::PRESSED) m_lastStr = L"Button LEFT STICK was pressed RIGHT\n"; else if (m_tracker.leftStickRight == ButtonState::RELEASED) m_lastStr = L"Button LEFT STICK was released from RIGHT\n"; else if (m_tracker.rightStickUp == ButtonState::PRESSED) m_lastStr = L"Button RIGHT STICK was pressed UP\n"; else if (m_tracker.rightStickUp == ButtonState::RELEASED) m_lastStr = L"Button RIGHT STICK was released from UP\n"; else if (m_tracker.rightStickDown == ButtonState::PRESSED) m_lastStr = L"Button RIGHT STICK was pressed DOWN\n"; else if (m_tracker.rightStickDown == ButtonState::RELEASED) m_lastStr = L"Button RIGHT STICK was released from DOWN\n"; else if (m_tracker.rightStickLeft == ButtonState::PRESSED) m_lastStr = L"Button RIGHT STICK was pressed LEFT\n"; else if (m_tracker.rightStickLeft == ButtonState::RELEASED) m_lastStr = L"Button RIGHT STICK was released from LEFT\n"; else if (m_tracker.rightStickRight == ButtonState::PRESSED) m_lastStr = L"Button RIGHT STICK was pressed RIGHT\n"; else if (m_tracker.rightStickRight == ButtonState::RELEASED) m_lastStr = L"Button RIGHT STICK was released from RIGHT\n"; else if (m_tracker.leftTrigger == ButtonState::PRESSED) m_lastStr = L"Button LEFT TRIGGER was pressed\n"; else if (m_tracker.leftTrigger == ButtonState::RELEASED) m_lastStr = L"Button LEFT TRIGGER was released\n"; else if (m_tracker.rightTrigger == ButtonState::PRESSED) m_lastStr = L"Button RIGHT TRIGGER was pressed\n"; else if (m_tracker.rightTrigger == ButtonState::RELEASED) m_lastStr = L"Button RIGHT TRIGGER was released\n"; assert(m_tracker.back == m_tracker.view); assert(m_tracker.start == m_tracker.menu); m_gamePad->SetVibration(GamePad::c_MostRecent, m_state.triggers.left, m_state.triggers.right); } else { memset(&m_state, 0, sizeof(GamePad::State)); m_lastStr = nullptr; m_tracker.Reset(); } } #pragma endregion #pragma region Frame Render // Draws the scene. void Game::Render() { // Don't try to render anything before the first Update. if (m_timer.GetFrameCount() == 0) { return; } XMVECTORF32 yellow; #ifdef GAMMA_CORRECT_RENDERING yellow.v = XMColorSRGBToRGB(Colors::Yellow); #else yellow.v = Colors::Yellow; #endif #ifdef XBOX m_deviceResources->Prepare(); #endif Clear(); m_spriteBatch->Begin(); for (int j = 0; j < std::min(GamePad::MAX_PLAYER_COUNT, 4); ++j) { XMVECTOR color = m_found[size_t(j)] ? Colors::White : Colors::DimGray; m_ctrlFont->DrawString(m_spriteBatch.get(), L"$", XMFLOAT2(800.f, float(50 + j * 150)), color); } if (m_lastStr) { m_comicFont->DrawString(m_spriteBatch.get(), m_lastStr, XMFLOAT2(25.f, 650.f), yellow); } // X Y A B m_ctrlFont->DrawString(m_spriteBatch.get(), L"&", XMFLOAT2(325, 150), m_state.IsXPressed() ? Colors::White : Colors::DimGray); m_ctrlFont->DrawString(m_spriteBatch.get(), L"(", XMFLOAT2(400, 110), m_state.IsYPressed() ? Colors::White : Colors::DimGray); m_ctrlFont->DrawString(m_spriteBatch.get(), L"'", XMFLOAT2(400, 200), m_state.IsAPressed() ? Colors::White : Colors::DimGray); m_ctrlFont->DrawString(m_spriteBatch.get(), L")", XMFLOAT2(475, 150), m_state.IsBPressed() ? Colors::White : Colors::DimGray); // Left/Right sticks auto loc = XMFLOAT2(10, 110); loc.x -= m_state.IsLeftThumbStickLeft() ? 20.f : 0.f; loc.x += m_state.IsLeftThumbStickRight() ? 20.f : 0.f; loc.y -= m_state.IsLeftThumbStickUp() ? 20.f : 0.f; loc.y += m_state.IsLeftThumbStickDown() ? 20.f : 0.f; m_ctrlFont->DrawString(m_spriteBatch.get(), L" ", loc, m_state.IsLeftStickPressed() ? Colors::White : Colors::DimGray, 0, XMFLOAT2(0, 0)); loc = XMFLOAT2(450, 300); loc.x -= m_state.IsRightThumbStickLeft() ? 20.f : 0.f; loc.x += m_state.IsRightThumbStickRight() ? 20.f : 0.f; loc.y -= m_state.IsRightThumbStickUp() ? 20.f : 0.f; loc.y += m_state.IsRightThumbStickDown() ? 20.f : 0.f; m_ctrlFont->DrawString(m_spriteBatch.get(), L"\"", loc, m_state.IsRightStickPressed() ? Colors::White : Colors::DimGray, 0, XMFLOAT2(0, 0)); // DPad XMVECTOR color = Colors::DimGray; if (m_state.dpad.up || m_state.dpad.down || m_state.dpad.right || m_state.dpad.left) color = Colors::White; loc = XMFLOAT2(175, 300); loc.x -= m_state.IsDPadLeftPressed() ? 20.f : 0.f; loc.x += m_state.IsDPadRightPressed() ? 20.f : 0.f; loc.y -= m_state.IsDPadUpPressed() ? 20.f : 0.f; loc.y += m_state.IsDPadDownPressed() ? 20.f : 0.f; m_ctrlFont->DrawString(m_spriteBatch.get(), L"!", loc, color); // Back/Start (aka View/Menu) m_ctrlFont->DrawString(m_spriteBatch.get(), L"#", XMFLOAT2(175, 75), m_state.IsViewPressed() ? Colors::White : Colors::DimGray); assert(m_state.IsViewPressed() == m_state.IsBackPressed()); assert(m_state.buttons.back == m_state.buttons.view); m_ctrlFont->DrawString(m_spriteBatch.get(), L"%", XMFLOAT2(300, 75), m_state.IsMenuPressed() ? Colors::White : Colors::DimGray); assert(m_state.IsMenuPressed() == m_state.IsStartPressed()); assert(m_state.buttons.start == m_state.buttons.menu); // Triggers/Shoulders m_ctrlFont->DrawString(m_spriteBatch.get(), L"*", XMFLOAT2(500, 10), m_state.IsRightShoulderPressed() ? Colors::White : Colors::DimGray, 0, XMFLOAT2(0, 0), 0.5f); loc = XMFLOAT2(450, 10); loc.x += m_state.IsRightTriggerPressed() ? 5.f : 0.f; color = XMVectorLerp(Colors::DimGray, Colors::White, m_state.triggers.right); m_ctrlFont->DrawString(m_spriteBatch.get(), L"+", loc, color, 0, XMFLOAT2(0, 0), 0.5f); loc = XMFLOAT2(130, 10); loc.x -= m_state.IsLeftTriggerPressed() ? 5.f : 0.f; color = XMVectorLerp(Colors::DimGray, Colors::White, m_state.triggers.left); m_ctrlFont->DrawString(m_spriteBatch.get(), L",", loc, color, 0, XMFLOAT2(0, 0), 0.5f); m_ctrlFont->DrawString(m_spriteBatch.get(), L"-", XMFLOAT2(10, 10), m_state.IsLeftShoulderPressed() ? Colors::White : Colors::DimGray, 0, XMFLOAT2(0, 0), 0.5f); // Sticks RECT src = { 0, 0, 1, 1 }; RECT rc; rc.top = 500; rc.left = 10; rc.bottom = 525; rc.right = rc.left + int(((m_state.thumbSticks.leftX + 1.f) / 2.f) * 275); m_spriteBatch->Draw(m_defaultTex.Get(), rc, &src); rc.top = 550; rc.bottom = 575; rc.right = rc.left + int(((m_state.thumbSticks.leftY + 1.f) / 2.f) * 275); m_spriteBatch->Draw(m_defaultTex.Get(), rc, &src); rc.top = 500; rc.left = 325; rc.bottom = 525; rc.right = rc.left + int(((m_state.thumbSticks.rightX + 1.f) / 2.f) * 275); m_spriteBatch->Draw(m_defaultTex.Get(), rc, &src); rc.top = 550; rc.bottom = 575; rc.right = rc.left + int(((m_state.thumbSticks.rightY + 1.f) / 2.f) * 275); m_spriteBatch->Draw(m_defaultTex.Get(), rc, &src); m_spriteBatch->End(); // Show the new frame. m_deviceResources->Present(); #ifdef XBOX m_graphicsMemory->Commit(); #endif } // Helper method to clear the back buffers. void Game::Clear() { // Clear the views. auto context = m_deviceResources->GetD3DDeviceContext(); auto renderTarget = m_deviceResources->GetRenderTargetView(); XMVECTORF32 color; #ifdef GAMMA_CORRECT_RENDERING color.v = XMColorSRGBToRGB(Colors::CornflowerBlue); #else color.v = Colors::CornflowerBlue; #endif context->ClearRenderTargetView(renderTarget, color); context->OMSetRenderTargets(1, &renderTarget, nullptr); // Set the viewport. auto viewport = m_deviceResources->GetScreenViewport(); context->RSSetViewports(1, &viewport); } #pragma endregion #pragma region Message Handlers // Message handlers void Game::OnActivated() { } void Game::OnDeactivated() { } void Game::OnSuspending() { m_deviceResources->Suspend(); } void Game::OnResuming() { m_deviceResources->Resume(); m_tracker.Reset(); m_timer.ResetElapsedTime(); } #ifdef PC void Game::OnWindowMoved() { auto r = m_deviceResources->GetOutputSize(); m_deviceResources->WindowSizeChanged(r.right, r.bottom); } #endif #if defined(PC) || defined(UWP) void Game::OnDisplayChange() { m_deviceResources->UpdateColorSpace(); } #endif #ifndef XBOX void Game::OnWindowSizeChanged(int width, int height, DXGI_MODE_ROTATION rotation) { #ifdef UWP if (!m_deviceResources->WindowSizeChanged(width, height, rotation)) return; #else UNREFERENCED_PARAMETER(rotation); if (!m_deviceResources->WindowSizeChanged(width, height)) return; #endif CreateWindowSizeDependentResources(); } #endif #ifdef UWP void Game::ValidateDevice() { m_deviceResources->ValidateDevice(); } #endif // Properties void Game::GetDefaultSize(int& width, int& height) const { width = 1024; height = 768; } #pragma endregion #pragma region Direct3D Resources // These are the resources that depend on the device. void Game::CreateDeviceDependentResources() { auto device = m_deviceResources->GetD3DDevice(); auto context = m_deviceResources->GetD3DDeviceContext(); #ifdef XBOX m_graphicsMemory = std::make_unique<GraphicsMemory>(device, m_deviceResources->GetBackBufferCount()); #endif m_spriteBatch = std::make_unique<SpriteBatch>(context); m_comicFont = std::make_unique<SpriteFont>(device, L"comic.spritefont"); m_ctrlFont = std::make_unique<SpriteFont>(device, L"xboxController.spritefont"); { static const uint32_t s_pixel = 0xffffffff; D3D11_SUBRESOURCE_DATA initData = { &s_pixel, sizeof(uint32_t), 0 }; D3D11_TEXTURE2D_DESC desc = {}; desc.Width = desc.Height = desc.MipLevels = desc.ArraySize = 1; desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; desc.SampleDesc.Count = 1; desc.Usage = D3D11_USAGE_IMMUTABLE; desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; ComPtr<ID3D11Texture2D> tex; DX::ThrowIfFailed(device->CreateTexture2D(&desc, &initData, &tex)); D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc = {}; SRVDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; SRVDesc.Texture2D.MipLevels = 1; DX::ThrowIfFailed(device->CreateShaderResourceView(tex.Get(), &SRVDesc, m_defaultTex.ReleaseAndGetAddressOf())); } } // Allocate all memory resources that change on a window SizeChanged event. void Game::CreateWindowSizeDependentResources() { auto viewPort = m_deviceResources->GetScreenViewport(); m_spriteBatch->SetViewport(viewPort); #ifdef XBOX if (m_deviceResources->GetDeviceOptions() & DX::DeviceResources::c_Enable4K_UHD) { // Scale sprite batch rendering when running 4k static const D3D11_VIEWPORT s_vp1080 = { 0.f, 0.f, 1920.f, 1080.f, D3D11_MIN_DEPTH, D3D11_MAX_DEPTH }; m_spriteBatch->SetViewport(s_vp1080); } #elif defined(UWP) if (m_deviceResources->GetDeviceOptions() & DX::DeviceResources::c_Enable4K_Xbox) { // Scale sprite batch rendering when running 4k static const D3D11_VIEWPORT s_vp1080 = { 0.f, 0.f, 1920.f, 1080.f, D3D11_MIN_DEPTH, D3D11_MAX_DEPTH }; m_spriteBatch->SetViewport(s_vp1080); } m_spriteBatch->SetRotation(m_deviceResources->GetRotation()); #endif } #ifdef LOSTDEVICE void Game::OnDeviceLost() { m_spriteBatch.reset(); m_comicFont.reset(); m_ctrlFont.reset(); m_defaultTex.Reset(); } void Game::OnDeviceRestored() { CreateDeviceDependentResources(); CreateWindowSizeDependentResources(); } #endif #pragma endregion
walbourn/directxtktest
GamePadTest/Game.cpp
C++
mit
25,950
package session import ( "crypto/sha256" "fmt" "github.com/fasthttp/session/v2" "github.com/authelia/authelia/v4/internal/utils" ) // EncryptingSerializer a serializer encrypting the data with AES-GCM with 256-bit keys. type EncryptingSerializer struct { key [32]byte } // NewEncryptingSerializer return new encrypt instance. func NewEncryptingSerializer(secret string) *EncryptingSerializer { key := sha256.Sum256([]byte(secret)) return &EncryptingSerializer{key} } // Encode encode and encrypt session. func (e *EncryptingSerializer) Encode(src session.Dict) ([]byte, error) { if len(src.D) == 0 { return nil, nil } dst, err := src.MarshalMsg(nil) if err != nil { return nil, fmt.Errorf("unable to marshal session: %v", err) } encryptedDst, err := utils.Encrypt(dst, &e.key) if err != nil { return nil, fmt.Errorf("unable to encrypt session: %v", err) } return encryptedDst, nil } // Decode decrypt and decode session. func (e *EncryptingSerializer) Decode(dst *session.Dict, src []byte) error { if len(src) == 0 { return nil } dst.Reset() decryptedSrc, err := utils.Decrypt(src, &e.key) if err != nil { return fmt.Errorf("unable to decrypt session: %s", err) } _, err = dst.UnmarshalMsg(decryptedSrc) return err }
clems4ever/two-factor-auth-server
internal/session/encrypting_serializer.go
GO
mit
1,265
package parser import ( "io" "time" "github.com/lestrrat/go-lex" "github.com/lestrrat/go-xslate/internal/frame" "github.com/lestrrat/go-xslate/node" ) const ( ItemError lex.ItemType = lex.ItemDefaultMax + 1 + iota ItemEOF ItemRawString ItemComment ItemNumber ItemComplex ItemChar ItemSpace ItemTagStart ItemTagEnd ItemSymbol ItemIdentifier ItemDoubleQuotedString ItemSingleQuotedString ItemBool ItemField ItemComma ItemOpenParen // '(' ItemCloseParen // ')' ItemOpenSquareBracket // '[' ItemCloseSquareBracket // ']' ItemPeriod // '.' ItemKeyword // Delimiter ItemCall // CALL ItemGet // GET ItemSet // SET ItemMacro // MACRO ItemBlock // BLOCK ItemForeach // FOREACH ItemWhile // WHILE ItemIn // IN ItemInclude // INCLUDE ItemWith // WITH ItemIf // IF ItemElse // ELSE ItemElseIf // ELSIF ItemUnless // UNLESS ItemSwitch // SWITCH ItemCase // CASE ItemWrapper // WRAPPER ItemDefault // DEFAULT ItemEnd // END ItemOperator // Delimiter ItemRange // .. ItemEquals // == ItemNotEquals // != ItemGT // > ItemLT // < ItemCmp // <=> ItemLE // <= ItemGE // >= ItemShiftLeft // << ItemShiftRight // >> ItemAssignAdd // += ItemAssignSub // -= ItemAssignMul // *= ItemAssignDiv // /= ItemAssignMod // %= ItemAnd // && ItemOr // || ItemFatComma // => ItemIncr // ++ ItemDecr // -- ItemPlus ItemMinus ItemAsterisk ItemSlash ItemVerticalSlash ItemMod ItemAssign // = DefaultItemTypeMax ) // AST is represents the syntax tree for an Xslate template type AST struct { Name string // name of the template ParseName string // name of the top-level template during parsing Root *node.ListNode // root of the tree Timestamp time.Time // last-modified date of this template text string } type Builder struct { } // Frame is the frame struct used during parsing, which has a bit of // extension over the common Frame struct. type Frame struct { *frame.Frame Node node.Appender // This contains names of local variables, mapped to their // respective location in the framestack LvarNames map[string]int } type Lexer struct { lex.Lexer tagStart string tagEnd string symbols *LexSymbolSet } // LexSymbol holds the pre-defined symbols to be lexed type LexSymbol struct { Name string Type lex.ItemType Priority float32 } // LexSymbolList a list of LexSymbols. Normally you do not need to use it. // This is mainly only useful for sorting LexSymbols type LexSymbolList []LexSymbol // LexSymbolSorter sorts a list of LexSymbols by priority type LexSymbolSorter struct { list LexSymbolList } // LexSymbolSet is the container for symbols. type LexSymbolSet struct { Map map[string]LexSymbol SortedList LexSymbolList } // Parser defines the interface for Xslate parsers type Parser interface { Parse(string, []byte) (*AST, error) ParseString(string, string) (*AST, error) ParseReader(string, io.Reader) (*AST, error) }
lestrrat/go-xslate
parser/interface.go
GO
mit
3,503
using System; using System.Collections.Generic; using System.Linq; using System.Text; //25. Write a program that extracts from given HTML file its title (if available), // and its body text without the HTML tags. Example: namespace _25_ExtractHTML { class ExtractHTML { static void Main() { Console.Title = "Extract HTML"; Console.Write("Enter HTML text: "); string html = Console.ReadLine(); string title = GetTitle(html); string bodyText = GetBodyText(html); Console.WriteLine("\nTitle -> {0}\n", title); Console.WriteLine("Body text -> {0}\n", bodyText); } private static string GetBodyText(string html) { StringBuilder bodyText = new StringBuilder(); string openBodyTag = "<body>"; int startBodyIndex = html.IndexOf(openBodyTag) + openBodyTag.Length; bool isText = false; for (int i = startBodyIndex; i < html.Length; i++) { if (html[i] == '>') { isText = true; i++; } if (i < html.Length && isText && html[i] != '<') { bodyText.Append(html[i]); } else { isText = false; } } return bodyText.ToString(); } private static string GetTitle(string html) { string result = ""; string openTitleTag = "<title>"; string closeTitleTag = "</title>"; int startTitleIndex = html.IndexOf(openTitleTag) + openTitleTag.Length; if (startTitleIndex < 0) { return result; } int titleLength = html.IndexOf(closeTitleTag) - startTitleIndex; result = html.Substring(startTitleIndex, titleLength); return result; } } }
razsilev/TelerikAcademy_Homework
CSharp programing part 2/8.Strings-and-Text-Processing/25_ExtractHTML/ExtractHTML.cs
C#
mit
2,048
<?php /** * a validation class for checking form submissions * @package Maverick * @author Ashley Sheridan <ash@ashleysheridan.co.uk> */ class validator { public static $_instance; private $rules = array(); private $errors = array(); /** * returns a reference to ths singleton instance of this class - there can be only one! * @return validator */ public static function getInstance() { if(!(self::$_instance instanceof self)) self::$_instance = new self; return self::$_instance; } /** * applies the passed rules to the instance of this class and returns a reference to itself for chaining * @param array $rules an array of rules to apply to the submitted data * @return validator */ public static function make($rules) { $v = self::getInstance(); $app = \maverick\maverick::getInstance(); $v->reset(); if(!is_array($rules)) error::show('Validator ruleset is not an array'); $v->set_rules($rules); $app->validator = $v; return $v; } /** * gets all the errors with submitted data, or all errors for a specific field if given, * with individual errors wrapped with a specified set of tags * @param string|null $field an optional field name * @param array $wrapper an array containing a pair of strings to wrap around an individual error * @return array */ public static function get_all_errors($field=null, $wrapper=array()) { $v = self::getInstance(); if($field && isset($v->errors[$field])) { $errors = $v->errors[$field]; if(count($wrapper)==2) { foreach($errors as &$error) $error = $wrapper[0] . $error . $wrapper[1]; } return $errors; } if(!$field) { if(count($wrapper)==2) { foreach($v->errors as $key => &$error) $v->errors[$key] = $v->get_all_errors($key, $wrapper); } return $v->errors; } } /** * return only the first error for the specified field * @param string $field the name of a field * @param array $wrapper an array containing a pair of strings to wrap around an individual error * @return string */ public static function get_first_error($field, $wrapper=array()) { $v = self::getInstance(); if(isset($v->errors[$field])) return (count($wrapper)==2)?$wrapper[0] . reset($v->errors[$field]) . $wrapper[1]:reset($v->errors[$field]); else return ''; } /** * get the number of fields with errors * note that this does not return the number of total errors where a field may have more than one error * @return int */ public static function get_error_count() { $v = self::getInstance(); return count($v->errors); } /** * run the rules attached to this instance and apply them to the submitted data * populating the internal errors array with any errors found * @return bool */ public static function run() { $v = self::getInstance(); $app = \maverick\maverick::getInstance(); // run through the rules and apply them to any data that exists in the $_REQUEST array foreach($v->rules as $field => $rules) { if(!is_array($rules)) $rules = (array)$rules; // cast the single string rules to an array to make them the same to work with as groups of rules foreach($rules as $rule) { $params = explode(':', $rule); $rule_method = "rule_{$params[0]}"; $rule = $params[0]; if(method_exists($v, $rule_method)) { $params = array_slice($params, 1); if(!$v->$rule_method($field, $params)) // if the rule fails, generate the error message from the specific template in the config, and push it into the array for that field { // look up an error message for this and push it into the errors array $error_string = vsprintf($app->get_config("validator.$rule"), array_merge((array)$field, $params) ); if(!isset($v->errors[$field])) $v->errors[$field] = array(); $v->errors[$field][] = $error_string; } } else error::show("the validation rule {$params[0]} does not exist"); }//end foreach }//end foreach return !count($v->errors); } /** * apply the required rule to a field * @param string $field the name of the field to which this rule applies * @return bool */ private function rule_required($field) { $ok = false; // file upload rule if(isset($_FILES[$field]) && $_FILES[$field]['error'] == 0 ) $ok = true; // regular element rule if(isset($_REQUEST[$field]) ) { if(is_array($_REQUEST[$field])) { $ok = true; foreach($_REQUEST[$field] as $field) $ok = $ok && !empty($field); } else $ok = strlen($_REQUEST[$field]); } return $ok; } /** * validates a field as required only if another field is set and not empty * @param string $field the field to make optionally required * @param array $value the field to check a value for * @return boolean */ private function rule_required_if($field, $value) { if(!empty($_REQUEST[$value[0]] ) ) return empty($_REQUEST[$field]); else return true; } /** * validates a field as required only if another field is set to something that validates as true by rule_accepted() * @param string $field the field to make optionally required * @param array $value the value of the other field to check for conforming to rule_accepted() * @return boolean */ private function rule_required_if_yes($field, $value) { if($this->rule_accepted($value[0])) return !empty($_REQUEST[$field]); else return true; } /** * validates a field as required only if another field is set to the specified value * @param string $field the field to make optionally required * @param array $value an array containing the second fields' value an the value it should match in order for this rule to apply * @return boolean */ private function rule_required_if_value($field, $value) { if(isset($_REQUEST[$value[0]]) && $_REQUEST[$value[0]] == $value[1] ) return !empty($_REQUEST[$field]); else return true; } /** * apply the accepted rule to a field * @param string $field the name of the field to which this rule applies * @return bool */ private function rule_accepted($field) { if(isset($_REQUEST[$field]) && strlen($_REQUEST[$field]) ) return in_array($_REQUEST[$field], array('1', 'yes', 'y', 'checked') ); else return true; } /** * apply the alpha rule to a field * @param string $field the name of the field to which this rule applies * @return bool */ private function rule_alpha($field) { if(isset($_REQUEST[$field]) && strlen($_REQUEST[$field]) ) return preg_match("/^[\p{L} ]+$/", $_REQUEST[$field]); else return true; } /** * apply the alpha_apos rule to a field * @param string $field the name of the field to which this rule applies * @return bool */ private function rule_alpha_apos($field) { if(isset($_REQUEST[$field]) && strlen($_REQUEST[$field]) ) return preg_match("/^[\p{L}' ]+$/", $_REQUEST[$field]); else return true; } /** * apply the alpha_numeric rule to a field * @param string $field the name of the field to which this rule applies * @return bool */ private function rule_alpha_numeric($field) { if(isset($_REQUEST[$field]) && strlen($_REQUEST[$field]) ) return preg_match("/^[\p{L}\d \.\-\+]+$/", $_REQUEST[$field]); else return true; } /** * apply the alpha_dash rule to a field * @param string $field the name of the field to which this rule applies * @return bool */ private function rule_alpha_dash($field) { $regex = "/^[\p{L}\d \-_]+$/"; if(isset($_REQUEST[$field]) ) { if(is_array($_REQUEST[$field])) { $ok = true; foreach($_REQUEST[$field] as $field) { if(!empty($field)) $ok = $ok && preg_match($regex, $field); } return $ok; } else return preg_match($regex, $_REQUEST[$field]); } else return true; } /** * apply the numeric rule to a field * @param string $field the name of the field to which this rule applies * @return bool */ private function rule_numeric($field) { if(isset($_REQUEST[$field]) ) { if(is_array($_REQUEST[$field])) { $ok = true; foreach($_REQUEST[$field] as $field) { if(!empty($field)) $ok = $ok && is_numeric($field); } return $ok; } else return is_numeric($_REQUEST[$field]); } else return true; } /** * applies the mimes rule to a field, which determines that the passed mime-type matches the rules * if the file exists on the local file system (which it should always under normal circumstances) * then the \helpers\file class is used to determine the real type of the file, and not the value * that is passed by the browser, as that can't really be trusted * @param string $field the name of the field to which this rule applies * @param array|string $value the mime type(s) that the file must be within bounds of * @return boolean */ private function rule_mimes($field, $value) { if(!is_array($value)) $value = (array)$value; // check to see if the file was even uploaded if(empty($_FILES[$field]) || (!empty($_FILES[$field]) && $_FILES[$field]['error'] != 0 ) ) return false; $file_mime = $_FILES[$field]['type']; // this will be used throughout to make it easier to reference if(file_exists($_FILES[$field]['tmp_name'])); { $file = new \helpers\file($_FILES[$field]['tmp_name']); $file_mime = $file->info()->mime; } foreach($value as $mime) { // check for a mime-type string, or something similar to one // and check for wildcards and replace with regex wildcard if(strpos($mime, '/')) $mime = str_replace('*', '.*', $mime); if(strpos($mime, '/') === false) $mime = ".*/$mime"; if(preg_match("~$mime~", $file_mime) ) return true; } return false; } /** * apply the min rule to a field * @param string $field the name of the field to which this rule applies * @param int $value the value to use for this rule * @return bool */ private function rule_min($field, $value) { if(isset($_FILES[$field]) ) return ($_FILES[$field]['size'] >= intval($value[0]) ); else { if(isset($_REQUEST[$field]) && strlen($_REQUEST[$field]) ) return $_REQUEST[$field] >= (float)$value[0]; else return true; } } /** * apply the max rule to a field * @param string $field the name of the field to which this rule applies * @param int $value the value to use for this rule * @return bool */ private function rule_max($field, $value) { if(isset($_FILES[$field]) ) return ($_FILES[$field]['size'] <= intval($value[0]) ); else { if(isset($_REQUEST[$field]) && strlen($_REQUEST[$field]) ) return $_REQUEST[$field] <= (float)$value[0]; else return true; } } /** * apply the email rule to a field * @param string $field the name of the field to which this rule applies * @return bool */ private function rule_email($field) { if(isset($_REQUEST[$field]) && strlen($_REQUEST[$field]) ) return filter_var($_REQUEST[$field], FILTER_VALIDATE_EMAIL); else return true; } /** * apply the regex rule to a field * @param string $field the name of the field to which this rule applies * @param string $regex the regular expression to apply to the field * @return bool */ private function rule_regex($field, $regex) { if(isset($_REQUEST[$field]) && strlen($_REQUEST[$field]) ) return preg_match($regex[0], $_REQUEST[$field]); else return true; } /** * apply the url rule to a field * @param string $field the name of the field to which this rule applies * @return bool */ private function rule_url($field) { if(isset($_REQUEST[$field]) && strlen($_REQUEST[$field]) ) return filter_var($_REQUEST[$field], FILTER_VALIDATE_URL); else return true; } /** * apply the phone rule to a field * @param string $field the name of the field to which this rule applies * @return bool */ private function rule_phone($field) { if(isset($_REQUEST[$field]) && strlen($_REQUEST[$field]) ) return preg_match("/^[\d\+\- ]{8,}$/", $_REQUEST[$field]); else return true; } /** * apply the ip rule to a field * @param string $field the name of the field to which this rule applies * @return bool */ private function rule_ip($field) { if(isset($_REQUEST[$field]) && strlen($_REQUEST[$field]) ) return filter_var($_REQUEST[$field], FILTER_VALIDATE_IP); else return true; } /** * apply the before rule to a field * @param string $field the name of the field to which this rule applies * @param string $date the date to use for this field * @return bool */ private function rule_before($field, $date) { if(isset($_REQUEST[$field]) && strlen($_REQUEST[$field]) ) return strtotime($_REQUEST[$field]) < strtotime($date[0]); else return true; } /** * apply the after rule to a field * @param string $field the name of the field to which this rule applies * @param string $date the date to use for this field * @return bool */ private function rule_after($field, $date) { if(isset($_REQUEST[$field]) && strlen($_REQUEST[$field]) ) return strtotime($_REQUEST[$field]) > strtotime($date[0]); else return true; } /** * apply the between rule to a field * @param string $field the name of the field to which this rule applies * @param array $numbers an array of two numbers to use as the min and max values for this rule * @return bool */ private function rule_between($field, $numbers) { $min = (float)$numbers[0]; $max = (float)$numbers[1]; if(isset($_FILES[$field]) ) return ($_FILES[$field]['size'] >= $min) && ($_FILES[$field]['size'] <= $max); else { if(isset($_REQUEST[$field]) && strlen($_REQUEST[$field]) ) { switch(true) { case is_numeric($_REQUEST[$field]): $val = (float)$_REQUEST[$field]; break; default: $val = strlen($_REQUEST[$field]); break; } return ($val >= $min) && ($val <= $max); } else return true; } } /** * apply the confirmed rule to a field * @param string $field the name of the field to which this rule applies * @param array $field2 an array (because of the way the arguments are passed) of one element specifying the name of the field to compare this field to * @return bool */ private function rule_confirmed($field, $field2) { if(isset($_REQUEST[$field]) && strlen($_REQUEST[$field]) ) return (isset($_REQUEST[$field2[0]]) && $_REQUEST[$field] == $_REQUEST[$field2[0]] ); else return true; } /** * apply the in rule to a field * @param string $field the name of the field to which this rule applies * @param array $array an array of values to use for this rule * @return bool */ private function rule_in($field, $array) { if(isset($_REQUEST[$field]) && strlen($_REQUEST[$field]) ) return in_array($_REQUEST[$field], $array); else return true; } /** * apply the notin rule to a field * @param string $field the name of the field to which this rule applies * @param array $array an array of values to use for this rule * @return bool */ private function rule_notin($field, $array) { if(isset($_REQUEST[$field]) && strlen($_REQUEST[$field]) ) return !in_array($_REQUEST[$field], $array); else return true; } /** * apply the size rule to a field * @param string $field the name of the field to which this rule applies * @param string $size a string representation of the int (due to the way it's parsed) that either a string must match exactly or a file size (in bytes) that a file must be equal to * @return bool */ private function rule_size($field, $size) { if(isset($_FILES[$field]) ) return ($_FILES[$field]['size'] == intval($size[0]) ); else return (isset($_REQUEST[$field]) && strlen($_REQUEST[$field]) == intval($size[0]) ); } /** * set the rules to this validator instance * @param array $rules the rules to use * @return bool */ private function set_rules($rules) { $v = self::getInstance(); $v->rules = $rules; } /** * reset this singleton back to base values * @return bool */ private function reset() { $v = self::getInstance(); foreach(array('rules') as $var) $v->$var = array(); } }
AshleyJSheridan/maverick
maverick/vendor/maverick/validator.php
PHP
mit
16,426
import React, {Component, PropTypes} from 'react'; import {View, ListView, Image, CameraRoll, TouchableHighlight, StyleSheet} from 'react-native'; import MessageDao from '../../dao/MessageDao'; import LoadingSpinner from '../common/LoadingSpinner'; import Icon from 'react-native-vector-icons/MaterialIcons'; import MediaRenderer from './MediaRenderer'; import {InteractionManager} from 'react-native'; import { Dimensions } from 'react-native'; class MediaGallery extends Component { constructor(props, context) { super(props, context); this.state = {mediasForThread: [], isLoading: true}; } componentDidMount(){ let threadId = this.props.threadId; InteractionManager.runAfterInteractions(() => { requestAnimationFrame(() => { this.openGalleryForThread(threadId); }); }); } reloadMedia(){ let threadId = this.props.threadId; this.openGalleryForThread(threadId); } openGalleryForThread(threadId){ let mediaResult = MessageDao.getMediasForThread(threadId); this.setState({ mediasForThread: mediaResult.mediasForThread, isLoading: false }); } render() { const {router} = this.props; let imagesDS = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2}); //let lotOfImages = []; //const images = this.state.mediasForThread; //lotOfImages = lotOfImages.concat(images, images, images); //imagesDS = imagesDS.cloneWithRows(lotOfImages); imagesDS = imagesDS.cloneWithRows(this.state.mediasForThread); if(this.state.isLoading){ return( <View style={[styles.loadingContainer]}> <LoadingSpinner size="large"/> </View> ); } else{ return ( <View style={[styles.container]}> <ListView contentContainerStyle={styles.imageGrid} enableEmptySections={true} dataSource={imagesDS} renderRow={(media) => this.renderMedia(media)} initialListSize={15} scrollRenderAheadDistance={500} pagingEnabled={true} pageSize={1} removeClippedSubviews={true} /> </View> ); } } renderMedia(media){ return( <TouchableHighlight onPress={() => this.openMediaViewer(media)}> <View> <MediaRenderer media={media} router={this.props.router} threadId={this.props.threadId} mediaViewerEnabled={true} mediaStyle={styles.image}/> </View> </TouchableHighlight> ); } openMediaViewer(media){ this.props.router.toMediaViewer({selectedMedia: media, threadId: this.props.threadId}); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: 'black', borderRadius: 4, borderWidth: 0.5, borderColor: '#d6d7da', paddingBottom: 10 }, loadingContainer:{ flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: 'black', height: Dimensions.get('window').height, width: Dimensions.get('window').width, }, image: { width: 100, height: 100, margin: 2, justifyContent: 'center', }, imageGrid: { flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'space-around', marginBottom: 50 }, }); MediaRenderer.propTypes = { router: PropTypes.object.isRequired, threadId: PropTypes.number.isRequired, }; export default MediaGallery;
ramsundark5/stitchchat
app/components/media/MediaGallery.js
JavaScript
mit
4,056
<?php /** * Dibs A/S * Dibs Payment Extension * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@magentocommerce.com so we can send you a copy immediately. * * @category Payments & Gateways Extensions * @package Dibspw_Dibspw * @author Dibs A/S * @copyright Copyright (c) 2010 Dibs A/S. (http://www.dibs.dk/) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ define("DIBS_PAYMENT_GATEWAT_CODE", "dibspw"); $nzshpcrt_gateways[$num] = array('name' => 'DIBS Payment Window', 'internalname' => DIBS_PAYMENT_GATEWAT_CODE, 'function' => 'dibspayment_paywin_gateway', 'form' => 'dibspayment_paywin_form', 'submit_function' => 'dibspayment_paywin_submit', 'payment_type' => DIBS_PAYMENT_GATEWAT_CODE, //'display_name' => 'DIBS Payment Window | Secured Payment Services', 'image' => "http://m.c.lnkd.licdn.com/media/p/2/005/023/302/3889cf5.png", 'requirements' => array( 'php_version' => 5.2, 'extra_modules' => array() )); define("DIBS_ENTRYPOINT_D2_URL", "https://sat1.dibspayment.com/dibspaymentwindow/entrypoint"); define("DIBS_ENTRYPOINT_DX_URL", "https://payment.dibspayment.com/dpw/entrypoint"); define("DIBS_SYSMOD", "wp3e_4_1_8"); /** * Generate form for checkout. * * * @global object $wpdb * @global object $wpsc_cart * @param type $separator * @param string $sessionid */ function dibspayment_paywin_gateway($separator, $sessionid) { global $wpdb, $wpsc_cart; $wpsc_cart->sessionid = $sessionid; if(get_option('dibspw_platform') == "D2") { $entrypoint_url = DIBS_ENTRYPOINT_D2_URL; } if(get_option('dibspw_platform') == "DX") { $entrypoint_url = DIBS_ENTRYPOINT_DX_URL; } $request_data = dibspayment_paywin_order_params($wpsc_cart); if(WPSC_GATEWAY_DEBUG == true ) { exit("<pre>".print_r($request_data,true)."</pre>"); } $out = '<form id="dibspw_form" name="dibspw_form" method="post" action="' . $entrypoint_url . '">' . "\n"; foreach($request_data as $key => $value) { $out .= '<input type="hidden" name="' . $key . '" value="' . $value . '" />' . "\n"; } $out .= '<input type="submit" name="submit_to_dibs" value="Continue to DIBS..." />' . "\n"; $out .= '</form>'. "\n"; echo $out; echo "<script language=\"javascript\" type=\"text/javascript\">document.getElementById('dibspw_form').submit();</script>"; exit(); } /** * Handle Response from DIBS server * * * */ function dibspayment_paywin_process() { global $wpdb; if(isset($_GET['dibspw_result']) && isset($_POST['s_pid'])) { array_walk($_POST, create_function('&$val', '$val = stripslashes($val);')); $hamc_key = get_option('dibspw_hmac'); $order_id = $_POST['orderid']; switch($_GET['dibspw_result']) { case 'callback': if( $hamc_key && !isset( $_POST['MAC'])) { die("HMAC error!"); } if($hamc_key && isset( $_POST['MAC']) && $_POST['MAC']) { if( $_POST['MAC'] != dibspayment_paywin_calc_mac($_POST, $hamc_key, $bUrlDecode = FALSE)) { die("MAC is incorrect, fraud attempt!"); } } $dibsInvoiceFields = array("acquirerLastName", "acquirerFirstName", "acquirerDeliveryAddress", "acquirerDeliveryPostalCode", "acquirerDeliveryPostalPlace" ); $dibsInvoiceFieldsString = ""; foreach($_POST as $key=>$value) { if(in_array($key, $dibsInvoiceFields)) { $dibsInvoiceFieldsString .= "{$key}={$value}\n"; } } // Email is not send automatically on a success transactio page // from version '3.8.9 so we send email on callback from this version if( version_compare(get_option( 'wpsc_version' ), '3.8.9', '>=' ) ) { if( $_POST['status'] == "ACCEPTED" ) { $purchaselog = new WPSC_Purchase_Log($order_id); $purchaselog->set('processed', get_option('dibspw_status')); $purchaselog->set('notes', $dibsInvoiceFieldsString); $purchaselog->set('transactid', $_POST['transaction']); $purchaselog ->save(); $wpscmerch = new wpsc_merchant($order_id, false); $wpscmerch->set_purchase_processed_by_purchid(get_option('dibspw_status')); } }else { if( $_POST['status'] == "ACCEPTED" ) { $purchase_log = $wpdb->get_results("SELECT * FROM `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE `sessionid`= ".$_POST['s_pid']." LIMIT 1", ARRAY_A); $wpdb->query("UPDATE `" . WPSC_TABLE_PURCHASE_LOGS . "` SET `processed` = '". get_option('dibspw_status') ."', `notes`='".$dibsInvoiceFieldsString."' WHERE `id` = '" . $purchase_log[0]['id'] . "' LIMIT 1;"); // If it is the second callback with status ACCEPTED // we want to send an email to customer. if( $purchase_log[0]['authcode'] == "PENDING" ) { transaction_results( $_POST['s_pid'],false); } } else { // we save not successed statuses it can be PENDING status.. $wpdb->query("UPDATE `" . WPSC_TABLE_PURCHASE_LOGS . "` SET `processed` = '1' , `authcode` = '".$_POST['status']."' WHERE `id` = '" . $purchase_log[0]['id'] . "' LIMIT 1;"); } } break; case 'success': if(!isset($_GET['page_id']) || get_permalink($_GET['page_id']) != get_option('transact_url')) { $location = add_query_arg('sessionid', $_POST['s_pid'], get_option('transact_url')); if( $_POST['status'] == "ACCEPTED" ) { if( $hamc_key && !isset( $_POST['MAC'])) { die("HMAC error!"); } if($hamc_key && isset( $_POST['MAC']) && $_POST['MAC']) { if( $_POST['MAC'] != dibspayment_paywin_calc_mac($_POST, $hamc_key, $bUrlDecode = FALSE)) { die("HMAC is incorrect, fraud attempt!"); } } } else { // Declined or PENDING $purchase_log = $wpdb->get_results("SELECT * FROM `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE `sessionid`= ".$_POST['s_pid']." LIMIT 1", ARRAY_A); $wpdb->query("UPDATE `" . WPSC_TABLE_PURCHASE_LOGS . "` SET `processed` = '1' , `authcode` = '".$_POST['status']."' WHERE `id` = '" . $purchase_log[0]['id'] . "' LIMIT 1;"); } wp_redirect($location); exit(); } break; case 'cancel': if (isset($_POST['orderid'])) { $purchase_log = $wpdb->get_results("SELECT * FROM `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE `sessionid`= ".$_POST['s_pid']." LIMIT 1", ARRAY_A); $wpdb->query("UPDATE `" . WPSC_TABLE_PURCHASE_LOGS . "` SET `processed` = '".get_option('dibspw_statusc')."' WHERE `id` = '" . $purchase_log[0]['id'] . "' LIMIT 1;"); wp_redirect(get_option( 'shopping_cart_url' )); exit(); } break; } } } /** * Saving of module settings. * * @return bool */ function dibspayment_paywin_submit() { foreach($_POST as $key => $value) { if(false !== strpos($key,"dibspw_") && $key != 'dibspw_form') { update_option($key, isset($_POST[$key]) ? $_POST[$key] : ""); } } if(isset($_POST['dibspw_capturenow'])) { update_option('dibspw_capturenow', $_POST['dibspw_capturenow']); }else { update_option('dibspw_capturenow', ""); } if(isset($_POST['dibspw_fee'])) { update_option('dibspw_fee', $_POST['dibspw_fee']); }else { update_option('dibspw_fee', ""); } if(isset($_POST['dibspw_testmode'])) { update_option('dibspw_testmode', $_POST['dibspw_testmode']); }else { update_option('dibspw_testmode', ""); } if (!isset($_POST['dibspw_form'])) $_POST['dibspw_form'] = array(); if(isset($_POST['dibspw_cardslogo'])) { update_option('dibspw_cardslogo', str_replace('\\', '', $_POST['dibspw_cardslogo'])); } if(isset($_POST['dibspw_invoicelogo'])) { update_option('dibspw_invoicelogo', str_replace('\\', '', $_POST['dibspw_invoicelogo'])); } if(isset($_POST['dibspw_netbanklogo'])) { update_option('dibspw_netbanklogo', str_replace('\\', '', $_POST['dibspw_netbanklogo'])); } foreach((array)$_POST['dibspw_form'] as $key => $value) { update_option(('dibspw_form_' . $key), $value); } return true; } function dibspayment_paywin_order_params($cart) { global $wpdb; $order_data = array(); $purchase_log = $wpdb->get_results("SELECT * FROM `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE `sessionid`= ".$cart->sessionid." LIMIT 1", ARRAY_A); $currency_code = $wpdb->get_results("SELECT `code` FROM `" . WPSC_TABLE_CURRENCY_LIST . "` WHERE `id`='" . get_option('currency_type') . "' LIMIT 1", ARRAY_A); // Set status on new order $wpdb->query("UPDATE `" . WPSC_TABLE_PURCHASE_LOGS . "` SET `processed` = '". get_option('dibspw_statusp') ."' WHERE `sessionid` = '" . $cart->sessionid . "' LIMIT 1;"); // collect data for request $order_data['orderid'] = $purchase_log[0]['id']; $order_data['merchant'] = get_option('dibspw_mid'); $order_data['amount'] = dibspayment_paywin_round($cart->total_price); $order_data['currency'] = $currency_code[0]['code']; $order_data['language'] = get_option('dibspw_lang'); $order_data['oitypes'] = 'QUANTITY;UNITCODE;DESCRIPTION;AMOUNT;ITEMID;VATAMOUNT'; $order_data['oinames'] = 'Qty;UnitCode;Description;Amount;ItemId;VatAmount'; $order_data['oinames'] = 'Qty;UnitCode;Description;Amount;ItemId;VatAmount'; $wpec_taxes_c = new wpec_taxes_controller; //$tax_total = $wpec_taxes_c->wpec_taxes_calculate_total(); //get the rate for the country and region if set $tax_total = $wpec_taxes_c->wpec_taxes->wpec_taxes_get_rate($wpec_taxes_c->wpec_taxes_retrieve_selected_country(), $wpec_taxes_c->wpec_taxes_retrieve_region()); // cart items $i=1; foreach($cart->cart_items as $oitem) { $tmp_price = dibspayment_paywin_round($oitem->unit_price); if(!empty($tmp_price)) { $unit_price = $oitem->unit_price; $tax['tax'] = 0; if($wpec_taxes_c->wpec_taxes->wpec_taxes_get_enabled() && $tax_total['rate']) { if($wpec_taxes_c->wpec_taxes_isincluded()) { $tax = $wpec_taxes_c->wpec_taxes_calculate_included_tax($oitem); $tax['tax'] = $tax['tax']/$oitem->quantity; $unit_price = $oitem->unit_price - $tax['tax']; } else { $tax['tax'] = $unit_price * ($tax_total['rate'] / 100); } } $tmp_name = !empty($oitem->product_name) ? $oitem->product_name : $oitem->sku; if(empty($tmp_name)) $tmp_name = $oitem->product_id; $order_data['oiRow' . $i++] = dibspayment_paywin_oirow_str($oitem->quantity, dibspayment_paywin_utf8Fix(str_replace(";","\;",$tmp_name)), dibspayment_paywin_round($unit_price), dibspayment_paywin_utf8Fix(str_replace(";","\;",$oitem->product_id)), dibspayment_paywin_round($tax['tax'])); } unset($tmp_price, $tmp_name); } // Shipping calculation if($cart->calculate_total_shipping()) { $shipping_tax = 0; $fRate = $cart->calculate_total_shipping(); if( $tax_total['shipping'] && $wpec_taxes_c->wpec_taxes->wpec_taxes_get_enabled()) { if($wpec_taxes_c->wpec_taxes_isincluded()) { $shipping_tax = $wpec_taxes_c->wpec_taxes_calculate_tax( $cart->calculate_total_shipping(), $tax_total['rate'], false); $fRate = $fRate - $shipping_tax; } else { $shipping_tax = $wpec_taxes_c->wpec_taxes_calculate_tax( $cart->calculate_total_shipping(), $tax_total['rate']); } } $order_data['oiRow' . $i++] = dibspayment_paywin_oirow_str(1, "Shipping" , dibspayment_paywin_round($fRate) , "shipping_0", dibspayment_paywin_round($shipping_tax)); } // Cupone if it is avaliable if($cart->coupons_amount > 0) { $order_data['oiRow'.$i++]=dibspayment_paywin_oirow_str(1, "Coupon", -dibspayment_paywin_round($cart->coupons_amount) , "coupon_0", 0); } // Address fields here.. $aAddr = $_POST['collected_data']; $order_data['shippingfirstname'] = $aAddr[get_option('dibspw_form_first_name_d')]; $order_data['shippinglastname'] = $aAddr[get_option('dibspw_form_last_name_d')]; $order_data['shippingpostalcode'] = $aAddr[get_option('dibspw_form_post_code_d')]; $order_data['shippingpostalplace']= $aAddr[get_option('dibspw_form_city_d')]; //$order_data['shippingaddress2'] = $aAddr[get_option('dibspw_form_address_d')]; $order_data['shippingaddress'] = $aAddr[get_option('dibspw_form_country_d')] . " " . $aAddr[get_option('dibspw_form_state_d')]; $order_data['billingfirstname'] = $aAddr[get_option('dibspw_form_first_name_b')]; $order_data['billinglastname'] = $aAddr[get_option('dibspw_form_last_name_b')]; $order_data['billingpostalcode'] = $aAddr[get_option('dibspw_form_post_code_b')]; $order_data['billingpostalplace'] = $aAddr[get_option('dibspw_form_city_b')]; $order_data['billingaddress'] = $aAddr[get_option('dibspw_form_address_b')]; //$order_data['billingaddress'] = $aAddr[get_option('dibspw_form_country_b')]. " " . // $aAddr[get_option('dibspw_form_state_b')]; $order_data['billingmobile'] = $aAddr[get_option('dibspw_form_phone_b')]; $order_data['billingemail'] = $aAddr[get_option('dibspw_form_email_b')]; $order_data['acceptreturnurl'] = get_option('siteurl') . "/?dibspw_result=success"; $order_data['cancelreturnurl'] = site_url() . "/?dibspw_result=cancel"; $order_data['callbackurl'] = site_url() . "/?dibspw_result=callback"; $order_data['s_callbackfix'] = get_option('siteurl') . "/?dibspw_result=callback"; $order_data['s_sysmod'] = DIBS_SYSMOD; if(get_option('dibspw_testmode')) { $order_data['test'] = 1; } if(get_option('dibspw_capturenow')) { $order_data['capturenow'] = 1; } if(get_option('dibspw_fee')) { $order_data['addfee'] = 1; } $order_data['s_pid'] = $cart->sessionid; if(get_option('dibspw_account')) { $order_data['account'] = get_option('dibspw_account'); } if(get_option('dibspw_paytype')) { $order_data['paytype'] = get_option('dibspw_paytype'); } if(get_option('dibspw_pid')) { $order_data['s_partnerid'] = get_option('dibspw_pid'); } if($hmac = get_option('dibspw_hmac')) { $order_data['MAC'] = dibspayment_paywin_calc_mac($order_data, $hmac, $bUrlDecode = FALSE); } return $order_data; } function dibspayment_paywin_round($fNum, $iPrec = 2) { return empty($fNum) ? (int)0 : (int)(string)(round($fNum, $iPrec) * pow(10, $iPrec)); } function checkbox_checked($value) { if($value == 'yes') { return 'checked'; } } function dibspayment_paywin_build_select($resource, $stored_value) { $out = ""; $checked = ""; foreach($resource as $key => $value) { echo $checked; if($key == $stored_value) $checked = "selected = \"selected\""; $out .= "<option value=\"$key\" $checked> $value </option>"; $checked = ""; } return $out; } function get_statuses($status) { global $wpsc_purchlog_statuses; $statuses = array(); foreach($wpsc_purchlog_statuses as $key=>$value) { $statuses[$value['order']] = $value['label']; } return dibspayment_paywin_build_select($statuses, $status); } /** * Calculates MAC for given array of data. * * @param array $adata * @param string $hmac * @param bool $url_decode * @return string */ function dibspayment_paywin_calc_mac($adata, $hmac, $url_decode = FALSE) { $mac = ""; if(!empty($hmac)) { $sdata = ""; if(isset($adata['MAC'])) unset($adata['MAC']); ksort($adata); foreach($adata as $key => $val) { $sdata .= "&" . $key . "=" . (($url_decode === TRUE) ? urldecode($val) : $val); } $mac = hash_hmac("sha256", ltrim($sdata, "&"), dibspayment_paywin_hextostr($hmac)); } return $mac; } /** * Convert hex HMAC to string. * * @param string $shex * @return string */ function dibspayment_paywin_hextostr($shex) { $sres = ""; foreach(explode("\n", trim(chunk_split($shex,2))) as $h) $sres .= chr(hexdec($h)); return $sres; } /** * Fixes UTF-8 special symbols if encoding of CMS is not UTF-8. * Main using is for wided latin alphabets. * * @param string $s_text * @return string */ function dibspayment_paywin_utf8Fix($s_text) { return (mb_detect_encoding($s_text) == "UTF-8" && mb_check_encoding($s_text, "UTF-8")) ? $s_text : utf8_encode($s_text); } function dibspayment_paywin_oirow_str( $qty = 1, $item_name, $item_price, $item_id, $item_tax = 0 ) { return "$qty;pcs;$item_name;$item_price;$item_id;$item_tax"; } /** * Generating module settings form. * * @return string */ function dibspayment_paywin_form() { $lang = array( 'da_DK' => 'Danish', 'en_GB' => 'English (GB)', 'nb_NO' => 'Norwegian', 'sv_SE' => 'Swedish', 'de_DE' => 'German', 'en_US' => 'English (US)', 'es_ES' => 'Spanish', 'fi_FI' => 'Finnish', 'fr_FR' => 'French', 'it_IT' => 'Italian', 'nl_NL' => 'Dutch', 'pl_PL' => 'Polish', 'pt_PT' => 'Portuguese', ); $platform = array('D2' =>'D2', 'DX' => 'DX'); $dibs_params = '<tr> <td>DIBS Integration ID:</td> <td><input type="text" name="dibspw_mid" value="'.get_option('dibspw_mid').'" /></td> </tr> <tr> <td>&nbsp;</td> <td> <span class="small description"> Your merchant ID in DIBS system. </span> </td> </tr> <tr> <td>DIBS platform:</td> <td><select name="dibspw_platform">'. dibspayment_paywin_build_select($platform, get_option('dibspw_platform')) . '</select></td> </tr> <tr> <td>&nbsp;</td> <td> <span class="small description"> Which platform to use ?. You can detect your platform here: <a style="color:#2E6E9E" href="http://tech.dibspayment.com/platformfinder" target="_blank">http://tech.dibspayment.com/platformfinder </a> </span> </td> </tr> <tr> <td>Partner ID:</td> <td><input type="text" name="dibspw_pid" value="'.get_option('dibspw_pid').'" /></td> </tr> <tr> <td>&nbsp;</td> <td> <span class="small description"> Partner ID. </span> </td> </tr><tr> <td>HMAC:</td> <td><input type="text" name="dibspw_hmac" value="'.get_option('dibspw_hmac').'" /></td> </tr> <tr> <td>&nbsp;</td> <td> <span class="small description"> Key for transactions security. </span> </td> </tr><tr> <td>Test mode:</td> <td><input type="checkbox" name="dibspw_testmode" value="yes"'.checkbox_checked(get_option('dibspw_testmode')).'/></td> </tr> <tr> <td>&nbsp;</td> <td> <span class="small description"> Run transactions in test mode. </span> </td> </tr><tr> <td>Add fee:</td> <td><input type="checkbox" name="dibspw_fee" value="yes" '.checkbox_checked(get_option('dibspw_fee')).'/></td> </tr> <tr> <td>&nbsp;</td> <td> <span class="small description"> Customer pays fee. </span> </td> </tr> <tr> <td>Capture now:</td> <td><input type="checkbox" name="dibspw_capturenow" value="yes"'.checkbox_checked(get_option('dibspw_capturenow')).'/></td> </tr> <tr> <td>&nbsp;</td> <td> <span class="small description"> Make attempt to capture the transaction upon a successful authorization. (DIBS PW only) </span> </td> </tr> <tr> <td>Cards logo:</td> <td> <textarea type="checkbox" style="width:60%" name="dibspw_cardslogo" rows="4" cols="40">'.get_option('dibspw_cardslogo').'</textarea> </td> </tr> <tr> <td>&nbsp;</td> <td> <span class="small description"> Please choose and confire logo on our site <a href="http://tech.dibspayment.com/logos#check-out-logos" target="_blank">http://tech.dibspayment.com/logos#check-out-logos</a> and paste html markup for Card logo here. </span> </td> </tr> <tr> <td>Netbank logo:</td> <td> <textarea type="checkbox" style="width:60%" name="dibspw_netbanklogo" rows="4" cols="20">'.get_option('dibspw_netbanklogo').'</textarea> </td> </tr> <tr> <td>&nbsp;</td> <td> <span class="small description"> Please choose and confire logo on our site <a href="http://tech.dibspayment.com/logos#check-out-logos" target="_blank">http://tech.dibspayment.com/logos#check-out-logos</a> and paste html markup for Netbank logo here. </span> </td> </tr> <tr> <td>Invoice logo:</td> <td> <textarea type="checkbox" style="width:60%" name="dibspw_invoicelogo" rows="4" cols="20">'.get_option('dibspw_invoicelogo').'</textarea> </td> </tr> <tr> <td>&nbsp;</td> <td> <span class="small description"> Please choose and confire logo on our site <a href="http://tech.dibspayment.com/logos#check-out-logos" target="_blank">http://tech.dibspayment.com/logos#check-out-logos</a> and paste html markup for Invoice logo here. </span> </td> </tr> <tr> <td>Paytype:</td> <td><input type="text" name="dibspw_paytype" value="'.get_option('dibspw_paytype').'" /></td> </tr> <tr> <td>&nbsp;</td> <td> <span class="small description"> Paytypes available to customer (e.g.: VISA,MC) </span> </td> </tr><tr> <td>Language:</td> <td><select style="width: 108px;" name="dibspw_lang">'. dibspayment_paywin_build_select($lang, get_option('dibspw_lang')) . '</select></td> </tr> <tr> <td>&nbsp;</td> <td> <span class="small description"> Language of payment window interface. </span> </td> </tr><tr> <td>Account:</td> <td><input type="text" name="dibspw_account" value="'.get_option('dibspw_account').'" /></td> </tr> <tr> <td>&nbsp;</td> <td> <span class="small description"> Account id used to visually separate transactions in merchant admin. </span> </td> </tr> <tr> <td>&nbsp;</td> <td> <span class="small description"> </span> </td> </tr><tr> <td>Success payment status:</td> <td><select name="dibspw_status">'.get_statuses(get_option('dibspw_status')).'</select></td> </tr> <tr> <td>&nbsp;</td> <td> <span class="small description"> Order status after success transaction. </span> </td> </tr><tr> <td>Pending payment status:</td> <td><select name="dibspw_statusp"> '.get_statuses(get_option('dibspw_statusp')).' </select></td> </tr> <tr> <td>&nbsp;</td> <td> <span class="small description"> Order status before payment. </span> </td> </tr><tr> <td>Cancel payment status:</td> <td><select name="dibspw_statusc"> '.get_statuses(get_option('dibspw_statusc')).' </select></td> </tr> <tr> <td>&nbsp;</td> <td> <span class="small description"> Order status on cancellation. </span> </td> </tr>'; $address_fields = '<tr class="update_gateway" > <td colspan="2"> <div class="submit"> <input type="submit" value="' . __('Update &raquo;', 'wpsc') . '" name="updateoption" /> </div> </td> </tr> <tr class="firstrowth"> <td style="border-bottom: medium none;" colspan="2"> <strong class="form_group">Billing Form Sent to Gateway</strong> </td> </tr> <tr> <td>First Name Field</td> <td> <select name="dibspw_form[first_name_b]">' . nzshpcrt_form_field_list(get_option('dibspw_form_first_name_b')) . '</select> </td> </tr> <tr> <td>Last Name Field</td> <td> <select name="dibspw_form[last_name_b]">' . nzshpcrt_form_field_list(get_option('dibspw_form_last_name_b')) . '</select> </td> </tr> <tr> <td>Address Field</td> <td> <select name="dibspw_form[address_b]">' . nzshpcrt_form_field_list(get_option('dibspw_form_address_b')) . '</select> </td> </tr> <tr> <td>City Field</td> <td> <select name="dibspw_form[city_b]">' . nzshpcrt_form_field_list(get_option('dibspw_form_city_b')) . '</select> </td> </tr> <tr> <td>State Field</td> <td> <select name="dibspw_form[state_b]">' . nzshpcrt_form_field_list(get_option('dibspw_form_state_b')) . '</select> </td> </tr> <tr> <td>Postal/Zip code Field</td> <td> <select name="dibspw_form[post_code_b]">' . nzshpcrt_form_field_list(get_option('dibspw_form_post_code_b')) . '</select> </td> </tr> <tr> <td>Country Field</td> <td> <select name="dibspw_form[country_b]">' . nzshpcrt_form_field_list(get_option('dibspw_form_country_b')) . '</select> </td> </tr> <tr class="firstrowth"> <td style="border-bottom: medium none;" colspan="2"> <strong class="form_group">Shipping Form Sent to Gateway</strong> </td> </tr> <tr> <td>First Name Field</td> <td> <select name="dibspw_form[first_name_d]">' . nzshpcrt_form_field_list(get_option('dibspw_form_first_name_d')) . '</select> </td> </tr> <tr> <td>Last Name Field</td> <td> <select name="dibspw_form[last_name_d]">' . nzshpcrt_form_field_list(get_option('dibspw_form_last_name_d')) . '</select> </td> </tr> <tr> <td>Address Field</td> <td> <select name="dibspw_form[address_d]">' . nzshpcrt_form_field_list(get_option('dibspw_form_address_d')) . '</select> </td> </tr> <tr> <td>City Field</td> <td> <select name="dibspw_form[city_d]">' . nzshpcrt_form_field_list(get_option('dibspw_form_city_d')) . '</select> </td> </tr> <tr> <td>State Field</td> <td> <select name="dibspw_form[state_d]">' . nzshpcrt_form_field_list(get_option('dibspw_form_state_d')) . '</select> </td> </tr> <tr> <td>Postal/Zip code Field</td> <td> <select name="dibspw_form[post_code_d]">' . nzshpcrt_form_field_list(get_option('dibspw_form_post_code_d')) . '</select> </td> </tr> <tr> <td>Country Field</td> <td> <select name="dibspw_form[country_d]">' . nzshpcrt_form_field_list(get_option('dibspw_form_country_d')) . '</select> </td> </tr> <tr class="firstrowth"> <td style="border-bottom: medium none;" colspan="2"> <strong class="form_group">Contacts Form Sent to Gateway</strong> </td> </tr> <tr> <td>Email</td> <td> <select name="dibspw_form[email_b]">' . nzshpcrt_form_field_list(get_option('dibspw_form_email_b')) . '</select> </td> </tr> <tr> <td>Phone</td> <td> <select name="dibspw_form[phone_b]">' . nzshpcrt_form_field_list(get_option('dibspw_form_phone_b')) . '</select> </td> </tr> <tr> <td colspan="2"> <span class="wpscsmall description"> For more help configuring DIBS Payment Window, please read our documentation <a href="http://tech.dibspayment.com/starter_guide" target="_blank">here</a>. </span> </td> </tr>'; return $dibs_params . $address_fields; } function dibspayment_paywin_checkout_form_dibspw($output) { $output = ''; $output .= get_option('dibspw_cardslogo') . get_option('dibspw_netbanklogo'). get_option('dibspw_invoicelogo') ; if( $output ) { $output = '<tr><td>' .$output .'</td></tr>'; } return $output; } function dibspayment_paywin_user_log_after_order_status( $purchase) { var_dump($purchase); if(DIBS_PAYMENT_GATEWAT_CODE == $purchase['gateway']) { $dibsTransDetails = '<strong>DIBS transaction details:</strong>' . '<table class="customer_details"> <tbody><tr>' . '<td colspan="2">Transaction details:</td></tr> ' . '<tr><td>Transactionid:</td><td>'.$purchase['transactid'].'</td></tr> ' . '<tr><td>Status:</td><td>ACCEPTED</td></tr> ' . '</table>'; echo $dibsTransDetails; } } function _dibspayment_customer_notification_raw_message($message, $notification ) { $purchase_log = $notification->get_purchase_log(); if( $purchase_log->get('gateway') == DIBS_PAYMENT_GATEWAT_CODE) { $transactid = $purchase_log->get('transactid'); $message = $message . "DIBS Transaction id = $transactid \n"; } return $message; } function dibspayment_paywin_purchlogitem_metabox_end($log_id) { $log = new WPSC_Purchase_Log( $log_id ); $log_data_arr = $log->get_data(); if( $log_data_arr['gateway'] == DIBS_PAYMENT_GATEWAT_CODE && $log_data_arr['transactid']) { echo 'DIBS transactionid =' . $log_data_arr['transactid']; } } add_action('init', 'dibspayment_paywin_process'); add_filter('wpsc_gateway_checkout_form_dibspw', 'dibspayment_paywin_checkout_form_dibspw'); add_action('wpsc_purchlogitem_metabox_end', 'dibspayment_paywin_purchlogitem_metabox_end'); add_action( 'wpsc_user_log_after_order_status' , 'dibspayment_paywin_user_log_after_order_status'); add_filter( 'wpsc_purchase_log_customer_notification_raw_message', '_dibspayment_customer_notification_raw_message', 10, 2 );
DIBS-Payment-Services/Ecommerce
src/WP_Ecommerce_4.1.8/dibspw.php
PHP
mit
36,309
<?php namespace Rice\DeckKeeperBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Rice\DeckKeeperBundle\Entity\CardSet; use Rice\DeckKeeperBundle\Form\CardSetType; class CardSetController extends Controller { /** * @Template() */ public function indexAction() { $sets = $this ->getDoctrine() ->getRepository('RiceDeckKeeperBundle:CardSet') ->findAll() ; return array( 'sets' => $sets, ); } public function newAction() { $cardSet = new CardSet(); $form = $this->createForm(new CardSetType(), $cardSet); $request = $this->getRequest(); if ('POST' === $request->getMethod()) { $form->bind($request); if ($form->isValid()) { $em = $this->getDoctrine()->getEntityManager(); $em->persist($cardSet); $em->flush(); return $this->redirect($this->generateUrl('frontend_deck_keeper_cardset_index')); } } return $this->render('RiceDeckKeeperBundle:CardSet:new.html.twig', array( 'form' => $form->createView() )); } }
cystbear/rice
src/Rice/DeckKeeperBundle/Controller/CardSetController.php
PHP
mit
1,297
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Text.RegularExpressions; using System.Web.Configuration; using System.Web.Mvc; using System.Web.Mvc.Html; using System.Web.Optimization; namespace aspnet_mvc_helpers { /// <summary> /// A collection of usefull Html Helpers /// </summary> public static class HtmlExtensions { private const string MicrosoftCDNRoot = "https://ajax.aspnetcdn.com/ajax/"; //private const string GoogleCDNRoot = "https://ajax.googleapis.com/ajax/libs/"; /// <summary> /// Tag for prevent caching /// </summary> public static ShortGuid CacheTag = new ShortGuid(Guid.NewGuid()); /// <summary> /// set the mail type on an input (HTML5) /// </summary> /// <typeparam name="TModel">Exposed model</typeparam> /// <typeparam name="TProperty">Property type of field</typeparam> /// <param name="html">Html context</param> /// <param name="expression">Model expression</param> /// <param name="htmlAttributes">Additional attributes</param> /// <returns></returns> public static MvcHtmlString EmailFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression, object htmlAttributes) { // unsupported by safari var emailfor = html.TextBoxFor(expression, htmlAttributes); return new MvcHtmlString(emailfor.ToHtmlString().Replace("type=\"text\"", "type=\"email\"")); } private const string ScriptTag = "<script src='{0}'></script>"; /// <summary> /// Wrapper used to load the right JS /// generated by a typescript file /// And add in bundle cache /// </summary> /// <param name="helper">The HTML context</param> /// <param name="url">Url of the TS file</param> /// <param name="debug">Set if we we are in debug mode(true)</param> /// <returns>The right JS file (.min if not debug)</returns> public static MvcHtmlString TypeScript(this HtmlHelper helper, string url, bool debug = false) { // ReSharper disable once NotResolvedInText if (debug && string.IsNullOrWhiteSpace(url)) throw new ArgumentNullException(@"TypeScript Helper"); var suffixPos = url.LastIndexOf('.'); if (debug && (suffixPos < 0 || url.Substring(suffixPos) != ".ts")) throw new ArgumentException("TypeScript Helper : bad name or bad suffix"); var realName = url.Substring(0, suffixPos); return helper.JavaScript(realName, true, debug); } /// <summary> /// Wrapper used to load the right JS /// generated by a typescript files /// And add in bundle cache /// </summary> /// <param name="helper">The HTML context</param> /// <param name="bundleName">Name of the future bundle</param> /// <param name="urls">List of URL of the TS file</param> /// <param name="debug">Set if we we are in debug mode(true)</param> /// <returns>The right JS file (.min if not debug)</returns> public static MvcHtmlString TypeScript(this HtmlHelper helper, string bundleName, IEnumerable<string> urls, bool debug = false) { if (!debug) { bundleName = "~/bundles/" + bundleName; var bundleUrl = BundleTable.Bundles.ResolveBundleUrl(bundleName); if (bundleUrl != null) return new MvcHtmlString(string.Format(ScriptTag, bundleUrl)); } var realUrls = new List<string>(); foreach (var url in urls) { // ReSharper disable once NotResolvedInText if (debug && string.IsNullOrWhiteSpace(url)) throw new ArgumentNullException(@"TypeScript Helper"); var suffixPos = url.LastIndexOf('.'); if (debug && (suffixPos < 0 || url.Substring(suffixPos) != ".ts")) throw new ArgumentException("TypeScript Helper : bad name or bad suffix"); realUrls.Add(url.Substring(0, suffixPos)+".js"); } return helper.JavaScript(bundleName, realUrls, debug); } ///// <summary> ///// Load a JS, create a Bundle ///// and set the script tag to load it ///// </summary> ///// <param name="helper">The HTML context</param> ///// <param name="url">Ulr of JS file without the JS extention</param> ///// <param name="debug">Set if we we are in debug mode(true)</param> ///// <returns>Return the script source</returns> //public static MvcHtmlString JavaScript(this HtmlHelper helper, string url, bool debug = false) //{ // return JavaScript(helper, url, true, debug); //} /// <summary> /// Load a JS, create a Bundle /// and set the script tag to load it /// </summary> /// <param name="helper">The HTML context</param> /// <param name="url">Ulr of JS file without the JS extention</param> /// <param name="noBundle"></param> /// <param name="debug">Set if we we are in debug mode(true)</param> /// <returns>Return the script source</returns> public static MvcHtmlString JavaScript(this HtmlHelper helper, string url, bool noBundle = false, bool debug = false) { if (url.EndsWith(".js")) url = url.Substring(0, url.Length - 3); // if we are in debug mode, just return the script tag if (debug) return new MvcHtmlString(string.Format(ScriptTag, System.Web.VirtualPathUtility.ToAbsolute(url + ".js") + "?v=" + DateTime.UtcNow.Ticks)); if (!noBundle) { // if BundleName is null, don't use the bundle and send just a script tag (with .min) return new MvcHtmlString(string.Format(ScriptTag, System.Web.VirtualPathUtility.ToAbsolute(url + ".min.js") + "?v=" + CacheTag)); } // try to find the bundle in app bundles table var bundleUrl = BundleTable.Bundles.ResolveBundleUrl(url); if (bundleUrl != null) return new MvcHtmlString(string.Format(ScriptTag, bundleUrl)); // if not found, create it (for everybody) var jsBundle = new ScriptBundle(url).Include(url + ".js"); BundleTable.Bundles.Add(jsBundle); bundleUrl = BundleTable.Bundles.ResolveBundleUrl(url) + "?v=" + CacheTag; // return the script tag with the right bundle url return new MvcHtmlString(string.Format(ScriptTag, bundleUrl)); } /// <summary> /// Load some JS files, create a Bundle /// and set the script tag to load it /// </summary> /// <param name="helper">The HTML context</param> /// <param name="bundleName">The name of the future bundle</param> /// <param name="urls">URL list of JS file without the JS extention</param> /// <param name="debug">Set if we we are in debug mode(true)</param> /// <returns></returns> public static MvcHtmlString JavaScript(this HtmlHelper helper, string bundleName, IEnumerable<string> urls, bool debug = false) { // if we are in debug mode, just return the script tags if (debug) { // UTC now is use for prevent against cache joke var scr = urls.Aggregate("", (current, url) => current + string.Format(ScriptTag, System.Web.VirtualPathUtility.ToAbsolute(url) + "?v=" + DateTime.UtcNow.Ticks)); return new MvcHtmlString(scr); } if (string.IsNullOrEmpty(bundleName)) { // if BundleName is null, don't use the bundle and send just a script tag (with .min) var scr = urls.Aggregate("", (current, url) => current + string.Format(ScriptTag, System.Web.VirtualPathUtility.ToAbsolute(url.Substring(0, url.LastIndexOf(".js", StringComparison.Ordinal)) + ".min.js") + "?v=" + CacheTag)); return new MvcHtmlString(scr); } // try to find the bundle in app bundles table var bundleUrl = BundleTable.Bundles.ResolveBundleUrl(bundleName); if (bundleUrl == null) { // if not found, create it (for everybody) var jsBundle = new ScriptBundle(bundleName); foreach (var url in urls) { // include all js in bundle jsBundle.Include(url); } BundleTable.Bundles.Add(jsBundle); bundleUrl = BundleTable.Bundles.ResolveBundleUrl(bundleName); } // return the script tag with the right bundle url return new MvcHtmlString(string.Format(ScriptTag, bundleUrl)); } /// <summary> /// Add Jquery files in page /// with CDN if it's release mode /// If CDN fail, it switch on local bundle /// local bundle if it's debug mode (usefull for debugging) /// </summary> /// <param name="helper">HTML Context</param> /// <param name="debug">Set if we we are in debug mode(true)</param> /// <param name="bundleName">Default name of JQuery bundle (default : ~/bundles/jquery) </param> /// <param name="version">Default version of JQuery (3.1.0 by default)</param> /// <returns>Scripts url for JQuery</returns> public static MvcHtmlString JQuery(this HtmlHelper helper, bool debug = false, string bundleName = "~/bundles/jquery", string version = "3.1.1") { var bundleUrl = BundleTable.Bundles.ResolveBundleUrl(bundleName); if (debug) return new MvcHtmlString(string.Format(ScriptTag, bundleUrl)); // setup the script to load Jquery from CDN //var jQueryVersion = GoogleCDNRoot + string.Format("jquery/{0}/jquery.min.js", version); // var jQueryVersion = MicrosoftCDNRoot + string.Format("jQuery/jquery-{0}.min.js", version); var jQueryVersion = string.Format("https://code.jquery.com/jquery-{0}.min.js", version); // setup the script to load Jquery if CDN is fail // Inspired by http://www.asp.net/mvc/overview/performance/bundling-and-minification // && http://www.hanselman.com/blog/CDNsFailButYourScriptsDontHaveToFallbackFromCDNToLocalJQuery.aspx var switchNoCdn = string.Format("\x3Cscript>(window.jQuery)||document.write('<script src=\"{0}\"><\\/script>');</script>", bundleUrl); // string.Format("<script src='{0}'></script><script>(window.jQuery)||document.write('<script src=\"{1}\">\x3C/script>');</script>", jQueryVersion, bundleUrl); return new MvcHtmlString(string.Format(ScriptTag, jQueryVersion) + switchNoCdn); } /// <summary> /// Add Jquery validation files in page /// with CDN if it's release mode and local bundle /// if it's debug mode (usefull for debugging) /// </summary> /// <param name="helper">HTML Context</param> /// <param name="debug">Set if we we are in debug mode(true)</param> /// <param name="bundleName">Default name of JQuery Validate bundle (default : ~/bundles/jqueryval)</param> /// <param name="version">Default version of JQuery Validate (1.14.0 by default)</param> /// <param name="mvcVersion">Default version of JQuery Validate Unobtrusive (5.2.3 by default)</param> /// <returns>Scripts url for validations</returns> public static MvcHtmlString JQueryVal(this HtmlHelper helper, bool debug = false, string bundleName = "~/bundles/jqueryval", string version = "1.15.1", string mvcVersion = "5.2.3") { // todo : increase version when MS CDN is ready // todo : include localized message if (!debug) { var scriptValidate = string.Format("{0}jquery.validate/{1}/jquery.validate.min.js", MicrosoftCDNRoot, version); var scriptValidateAdditionalMethods = string.Format("{0}jquery.validate/{1}/additional-methods.min.js", MicrosoftCDNRoot, version); var scriptUnobtrusive = string.Format("{0}mvc/{1}/jquery.validate.unobtrusive.min.js", MicrosoftCDNRoot, mvcVersion); return new MvcHtmlString( string.Format(ScriptTag, scriptValidate) + string.Format(ScriptTag, scriptValidateAdditionalMethods) + string.Format(ScriptTag, scriptUnobtrusive)); } var bundleUrl = BundleTable.Bundles.ResolveBundleUrl(bundleName); return new MvcHtmlString(string.Format(ScriptTag, bundleUrl)); } /// <summary> /// In full less configuration (or with webessential) /// VS/Build generate file.css and file.min.css /// this method choose the right file depend of mode 'release' or 'debug' /// </summary> /// <param name="helper">HTML Context</param> /// <param name="name">The CSS files</param> /// <param name="debug">Set if we we are in debug mode(true)</param> /// <returns></returns> public static MvcHtmlString Css(this HtmlHelper helper, string name, bool debug = false) { if (!debug) { // in release mode, we send the minify version of css name = name.Substring(0, name.LastIndexOf('.')) + ".min.css"; } name += "?v=" + CacheTag; return new MvcHtmlString(string.Format("<link rel='stylesheet' href='{0}'>", System.Web.VirtualPathUtility.ToAbsolute(name))); } /// <summary> /// Helper to combine with ResourceBuilder Class /// Give the right bundle Url contructed by /// Resources Builder /// </summary> /// <param name="helper">HTML context</param> /// <param name="language">Language of JS file</param> /// <returns>Url of JSON/JS Resources</returns> public static MvcHtmlString ResourcesJS(this HtmlHelper helper, string language = "en") { const string resxName = "~/bundles/resources"; var culture = helper.BrowserCulture(); var fullLang = string.Empty; var isoLang = "." + language; // by convention, English (en) is the main language // and it should not be modified if (culture.Name != language) { // else we add the standard name of language fullLang = "_" + culture.Name; isoLang = "_" + culture.TwoLetterISOLanguageName; } // and we try to find the good ressources file (depend of create method) // first the full language package (eg : fr-FR) // second the main language package (eg : fr) // and if it's not found, we use the main pack : en var bundleUrl = BundleTable.Bundles.ResolveBundleUrl(resxName + fullLang) ?? BundleTable.Bundles.ResolveBundleUrl(resxName + isoLang) ?? BundleTable.Bundles.ResolveBundleUrl(resxName); return new MvcHtmlString(string.Format(ScriptTag, bundleUrl)); } /// <summary> /// Get the culture from browser (client side) /// </summary> /// <param name="helper">Html Context</param> /// <returns>A culture</returns> public static CultureInfo BrowserCulture(this HtmlHelper helper) { // get from browser var userLanguages = helper.ViewContext.HttpContext.Request.UserLanguages; CultureInfo ci; if (userLanguages != null && userLanguages.Any()) { // browser have one or more language try { // take the first ci = new CultureInfo(userLanguages[0]); } catch (CultureNotFoundException) { ci = CultureInfo.InvariantCulture; } } else { ci = CultureInfo.InvariantCulture; } return ci; } /// <summary> /// Compose a valid Gravatar Url from email /// /// see : https://fr.gravatar.com/site/implement/images/ /// for more details /// </summary> /// <param name="helper">Html Helper context</param> /// <param name="mailAdd">Address to use</param> /// <param name="size">By default, images are presented at 80px by 80px</param> /// <param name="default"> /// 404: do not load any image if none is associated with the email hash, instead return an HTTP 404 (File Not Found) response /// mm: (mystery-man) a simple, cartoon-style silhouetted outline of a person (does not vary by email hash) /// identicon: a geometric pattern based on an email hash /// monsterid: a generated 'monster' with different colors, faces, etc /// wavatar: generated faces with differing features and backgrounds /// retro: awesome generated, 8-bit arcade-style pixelated faces /// blank: a transparent PNG image (border added to HTML below for demonstration purposes) /// </param> /// <param name="altText">Alternate text for image (default : Gravatar Image)</param> /// <param name="cssClass">Add a special class on img tag</param> /// <returns>url of Gravatar image</returns> public static MvcHtmlString GravatarImage(this HtmlHelper helper, string mailAdd, int size = 80, string @default = "404", string cssClass = "", string altText = "Gravatar Image") { const string gravatarUrl = "<img src='http://www.gravatar.com/avatar/{0}?s={1}&d={2}' {4} alt='{3}'>"; var hash = (string.IsNullOrWhiteSpace(mailAdd)) ? "unknow" : MD5Helpers.GetMd5Hash(mailAdd); if (cssClass != "") cssClass = "class='" + cssClass + "'"; return new MvcHtmlString(string.Format(gravatarUrl, hash, size, @default, altText, cssClass)); } /// <summary> /// Compose a valid Gravatar Url from email /// /// see : https://gravatar.com/site/implement/images/ /// for more details /// </summary> /// <param name="mailAdd">Address to use</param> /// <param name="size">By default, images are presented at 80px by 80px</param> /// <param name="default"> /// 404: do not load any image if none is associated with the email hash, instead return an HTTP 404 (File Not Found) response /// mm: (mystery-man) a simple, cartoon-style silhouetted outline of a person (does not vary by email hash) /// identicon: a geometric pattern based on an email hash /// monsterid: a generated 'monster' with different colors, faces, etc /// wavatar: generated faces with differing features and backgrounds /// retro: awesome generated, 8-bit arcade-style pixelated faces /// blank: a transparent PNG image (border added to HTML below for demonstration purposes) /// </param> /// <param name="altText">Alternate text for image (default : Gravatar Image)</param> /// <returns>url of Gravatar image</returns> public static string CreateGravatarUrl(string mailAdd, int size = 80, string @default = "404", string altText = "Gravatar Image") { const string gravatarUrl = "<img src='http://www.gravatar.com/avatar/{0}?s={1}&d={2}' alt='{3}'>"; var hash = (string.IsNullOrWhiteSpace(mailAdd)) ? "unknow" : MD5Helpers.GetMd5Hash(mailAdd); return string.Format(gravatarUrl, hash, size, @default, altText); } /// <summary> /// Add a bundle with /// Google Analytics /// MS Application Insight /// You should have a Analytics sub-directory in Scripts /// this sub-dir should contain google-analytics.js and /// ApplicationInsight.js /// </summary> /// <param name="helper">Html Context</param> /// <param name="debug">Set if we we are in debug mode(true)</param> /// <param name="useUserId">Use the user id (from IPrincipal) in ga (if user is connected)</param> /// <returns>Html String to inject in page</returns> public static MvcHtmlString AnalyticsScript(this HtmlHelper helper, bool debug = false, bool useUserId = false) { var applicationInsightsKey = WebConfigurationManager.AppSettings["applicationInsights"]; if (string.IsNullOrEmpty(applicationInsightsKey) && debug) return null; var script = new StringBuilder("<script type='text/javascript'>"); if (!debug) { var googlekey = WebConfigurationManager.AppSettings["GoogleAnalytics"]; if (!string.IsNullOrWhiteSpace(googlekey)) { var googleScript = "(function (i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a, m)})(window,document,'script','//www.google-analytics.com/analytics.js','ga');ga('create','" + googlekey + "','auto');ga('send','pageview');"; if (useUserId && helper.ViewContext.HttpContext.Request.IsAuthenticated) { // Set the userid (an hashcode of name) for a better tracing // https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#userId googleScript += string.Format("ga('set','userId','{0}');", helper.ViewContext.HttpContext.User.Identity.Name.GetHashCode()); } script.AppendLine(googleScript); } } if (!string.IsNullOrEmpty(applicationInsightsKey)) { script.AppendFormat("window.applicationInsightsKey='{0}';", applicationInsightsKey); } script.Append("</script>"); script.Append(Scripts.Render("~/bundles/analytics")); return new MvcHtmlString(script.ToString()); } /// <summary> /// Add an * to the label if the field is required /// </summary> /// <typeparam name="TModel"></typeparam> /// <typeparam name="TProperty"></typeparam> /// <param name="html"></param> /// <param name="expression"></param> /// <param name="htmlAttributes"></param> /// <param name="title">title of the label ("this field is required" by default)</param> /// <returns></returns> public static MvcHtmlString LabelWithRequiredFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression, object htmlAttributes = null, string title = "this field is required") { var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData); if (!metadata.IsRequired) return html.LabelFor(expression, htmlAttributes); var label = html.LabelFor(expression, htmlAttributes).ToHtmlString(); label = label.Replace("</label>", string.Format("<span class='text-danger required' title='{0}'>&nbsp;*</span></label>", title)); label = label.Replace("<label for", "<label class='required' for"); return MvcHtmlString.Create(label); } #region Compressed Partial /// <summary> /// Compress a partial view /// </summary> /// <param name="htmlHelper">HTML Context</param> /// <param name="partialViewName">The name (and path) of the partial view</param> /// <returns>The HTML code of partial compressed</returns> public static MvcHtmlString CompressedPartial(this HtmlHelper htmlHelper, string partialViewName) { return CompressedPartial(htmlHelper, partialViewName, null /* model */, htmlHelper.ViewData); } /// <summary> /// Compress a partial view /// </summary> /// <param name="htmlHelper">HTML Context</param> /// <param name="partialViewName">The name (and path) of the partial view</param> /// <param name="viewData">Additionnal data from server</param> /// <returns>The HTML code of partial compressed</returns> public static MvcHtmlString CompressedPartial(this HtmlHelper htmlHelper, string partialViewName, ViewDataDictionary viewData) { return CompressedPartial(htmlHelper, partialViewName, null /* model */, viewData); } /// <summary> /// Compress a partial view /// </summary> /// <param name="htmlHelper">HTML Context</param> /// <param name="partialViewName">The name (and path) of the partial view</param> /// <param name="model">Model come from server</param> /// <returns>The HTML code of partial compressed</returns> public static MvcHtmlString CompressedPartial(this HtmlHelper htmlHelper, string partialViewName, object model) { return CompressedPartial(htmlHelper, partialViewName, model, htmlHelper.ViewData); } /// <summary> /// Compress a partial view /// </summary> /// <param name="htmlHelper">HTML Context</param> /// <param name="partialViewName">The name (and path) of the partial view</param> /// <param name="model">Model come from server</param> /// <param name="viewData">Additionnal data from server</param> /// <returns>The HTML code of partial compressed</returns> public static MvcHtmlString CompressedPartial(this HtmlHelper htmlHelper, string partialViewName, object model, ViewDataDictionary viewData) { var result = htmlHelper.RenderPartialInternal(partialViewName, viewData, model, ViewEngines.Engines); return MvcHtmlString.Create(result); } private static string RenderPartialInternal(this HtmlHelper htmlHelper, string partialViewName, ViewDataDictionary viewData, object model, ViewEngineCollection viewEngineCollection) { #if DEBUG if (String.IsNullOrEmpty(partialViewName)) { throw new ArgumentException(@"Empty view", "partialViewName"); } #endif ViewDataDictionary newViewData = model == null ? (viewData == null ? new ViewDataDictionary(htmlHelper.ViewData) : new ViewDataDictionary(viewData)) : (viewData == null ? new ViewDataDictionary(model) : new ViewDataDictionary(viewData) { Model = model }); using (var writer = new StringWriter(CultureInfo.CurrentCulture)) { var newViewContext = new ViewContext(htmlHelper.ViewContext, htmlHelper.ViewContext.View, newViewData, htmlHelper.ViewContext.TempData, writer); var view = viewEngineCollection.FindPartialView(newViewContext, partialViewName).View; view.Render(newViewContext, writer); return SimpleHtmlMinifier(writer.ToString()); } } private static string SimpleHtmlMinifier(string html) { html = Regex.Replace(html, @"(?<=[^])\t{2,}|(?<=[>])\s{2,}(?=[<])|(?<=[>])\s{2,11}(?=[<])|(?=[\n])\s{2,}", ""); html = Regex.Replace(html, @"[ \f\r\t\v]?([\n\xFE\xFF/{}[\];,<>*%&|^!~?:=])[\f\r\t\v]?", "$1"); html = html.Replace(";\n", ";"); return html; } #endregion } }
RaynaldM/asp.net-mvc-helpers
aspnet-mvc-helpers/HtmlExtensions.cs
C#
mit
28,743
class BlinkyTapeOrb VERSION = '0.1.0' end
jtai/blinkytape-orb
lib/blinkytape-orb/version.rb
Ruby
mit
44
package com.almasb.mp; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javafx.animation.FadeTransition; import javafx.application.Application; import javafx.geometry.Pos; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.input.MouseEvent; import javafx.scene.layout.Pane; import javafx.scene.layout.StackPane; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.scene.text.Font; import javafx.scene.text.Text; import javafx.stage.Stage; import javafx.util.Duration; public class MemoryPuzzleApp extends Application { private static final int NUM_OF_PAIRS = 72; private static final int NUM_PER_ROW = 12; private Tile selected = null; private int clickCount = 2; private Parent createContent() { Pane root = new Pane(); root.setPrefSize(600, 600); char c = 'A'; List<Tile> tiles = new ArrayList<>(); for (int i = 0; i < NUM_OF_PAIRS; i++) { tiles.add(new Tile(String.valueOf(c))); tiles.add(new Tile(String.valueOf(c))); c++; } Collections.shuffle(tiles); for (int i = 0; i < tiles.size(); i++) { Tile tile = tiles.get(i); tile.setTranslateX(50 * (i % NUM_PER_ROW)); tile.setTranslateY(50 * (i / NUM_PER_ROW)); root.getChildren().add(tile); } return root; } @Override public void start(Stage primaryStage) throws Exception { primaryStage.setScene(new Scene(createContent())); primaryStage.show(); } private class Tile extends StackPane { private Text text = new Text(); public Tile(String value) { Rectangle border = new Rectangle(50, 50); border.setFill(null); border.setStroke(Color.BLACK); text.setText(value); text.setFont(Font.font(30)); setAlignment(Pos.CENTER); getChildren().addAll(border, text); setOnMouseClicked(this::handleMouseClick); close(); } public void handleMouseClick(MouseEvent event) { if (isOpen() || clickCount == 0) return; clickCount--; if (selected == null) { selected = this; open(() -> {}); } else { open(() -> { if (!hasSameValue(selected)) { selected.close(); this.close(); } selected = null; clickCount = 2; }); } } public boolean isOpen() { return text.getOpacity() == 1; } public void open(Runnable action) { FadeTransition ft = new FadeTransition(Duration.seconds(0.5), text); ft.setToValue(1); ft.setOnFinished(e -> action.run()); ft.play(); } public void close() { FadeTransition ft = new FadeTransition(Duration.seconds(0.5), text); ft.setToValue(0); ft.play(); } public boolean hasSameValue(Tile other) { return text.getText().equals(other.text.getText()); } } public static void main(String[] args) { launch(args); } }
AlmasB/FXTutorials
src/main/java/com/almasb/mp/MemoryPuzzleApp.java
Java
mit
3,420
# http://github.com/timestocome # use hidden markov model to predict changes in a stock market index fund # http://cs229.stanford.edu/proj2009/ShinLee.pdf # https://www.dartmouth.edu/~chance/teaching_aids/books_articles/probability_book/Chapter11.pdf import numpy as np import pandas as pd import tensorflow as tf import matplotlib.pyplot as plt # pandas display options pd.options.display.max_rows = 1000 pd.options.display.max_columns = 25 pd.options.display.width = 1000 ###################################################################### # data ######################################################################## # read in datafile created in LoadAndMatchDates.py data = pd.read_csv('StockDataWithVolume.csv', index_col='Date', parse_dates=True) features = [data.columns.values] # create target --- let's try Nasdaq value 1 day change data['returns'] = (data['NASDAQ'] - data['NASDAQ'].shift(1)) / data['NASDAQ'] # remove nan row from target creation data = data.dropna() ################################################################### # Simple markov chain ################################################################### # first pass only used 4 bins ( highGain, lowGain, lowLoss, highLoss ) # looks to be ~0.13, -.112, ~.25 diff between highest and lowest # divide returns into bins # round(2) gives 22 unique bins # round(3) gives 157 bins # round(4) gives 848 bins round_values = 4 data['gainLoss'] = data['returns'].round(round_values) total_samples = len(data) n_bins = data['gainLoss'].nunique() value_count = data['gainLoss'].value_counts() value_count = value_count.sort_index() b = value_count.index.tolist() bins = ['%.4f' % z for z in b] # match to round value #print(value_count) # calculate probability of a return value on a random day probability = value_count / total_samples #print(probability) # built transition matrix transitions = np.zeros((n_bins, n_bins)) def map_transition(this_return, previous_return): current = np.where(probability.index==this_return)[0] - 1 # pandas starts at 1, numpy starts at zero previous = np.where(probability.index==previous_return)[0] - 1 transitions[current, previous] += 1 total_transitions = 0 for i in range(len(data)-1): total_transitions += 1 previous = data.iloc[i]['gainLoss'] current = data.iloc[i+1]['gainLoss'] map_transition(current, previous) # normalize matrix, then normalize rows transitions /= total_transitions transitions /= transitions.sum(axis=0) ####################################################################################### # make a prediction # n number of days into future # s today's state hg, lg, ll, hl # t transition matrix that was calculated s = -.03 # today's gain or loss --- be sure it is a valid bin n = 5 t = transitions prediction_probabilities = (t **n) row_number = np.where(probability.index==s)[0] - 1 # pandas starts at 1, numpy starts at zero probabilities = prediction_probabilities[row_number] mostlikely = probabilities.argmax() bin_value = float(bins[mostlikely]) print("%d days from now, the market return will be %.2f" % (n, bin_value)) ###################################################################################### # plot predictions over time # scale prediction for plotting def convert_return_for_plot(r): return bins[r] days_ahead = 5 p = [] for i in range(len(data)-1): s = data.iloc[i]['gainLoss'] # get current day return from market prediction_probabilities = (transitions **n) # predict all probabilities for future date row_number = np.where(probability.index==s)[0] - 1 # get row number matching today's return probabilities = prediction_probabilities[row_number] mostlikely = probabilities.argmax() bin_value = bins[mostlikely] p.append(bin_value) # pad begining of p p = ([0] * 1 + p) data['predicted'] = p plt.figure(figsize=(12,12)) plt.title("Nasdaq daily gain/loss using single chain markov 5 days out") plt.plot(data['returns'], label='Actual') plt.plot(data['predicted'], label='Predicted', alpha=0.5) plt.legend(loc='best') plt.savefig("SingleChainMarkov.png") plt.show()
timestocome/Test-stock-prediction-algorithms
Misc experiments/Stocks_SimpleMarkovChain.py
Python
mit
4,218
package testserver import ( "net/http/httptest" "github.com/gorilla/mux" "github.com/pivotal-cf-experimental/warrant/internal/server/clients" "github.com/pivotal-cf-experimental/warrant/internal/server/common" "github.com/pivotal-cf-experimental/warrant/internal/server/domain" "github.com/pivotal-cf-experimental/warrant/internal/server/groups" "github.com/pivotal-cf-experimental/warrant/internal/server/tokens" "github.com/pivotal-cf-experimental/warrant/internal/server/users" ) var defaultScopes = []string{ "scim.read", "cloudcontroller.admin", "password.write", "scim.write", "openid", "cloud_controller.write", "cloud_controller.read", "doppler.firehose", "notification_preferences.write", "notification_preferences.read", } // UAA is a fake implementation of the UAA HTTP service. type UAA struct { server *httptest.Server users *domain.Users clients *domain.Clients groups *domain.Groups tokens *domain.Tokens publicKey string privateKey string } // NewUAA returns a new UAA initialized with the given Config. func NewUAA() *UAA { privateKey := common.TestPrivateKey publicKey := common.TestPublicKey tokensCollection := domain.NewTokens(publicKey, privateKey, defaultScopes) usersCollection := domain.NewUsers() clientsCollection := domain.NewClients() groupsCollection := domain.NewGroups() router := mux.NewRouter() uaa := &UAA{ server: httptest.NewUnstartedServer(router), tokens: tokensCollection, users: usersCollection, clients: clientsCollection, groups: groupsCollection, privateKey: privateKey, publicKey: publicKey, } tokenRouter := tokens.NewRouter( tokensCollection, usersCollection, clientsCollection, publicKey, privateKey, uaa) router.Handle("/Users{a:.*}", users.NewRouter(usersCollection, tokensCollection)) router.Handle("/Groups{a:.*}", groups.NewRouter(groupsCollection, tokensCollection)) router.Handle("/oauth/clients{a:.*}", clients.NewRouter(clientsCollection, tokensCollection)) router.Handle("/oauth{a:.*}", tokenRouter) router.Handle("/token_key{a:.*}", tokenRouter) return uaa } func (s *UAA) PublicKey() string { return s.publicKey } func (s *UAA) PrivateKey() string { return s.privateKey } // Start will cause the HTTP server to bind to a port // and start serving requests. func (s *UAA) Start() { s.server.Start() } // Close will cause the HTTP server to stop serving // requests and close its connection. func (s *UAA) Close() { s.server.Close() } // Reset will clear all internal resource state within // the server. This means that all users, clients, and // groups will be deleted. func (s *UAA) Reset() { s.users.Clear() s.clients.Clear() s.groups.Clear() } // URL returns the url that the server is hosted on. func (s *UAA) URL() string { return s.server.URL } // SetDefaultScopes allows the default scopes applied to a // user to be configured. func (s *UAA) SetDefaultScopes(scopes []string) { s.tokens.DefaultScopes = scopes } // TODO: move this configuration onto the Config // ResetDefaultScopes resets the default scopes back to their // original values. func (s *UAA) ResetDefaultScopes() { s.tokens.DefaultScopes = defaultScopes } // UserTokenFor returns a user token with the given id, // scopes, and audiences. func (s *UAA) UserTokenFor(userID string, scopes, audiences []string) string { // TODO: remove from API so that tokens are fetched like // they would be with a real UAA server. return s.tokens.Encrypt(domain.Token{ UserID: userID, Scopes: scopes, Audiences: audiences, }) }
pivotal-cf-experimental/warrant
testserver/uaa.go
GO
mit
3,586
import { CommandManager } from "./../../browser/src/Services/CommandManager" export const mockRegisterCommands = jest.fn() const MockCommands = jest.fn<CommandManager>().mockImplementation(() => ({ registerCommand: mockRegisterCommands, })) export default MockCommands
extr0py/oni
ui-tests/mocks/CommandManager.ts
TypeScript
mit
275
module DocuSign class DocuSignResponse def self.new(*args) response = args.first case response.to_hash.keys.first.to_sym when :create_and_send_envelope_response return EnvelopeStatus.new(response.to_hash[:create_and_send_envelope_response][:create_and_send_envelope_result]) when :request_status_response return EnvelopeStatus.new(response.to_hash[:request_status_response][:request_status_result]) when :request_status_ex_response return EnvelopeStatus.new(response.to_hash[:request_status_ex_response][:request_status_ex_result]) when :request_envelope_response return Envelope.new(response.to_hash[:request_envelope_response][:request_envelope_result]) when :void_envelope_response return VoidEnvelopeStatus.new(response.to_hash[:void_envelope_response][:void_envelope_result]) when :correct_and_resend_envelope_response return nil when :request_document_pd_fs_ex_response return response.to_hash[:request_document_pd_fs_ex_response][:request_document_pd_fs_ex_result][:document_pdf].map {|document_pdf_attributes| DocumentPDF.new(document_pdf_attributes)} when :request_recipient_token_response return RecipientToken.new(response.to_hash[:request_recipient_token_response][:request_recipient_token_result]) else puts response.to_hash.inspect return response end end end end
phanle/docu_sign
lib/docu_sign/docu_sign_response.rb
Ruby
mit
1,483
# frozen_string_literal: true module EGPRates # Suez Canal Bank class SuezCanalBank < EGPRates::Bank def initialize @sym = :SuezCanalBank @uri = URI.parse('http://scbank.com.eg/CurrencyAll.aspx') end # @return [Hash] of exchange rates for selling and buying # { # { sell: { SYM: rate }, { SYM: rate }, ... }, # { buy: { SYM: rate }, { SYM: rate }, ... } # } def exchange_rates @exchange_rates ||= parse(raw_exchange_rates) end # Send the request to the URL and retrun raw data of the response # @return [Enumerator::Lazy] with the table row in HTML that evaluates to # [ # "\r\n ", "\r\n ", "\r\n ", "\r\n US Dollar ", "\r\n ", # "\r\n 15.1500", "\r\n ", "\r\n 15.8000", "\r\n ", ... # ], [ # "\r\n ", "\r\n ", "\r\n ", "\r\n Sterling Pound", "\r\n ", # "\r\n 18.5933", "\r\n ", "\r\n 20.0448", "\r\n ", ... # ], # rubocop:disable Style/MultilineMethodCallIndentation def raw_exchange_rates # Suez Canal Bank provides 13 currencies only table_rows = Oga.parse_html(response.body)\ .css('#Table_01 tr:nth-child(4) > td:nth-child(2) > table tr') # But they have 2 <tr> used for the table headers fail ResponseError, 'Unknown HTML' unless table_rows&.size == 15 table_rows.lazy.drop(2).map(&:children).map { |cell| cell.map(&:text) } end # rubocop:enable Style/MultilineMethodCallIndentation # Parse the #raw_exchange_rates returned in response # @param [Array] of the raw_data scraped # @return [Hash] of exchange rates for selling and buying # { # { sell: { SYM: rate }, { SYM: rate }, ... }, # { buy: { SYM: rate }, { SYM: rate }, ... } # } def parse(raw_data) raw_data.each_with_object(sell: {}, buy: {}) do |row, result| sell_rate = row[7].to_f buy_rate = row[5].to_f currency = currency_symbol(row[3].strip) result[:sell][currency] = sell_rate result[:buy][currency] = buy_rate end end end end
mad-raz/EGP-Rates
lib/egp_rates/suez_canal_bank.rb
Ruby
mit
2,091
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; namespace DynamicDbSet.Models { public interface IEntityRelationType { long Id { get; set; } long ToClassId { get; set; } string Name { get; set; } EntityClass ToClass { get; set; } IEnumerable<IEntityAttributeType> AttributeTypes { get; } IEnumerable<IEntityRelation> Relations { get; } } public abstract class EntityRelationType<TEntity, TEntityAttribute, TEntityAttributeType, TEntityRelation, TEntityRelationType> : IEntityRelationType where TEntity : Entity<TEntity, TEntityAttribute, TEntityAttributeType, TEntityRelation, TEntityRelationType> where TEntityAttribute : EntityAttribute<TEntity, TEntityAttribute, TEntityAttributeType, TEntityRelation, TEntityRelationType> where TEntityAttributeType : EntityAttributeType<TEntity, TEntityAttribute, TEntityAttributeType, TEntityRelation, TEntityRelationType> where TEntityRelation : EntityRelation<TEntity, TEntityAttribute, TEntityAttributeType, TEntityRelation, TEntityRelationType> where TEntityRelationType : EntityRelationType<TEntity, TEntityAttribute, TEntityAttributeType, TEntityRelation, TEntityRelationType> { #region Fields public abstract long Id { get; set; } public long ToClassId { get; set; } [Required, MaxLength(255)] public string Name { get; set; } #endregion #region Relations [ForeignKey(nameof(ToClassId))] public EntityClass ToClass { get; set; } #endregion #region Collections [InverseProperty(nameof(IEntityAttributeType.RelationType))] public ICollection<TEntityAttributeType> AttributeTypes { get; set; } = new List<TEntityAttributeType>(); IEnumerable<IEntityAttributeType> IEntityRelationType.AttributeTypes { get { return AttributeTypes?.AsEnumerable<IEntityAttributeType>(); } } [InverseProperty(nameof(IEntityRelation.Type))] public ICollection<TEntityRelation> Relations { get; set; } = new List<TEntityRelation>(); IEnumerable<IEntityRelation> IEntityRelationType.Relations { get { return Relations?.AsEnumerable<IEntityRelation>(); } } #endregion } }
entitycontext/ef6-dynamic-dbset
src/DynamicDbSet/Models/EntityRelationType.cs
C#
mit
2,431
import * as Router from "universal-router"; import routes from "~/routes"; export default new Router(routes, { resolveRoute(context, params) { let { route } = context; // if (typeof route.load === 'function') { // return route.load().then(action => action.default(context, params)); // } //this function will be rendered only once for initial props loading no more! if (typeof route.getInitialProps === "function" && !route.props) { //return new Promise((resolve, reject) => { // to make sure that when there is server side props, we don't invoke getInitialProps from client side let props = context.state && context.state.route && context.state.route[route.path]; let state = objectWithoutKey(context.state, "route"); const serverProps = { props, state }; return route.getInitialProps(serverProps).then(props => { route.props = context.props = props || {}; return route.action(context, params); }); } if (typeof route.action === "function") { context.props = route.props; return route.action(context, params); } return null; } }); const objectWithoutKey = (object, key) => { return Object.keys(object).reduce((result, propName) => { if (propName !== key) { result[propName] = object[propName]; } return result; }, {}); };
llyys/trible
src/client/router.ts
TypeScript
mit
1,374
/**! * koa-generic-session - test/session.test.js * Copyright(c) 2013 * MIT Licensed * * Authors: * dead_horse <dead_horse@qq.com> (http://deadhorse.me) */ 'use strict'; /** * Module dependencies. */ var Session = require('..'); var koa = require('koa'); var app = require('./support/server'); var request = require('supertest'); var mm = require('mm'); var should = require('should'); var EventEmitter = require('events').EventEmitter; describe('test/koa-session.test.js', function () { describe('init', function () { afterEach(mm.restore); beforeEach(function (done) { request(app) .get('/session/remive') .expect(200, done); }); it('should warn when in production', function (done) { mm(process.env, 'NODE_ENV', 'production'); mm(console, 'warn', function (message) { message.should.equal('Warning: koa-generic-session\'s MemoryStore is not\n' + 'designed for a production environment, as it will leak\n' + 'memory, and will not scale past a single process.'); done(); }); Session({secret: 'secret'}); }); it('should listen disconnect and connect', function () { var store = new EventEmitter(); Session({ secret: 'secret', store: store }); store._events.disconnect.should.be.Function; store._events.connect.should.be.Function; }); }); describe('use', function () { var cookie; var mockCookie = 'koa.sid=s:dsfdss.PjOnUyhFG5bkeHsZ1UbEY7bDerxBINnZsD5MUguEph8; path=/; httponly'; it('should GET /session/get ok', function (done) { request(app) .get('/session/get') .expect(/1/) .end(function (err, res) { cookie = res.headers['set-cookie'].join(';'); done(); }); }); it('should GET /session/get second ok', function (done) { request(app) .get('/session/get') .set('cookie', cookie) .expect(/2/, done); }); it('should GET /session/httponly ok', function (done) { request(app) .get('/session/httponly') .set('cookie', cookie) .expect(/httpOnly: false/, function (err, res) { should.not.exist(err); cookie = res.headers['set-cookie'].join(';'); cookie.indexOf('httponly').should.equal(-1); cookie.indexOf('expires=').should.above(0); request(app) .get('/session/get') .set('cookie', cookie) .expect(/3/, done); }); }); it('should GET /session/httponly twice ok', function (done) { request(app) .get('/session/httponly') .set('cookie', cookie) .expect(/httpOnly: true/, function (err, res) { should.not.exist(err); cookie = res.headers['set-cookie'].join(';'); cookie.indexOf('httponly').should.above(0); cookie.indexOf('expires=').should.above(0); done(); }); }); it('should another user GET /session/get ok', function (done) { request(app) .get('/session/get') .expect(/1/, done); }); it('should GET /session/nothing ok', function (done) { request(app) .get('/session/nothing') .set('cookie', cookie) .expect(/3/, done); }); it('should wrong cookie GET /session/get ok', function (done) { request(app) .get('/session/get') .set('cookie', mockCookie) .expect(/1/, done); }); it('should wrong cookie GET /session/get twice ok', function (done) { request(app) .get('/session/get') .set('cookie', mockCookie) .expect(/1/, done); }); it('should GET /wrongpath response no session', function (done) { request(app) .get('/wrongpath') .set('cookie', cookie) .expect(/no session/, done); }); it('should GET /session/remove ok', function (done) { request(app) .get('/session/remove') .set('cookie', cookie) .expect(/0/, function () { request(app) .get('/session/get') .set('cookie', cookie) .expect(/1/, done); }); }); it('should GET / error by session ok', function (done) { request(app) .get('/') .expect(/no session/, done); }); it('should GET /session ok', function (done) { request(app) .get('/session') .expect(/has session/, done); }); it('should rewrite session before get ok', function (done) { request(app) .get('/session/rewrite') .expect({foo: 'bar', path: '/session/rewrite'}, done); }); it('should regenerate a new session when session invalid', function (done) { request(app) .get('/session/get') .expect('1', function (err) { should.not.exist(err); request(app) .get('/session/nothing?valid=false') .expect('', function (err) { should.not.exist(err); request(app) .get('/session/get') .expect('1', done); }); }); }); it('should GET /session ok', function (done) { request(app) .get('/session/id?test_sid_append=test') .expect(/test$/, done); }); it('should force a session id ok', function (done) { request(app) .get('/session/get') .expect(/.*/, function(err, res) { should.not.exist(err); cookie = res.headers['set-cookie'][0].split(';'); var val = cookie[0].split('=').pop(); request(app) .get('/session/id?force_session_id=' + val) .expect(new RegExp(val), done); }); }); it('should regenerate existing sessions', function (done) { var agent = request.agent(app) agent .get('/session/get') .expect(/.+/, function(err, res) { var firstId = res.body; agent .get('/session/regenerate') .expect(/.+/, function(err, res) { var secondId = res.body; secondId.should.not.equal(firstId); done(); }); }); }); it('should regenerate a new session', function (done) { request(app) .get('/session/regenerateWithData') .expect({ /* foo: undefined, */ hasSession: true }, done); }); }); });
halt-hammerzeit/generic-session
test/session.test.js
JavaScript
mit
6,319