file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
__openerp__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2015 Serpent Consulting Services Pvt. Ltd. (<http://www.serpentcs.com>)
# Copyright (C) 2016 FairCoop (<http://fair.coop>)
#
# This program is f... | 'author': 'FairCoop',
'website':'http://fair.coop',
'summary': '',
'version': '1.0',
'description': """
Allows to use product brands and countries as filtering for products in website.\n
This Module depends on product_brand module -https://github.com/OCA/product-attribute/tree/8.0/product_brand
... | random_line_split | |
base.ts | import Web3 from 'web3';
import { Contract } from 'web3-eth-contract';
import { AbiItem } from 'web3-utils';
import PriceOracleABI from '../../contracts/abi/v0.9.0/price-oracle';
import ExchangeABI from '../../contracts/abi/v0.9.0/exchange';
import { getOracle, getAddress } from '../../contracts/addresses';
import BN f... | } | random_line_split | |
base.ts | import Web3 from 'web3';
import { Contract } from 'web3-eth-contract';
import { AbiItem } from 'web3-utils';
import PriceOracleABI from '../../contracts/abi/v0.9.0/price-oracle';
import ExchangeABI from '../../contracts/abi/v0.9.0/exchange';
import { getOracle, getAddress } from '../../contracts/addresses';
import BN f... |
async getRateLock(tokenAddress: string): Promise<string> {
let exchange = new this.layer2Web3.eth.Contract(
ExchangeABI as AbiItem[],
await getAddress('exchange', this.layer2Web3)
);
let { price } = await exchange.methods.exchangeRateOf(tokenAddress).call();
return price;
}
async ge... | {
let exchange = new this.layer2Web3.eth.Contract(
ExchangeABI as AbiItem[],
await getAddress('exchange', this.layer2Web3)
);
return await exchange.methods.convertFromSpend(token, amount.toString()).call();
} | identifier_body |
base.ts | import Web3 from 'web3';
import { Contract } from 'web3-eth-contract';
import { AbiItem } from 'web3-utils';
import PriceOracleABI from '../../contracts/abi/v0.9.0/price-oracle';
import ExchangeABI from '../../contracts/abi/v0.9.0/exchange';
import { getOracle, getAddress } from '../../contracts/addresses';
import BN f... | (token: string): Promise<Date> {
let oracle = await this.getOracleContract(token);
let unixTime = Number((await oracle.methods.usdPrice().call()).updatedAt);
return new Date(unixTime * 1000);
}
private async getOracleContract(token: string): Promise<Contract> {
let address = await getOracle(token, ... | getUpdatedAt | identifier_name |
retailersSelector.js | import {createSelector} from 'reselect';
import Fuse from 'fuse.js';
import _ from 'lodash';
const options = {
keys: ['name', 'address'],
threshold: 0.45
};
const f = new Fuse([], options);
const getQuery = (state) => _.get(state.retailersView, 'query', '');
const getRetailers = (state) => _.map(_.get(state, 're... | (query, retailers) {
f.set(retailers);
if (query && query.length < 32) {
return f.search(query);
} else {
return retailers;
}
} | searchProducts | identifier_name |
retailersSelector.js | import {createSelector} from 'reselect';
import Fuse from 'fuse.js';
import _ from 'lodash';
const options = {
keys: ['name', 'address'],
threshold: 0.45
};
const f = new Fuse([], options);
const getQuery = (state) => _.get(state.retailersView, 'query', '');
const getRetailers = (state) => _.map(_.get(state, 're... | } | return retailers;
} | random_line_split |
retailersSelector.js | import {createSelector} from 'reselect';
import Fuse from 'fuse.js';
import _ from 'lodash';
const options = {
keys: ['name', 'address'],
threshold: 0.45
};
const f = new Fuse([], options);
const getQuery = (state) => _.get(state.retailersView, 'query', '');
const getRetailers = (state) => _.map(_.get(state, 're... | {
f.set(retailers);
if (query && query.length < 32) {
return f.search(query);
} else {
return retailers;
}
} | identifier_body | |
retailersSelector.js | import {createSelector} from 'reselect';
import Fuse from 'fuse.js';
import _ from 'lodash';
const options = {
keys: ['name', 'address'],
threshold: 0.45
};
const f = new Fuse([], options);
const getQuery = (state) => _.get(state.retailersView, 'query', '');
const getRetailers = (state) => _.map(_.get(state, 're... | else {
return retailers;
}
} | {
return f.search(query);
} | conditional_block |
isstream-tests.ts | /// <reference types="node" />
import isStream = require('isstream');
import { isDuplex, isReadable, isWritable } from 'isstream';
import { Stream, Readable, Writable, Duplex } from 'stream';
const objs = [
new Stream(),
new Readable(),
new Writable(),
new Duplex(),
'string',
10
];
for (let i... | {
let type = 'not a stream';
if (isDuplex(objs[i])) {
type = 'duplex';
} else if (isWritable(objs[i])) {
type = 'writable';
} else if (isReadable(objs[i])) {
type = 'readable';
} else if (isStream(objs[i])) {
type = 'stream';
}
console.log(`${i}. ${type}`);
} | conditional_block | |
isstream-tests.ts | /// <reference types="node" />
import isStream = require('isstream');
import { isDuplex, isReadable, isWritable } from 'isstream';
import { Stream, Readable, Writable, Duplex } from 'stream';
| const objs = [
new Stream(),
new Readable(),
new Writable(),
new Duplex(),
'string',
10
];
for (let i = 0; i < objs.length; i++) {
let type = 'not a stream';
if (isStream.isDuplex(objs[i])) {
type = 'duplex';
} else if (isStream.isWritable(objs[i])) {
type = 'writabl... | random_line_split | |
exponent.rs | use crate::digit_table::*;
use core::ptr;
#[cfg_attr(feature = "no-panic", inline)]
pub unsafe fn write_exponent3(mut k: isize, mut result: *mut u8) -> usize {
let sign = k < 0;
if sign {
*result = b'-';
result = result.offset(1);
k = -k;
}
debug_assert!(k < 1000);
if k >= ... | {
let sign = k < 0;
if sign {
*result = b'-';
result = result.offset(1);
k = -k;
}
debug_assert!(k < 100);
if k >= 10 {
let d = DIGIT_TABLE.get_unchecked(k as usize * 2);
ptr::copy_nonoverlapping(d, result, 2);
sign as usize + 2
} else {
*... | identifier_body | |
exponent.rs | use crate::digit_table::*;
use core::ptr;
#[cfg_attr(feature = "no-panic", inline)]
pub unsafe fn write_exponent3(mut k: isize, mut result: *mut u8) -> usize {
let sign = k < 0;
if sign {
*result = b'-';
result = result.offset(1);
k = -k;
}
debug_assert!(k < 1000);
if k >= ... | else {
*result = b'0' + k as u8;
sign as usize + 1
}
}
| {
let d = DIGIT_TABLE.get_unchecked(k as usize * 2);
ptr::copy_nonoverlapping(d, result, 2);
sign as usize + 2
} | conditional_block |
exponent.rs | use crate::digit_table::*;
use core::ptr;
#[cfg_attr(feature = "no-panic", inline)]
pub unsafe fn write_exponent3(mut k: isize, mut result: *mut u8) -> usize {
let sign = k < 0;
if sign {
*result = b'-';
result = result.offset(1);
k = -k;
}
debug_assert!(k < 1000);
if k >= ... | } else {
*result = b'0' + k as u8;
sign as usize + 1
}
} | let d = DIGIT_TABLE.get_unchecked(k as usize * 2);
ptr::copy_nonoverlapping(d, result, 2);
sign as usize + 2 | random_line_split |
exponent.rs | use crate::digit_table::*;
use core::ptr;
#[cfg_attr(feature = "no-panic", inline)]
pub unsafe fn write_exponent3(mut k: isize, mut result: *mut u8) -> usize {
let sign = k < 0;
if sign {
*result = b'-';
result = result.offset(1);
k = -k;
}
debug_assert!(k < 1000);
if k >= ... | (mut k: isize, mut result: *mut u8) -> usize {
let sign = k < 0;
if sign {
*result = b'-';
result = result.offset(1);
k = -k;
}
debug_assert!(k < 100);
if k >= 10 {
let d = DIGIT_TABLE.get_unchecked(k as usize * 2);
ptr::copy_nonoverlapping(d, result, 2);
... | write_exponent2 | identifier_name |
ai.rs | // See LICENSE file for copyright and license details.
use common::types::{Size2, ZInt, PlayerId, MapPos};
use game_state::{GameState};
use map::{distance};
use pathfinder::{MapPath, Pathfinder};
use dir::{Dir};
use unit::{Unit};
use db::{Db};
use core::{CoreEvent, Command, MoveMode, los};
pub struct Ai {
id: Pla... | }
}
}
// vim: set tabstop=4 shiftwidth=4 softtabstop=4 expandtab: | random_line_split | |
ai.rs | // See LICENSE file for copyright and license details.
use common::types::{Size2, ZInt, PlayerId, MapPos};
use game_state::{GameState};
use map::{distance};
use pathfinder::{MapPath, Pathfinder};
use dir::{Dir};
use unit::{Unit};
use db::{Db};
use core::{CoreEvent, Command, MoveMode, los};
pub struct Ai {
id: Pla... |
}
}
best_pos
}
fn truncate_path(&self, path: MapPath, move_points: ZInt) -> MapPath {
if path.total_cost().n <= move_points {
return path;
}
let len = path.nodes().len();
for i in 1 .. len {
let cost = &path.nodes()[i].cost;
... | {
best_cost = Some(cost);
best_pos = Some(destination.clone());
} | conditional_block |
ai.rs | // See LICENSE file for copyright and license details.
use common::types::{Size2, ZInt, PlayerId, MapPos};
use game_state::{GameState};
use map::{distance};
use pathfinder::{MapPath, Pathfinder};
use dir::{Dir};
use unit::{Unit};
use db::{Db};
use core::{CoreEvent, Command, MoveMode, los};
pub struct | {
id: PlayerId,
state: GameState,
pathfinder: Pathfinder,
}
impl Ai {
pub fn new(id: &PlayerId, map_size: &Size2) -> Ai {
Ai {
id: id.clone(),
state: GameState::new(map_size, id),
pathfinder: Pathfinder::new(map_size),
}
}
pub fn apply_event... | Ai | identifier_name |
ai.rs | // See LICENSE file for copyright and license details.
use common::types::{Size2, ZInt, PlayerId, MapPos};
use game_state::{GameState};
use map::{distance};
use pathfinder::{MapPath, Pathfinder};
use dir::{Dir};
use unit::{Unit};
use db::{Db};
use core::{CoreEvent, Command, MoveMode, los};
pub struct Ai {
id: Pla... |
}
// vim: set tabstop=4 shiftwidth=4 softtabstop=4 expandtab:
| {
if let Some(cmd) = self.try_get_move_command(db) {
cmd
} else if let Some(cmd) = self.try_get_attack_command(db) {
cmd
} else {
Command::EndTurn
}
} | identifier_body |
main.rs | mod tokenizer;
mod executor;
use tokenizer::*;
use executor::{execute, Numeric};
use std::collections::HashMap;
use std::io::prelude::*;
use std::io;
fn main() {
// contain all program variables
let mut variables: HashMap<String, executor::Numeric> = HashMap::new();
// string to execute
let mut buffer ... | // split string to tokens
let data = tokenizer::tokenize(buffer.trim());
// execute operation (check by exit flag)
if execute(&mut variables, &data) {
break;
}
// clean string
buffer.clear();
}
} | .expect( "[error] Can't read line from stdin!" );
// ignore null strings
if buffer.trim().len() == 0 {
continue;
} | random_line_split |
main.rs | mod tokenizer;
mod executor;
use tokenizer::*;
use executor::{execute, Numeric};
use std::collections::HashMap;
use std::io::prelude::*;
use std::io;
fn | () {
// contain all program variables
let mut variables: HashMap<String, executor::Numeric> = HashMap::new();
// string to execute
let mut buffer = String::new();
loop {
print!(">> ");
io::stdout().flush()
.ok()
.expect( "[error] Can't flush to stdout!" );
... | main | identifier_name |
main.rs | mod tokenizer;
mod executor;
use tokenizer::*;
use executor::{execute, Numeric};
use std::collections::HashMap;
use std::io::prelude::*;
use std::io;
fn main() | {
// contain all program variables
let mut variables: HashMap<String, executor::Numeric> = HashMap::new();
// string to execute
let mut buffer = String::new();
loop {
print!(">> ");
io::stdout().flush()
.ok()
.expect( "[error] Can't flush to stdout!" );
... | identifier_body | |
main.rs | mod tokenizer;
mod executor;
use tokenizer::*;
use executor::{execute, Numeric};
use std::collections::HashMap;
use std::io::prelude::*;
use std::io;
fn main() {
// contain all program variables
let mut variables: HashMap<String, executor::Numeric> = HashMap::new();
// string to execute
let mut buffer ... |
// clean string
buffer.clear();
}
}
| {
break;
} | conditional_block |
templates.py | ## This file is part of Invenio.
## Copyright (C) 2009, 2010, 2011 CERN.
##
## Invenio is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (at your option) any later versio... | (DefaultTemplate):
""" HTML generators for BibCatalog """
SHOW_MAX_TICKETS = 25
def tmpl_your_tickets(self, uid, ln=CFG_SITE_LANG, start=1):
""" make a pretty html body of tickets that belong to the user given as param """
ln = wash_language(ln)
_ = gettext_set_language(ln)
... | Template | identifier_name |
templates.py | ## This file is part of Invenio.
## Copyright (C) 2009, 2010, 2011 CERN.
##
## Invenio is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (at your option) any later versio... |
#errors? tell what happened and get out
bibcat_probs = bibcatalog_system.check_system(uid)
if bibcat_probs:
return _("Error")+" "+bibcat_probs
tickets = bibcatalog_system.ticket_search(uid, owner=uid) #get ticket id's
lines = "" #put result here
i = 1
... | return _("Error: No BibCatalog system configured.") | conditional_block |
templates.py | ## This file is part of Invenio.
## Copyright (C) 2009, 2010, 2011 CERN.
##
## Invenio is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (at your option) any later versio... | """ make a pretty html body of tickets that belong to the user given as param """
ln = wash_language(ln)
_ = gettext_set_language(ln)
if bibcatalog_system is None:
return _("Error: No BibCatalog system configured.")
#errors? tell what happened and get out
bibcat_probs... | identifier_body | |
templates.py | ## This file is part of Invenio. | ## published by the Free Software Foundation; either version 2 of the
## License, or (at your option) any later version.
##
## Invenio is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU... | ## Copyright (C) 2009, 2010, 2011 CERN.
##
## Invenio is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as | random_line_split |
needless_borrow.rs | // run-rustfix | *y
}
#[warn(clippy::all, clippy::needless_borrow)]
#[allow(unused_variables)]
fn main() {
let a = 5;
let b = x(&a);
let c = x(&&a);
let s = &String::from("hi");
let s_ident = f(&s); // should not error, because `&String` implements Copy, but `String` does not
let g_val = g(&Vec::new()); // ... |
#![allow(clippy::needless_borrowed_reference)]
fn x(y: &i32) -> i32 { | random_line_split |
needless_borrow.rs | // run-rustfix
#![allow(clippy::needless_borrowed_reference)]
fn x(y: &i32) -> i32 {
*y
}
#[warn(clippy::all, clippy::needless_borrow)]
#[allow(unused_variables)]
fn main() {
let a = 5;
let b = x(&a);
let c = x(&&a);
let s = &String::from("hi");
let s_ident = f(&s); // should not error, becau... | (y: &[u8]) -> u8 {
y[0]
}
trait Trait {}
impl<'a> Trait for &'a str {}
fn h(_: &dyn Trait) {}
| g | identifier_name |
needless_borrow.rs | // run-rustfix
#![allow(clippy::needless_borrowed_reference)]
fn x(y: &i32) -> i32 {
*y
}
#[warn(clippy::all, clippy::needless_borrow)]
#[allow(unused_variables)]
fn main() |
fn f<T: Copy>(y: &T) -> T {
*y
}
fn g(y: &[u8]) -> u8 {
y[0]
}
trait Trait {}
impl<'a> Trait for &'a str {}
fn h(_: &dyn Trait) {}
| {
let a = 5;
let b = x(&a);
let c = x(&&a);
let s = &String::from("hi");
let s_ident = f(&s); // should not error, because `&String` implements Copy, but `String` does not
let g_val = g(&Vec::new()); // should not error, because `&Vec<T>` derefs to `&[T]`
let vec = Vec::new();
let vec_va... | identifier_body |
create_midpoint.js | import * as Constants from '../constants';
export default function(parent, startVertex, endVertex) {
const startCoord = startVertex.geometry.coordinates;
const endCoord = endVertex.geometry.coordinates;
// If a coordinate exceeds the projection, we can't calculate a midpoint,
// so run away
if (startCoord[1... |
const mid = {
lng: (startCoord[0] + endCoord[0]) / 2,
lat: (startCoord[1] + endCoord[1]) / 2
};
return {
type: Constants.geojsonTypes.FEATURE,
properties: {
meta: Constants.meta.MIDPOINT,
parent,
lng: mid.lng,
lat: mid.lat,
coord_path: endVertex.properties.coord_pa... | {
return null;
} | conditional_block |
create_midpoint.js | import * as Constants from '../constants';
export default function(parent, startVertex, endVertex) {
const startCoord = startVertex.geometry.coordinates;
const endCoord = endVertex.geometry.coordinates;
// If a coordinate exceeds the projection, we can't calculate a midpoint,
// so run away
if (startCoord[1... | lng: (startCoord[0] + endCoord[0]) / 2,
lat: (startCoord[1] + endCoord[1]) / 2
};
return {
type: Constants.geojsonTypes.FEATURE,
properties: {
meta: Constants.meta.MIDPOINT,
parent,
lng: mid.lng,
lat: mid.lat,
coord_path: endVertex.properties.coord_path
},
geom... | }
const mid = { | random_line_split |
emf_export.py | # Copyright (C) 2009 Jeremy S. Sanders
# Email: Jeremy Sanders <jeremy@jeremysanders.net>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# ... | (self, path):
"""Draw a path on the output."""
# print "path"
self._createPath(path)
self.emf.StrokeAndFillPath()
def drawTextItem(self, pt, textitem):
"""Convert text to a path and draw it.
"""
# print "text", pt, textitem.text()
path = qt4.QPainter... | drawPath | identifier_name |
emf_export.py | # Copyright (C) 2009 Jeremy S. Sanders
# Email: Jeremy Sanders <jeremy@jeremysanders.net>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# ... |
self.emf.SelectClipPath(mode=clipmode)
def _updateTransform(self, m):
"""Update transformation."""
self.emf.SetWorldTransform(m.m11(), m.m12(),
m.m21(), m.m22(),
m.dx()*scale, m.dy()*scale)
def updateState(self, sta... | self.emf.LineTo(0, h)
self.emf.CloseFigure()
self.emf.EndPath()
clipmode = pyemf.RGN_COPY | random_line_split |
emf_export.py | # Copyright (C) 2009 Jeremy S. Sanders
# Email: Jeremy Sanders <jeremy@jeremysanders.net>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# ... |
elif m == qt4.QPaintDevice.PdmDpiX:
return int(self.engine.dpi)
elif m == qt4.QPaintDevice.PdmDpiY:
return int(self.engine.dpi)
elif m == qt4.QPaintDevice.PdmPhysicalDpiX:
return int(self.engine.dpi)
elif m == qt4.QPaintDevice.PdmPhysicalDpiY:
... | return 24 | conditional_block |
emf_export.py | # Copyright (C) 2009 Jeremy S. Sanders
# Email: Jeremy Sanders <jeremy@jeremysanders.net>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# ... |
def sizeExtra(self):
return struct.calcsize("i")*len(self.styleentries)
def serializeExtra(self, fh):
self.serializeList(fh, "i", self.styleentries)
def hasHandle(self):
return True
class EMFPaintEngine(qt4.QPaintEngine):
"""Custom EMF paint engine."""
def __init__(self... | """Create pen.
styleentries is a list of dash and space lengths."""
pyemf._EMR._EXTCREATEPEN.__init__(self)
self.style = style
self.penwidth = width
self.color = pyemf._normalizeColor(color)
self.brushstyle = 0x0 # solid
if style & pyemf.PS_USERSTYLE == 0:
... | identifier_body |
rdflib-example.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2018 David Arroyo Menéndez
# Author: David Arroyo Menéndez <davidam@gnu.org>
# Maintainer: David Arroyo Menéndez <davidam@gnu.org>
# This file is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License ... | # the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA,
import rdflib
g=rdflib.Graph()
g.load('http://dbpedia.org/resource/Semantic_Web')
for s,p,o in g:
print(s,p,o) | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with GNU Emacs; see the file COPYING. If not, write to | random_line_split |
rdflib-example.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2018 David Arroyo Menéndez
# Author: David Arroyo Menéndez <davidam@gnu.org>
# Maintainer: David Arroyo Menéndez <davidam@gnu.org>
# This file is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License ... | nt(s,p,o)
| conditional_block | |
token_tests.js | Tinytest.add("blaze-tools - token parsers", function (test) {
| var result = func(scanner);
if (expected === null) {
test.equal(scanner.pos, 1);
test.equal(result, null);
} else {
test.isTrue(scanner.isEOF());
test.equal(result, expected);
}
};
var runValue = function (func, input, expectedValue) {
var expected;
if (expectedValue... | var run = function (func, input, expected) {
var scanner = new HTMLTools.Scanner('z' + input);
// make sure the parse function respects `scanner.pos`
scanner.pos = 1; | random_line_split |
panda-12b.py | import dragonfly
import dragonfly.pandahive
import bee
from bee import connect
import math, functools
from panda3d.core import NodePath
import dragonfly.scene.unbound, dragonfly.scene.bound
import dragonfly.std
import dragonfly.io
import dragonfly.canvas
import Spyder
# ## random matrix generator
from random impor... |
main = myhive().getinstance()
main.build("main")
main.place()
main.close()
main.init()
main.run()
| pandaclassname = "pandaclass"
pandaclassname_ = bee.attribute("pandaclassname")
canvas = dragonfly.pandahive.pandacanvas()
mousearea = dragonfly.canvas.mousearea()
raiser = bee.raiser()
connect("evexc", raiser)
camerabind = camerabind().worker()
camcenter = dragonfly.std.variable("id")("ca... | identifier_body |
panda-12b.py | import dragonfly
import dragonfly.pandahive
import bee
from bee import connect
import math, functools
from panda3d.core import NodePath
import dragonfly.scene.unbound, dragonfly.scene.bound
import dragonfly.std
import dragonfly.io
import dragonfly.canvas
import Spyder
# ## random matrix generator
from random impor... | connect(startsensor, ip1.start)
connect(ip1.reach_end, ip1.stop)
connect(ip1.reach_end, ip2.start)
connect(ip2.reach_end, ip2.stop)
connect(ip2.reach_end, ip1.start)
connect(ip2.reach_end, interval.start)
sethpr = dragonfly.scene.bound.setHpr()
connect(ip1, sethpr)
connect(ip2, se... | random_line_split | |
panda-12b.py | import dragonfly
import dragonfly.pandahive
import bee
from bee import connect
import math, functools
from panda3d.core import NodePath
import dragonfly.scene.unbound, dragonfly.scene.bound
import dragonfly.std
import dragonfly.io
import dragonfly.canvas
import Spyder
# ## random matrix generator
from random impor... |
def id_generator():
n = 0
while 1:
n += 1
yield "spawnedpanda" + str(n)
from dragonfly.canvas import box2d
from bee.mstr import mstr
class parameters: pass
class myscene(dragonfly.pandahive.spyderframe):
a = Spyder.AxisSystem()
a *= 0.25
a.origin += (-8, 42, 0)
env = Spy... | a = Spyder.AxisSystem()
a.rotateZ(360 * random())
a.origin = Spyder.Coordinate(15 * random() - 7.5, 15 * random() - 7.5, 0)
yield dragonfly.scene.matrix(a, "AxisSystem") | conditional_block |
panda-12b.py | import dragonfly
import dragonfly.pandahive
import bee
from bee import connect
import math, functools
from panda3d.core import NodePath
import dragonfly.scene.unbound, dragonfly.scene.bound
import dragonfly.std
import dragonfly.io
import dragonfly.canvas
import Spyder
# ## random matrix generator
from random impor... | (bee.inithive):
animation = dragonfly.scene.bound.animation()
walk = dragonfly.std.variable("str")("walk")
connect(walk, animation.animation_name)
key_w = dragonfly.io.keyboardsensor_trigger("W")
connect(key_w, animation.loop)
key_s = dragonfly.io.keyboardsensor_trigger("S")
connect(key_s, ... | pandawalkhive | identifier_name |
cache.py | # Copyright (c) 2014 Alexander Bredo
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the
# following conditions are met:
#
# 1. Redistributions of source code must retain the above
# copyright notice, this list of conditions ... | (self):
return len(self.cache)
def getItemsOutOfTTL(self):
IndexedTimeCache.lock.acquire()
cache_outofdate = dict()
cache_new = dict()
for k,v in self.cache.items():
if v['timestamp'] < (time.time() - self.ttl):
cache_outofdate[k] = v
else:
cache_new[k] = v
self.cache = cache_new # Update... | size | identifier_name |
cache.py | # Copyright (c) 2014 Alexander Bredo
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the
# following conditions are met:
#
# 1. Redistributions of source code must retain the above
# copyright notice, this list of conditions ... |
def insert(self, index, data, ignore_fields=[]):
IndexedTimeCache.lock.acquire()
if index in self.cache: # UPDATE + AGGREGATE
self.cache[index]['data'] = self.__aggregate(self.cache[index]['data'], data, ignore_fields)
else: # NEW
self.cache[index] = {
'timestamp': int(time.time()), # Insert... | self.cache = dict()
self.ttl = ttl | identifier_body |
cache.py | # Copyright (c) 2014 Alexander Bredo
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the
# following conditions are met:
#
# 1. Redistributions of source code must retain the above
# copyright notice, this list of conditions ... | def __aggregate(self, old, new, ignore_fields):
aggregated = old
for key, value in new.items():
if isinstance(value, dict):
for sub_key, sub_value in value.items():
if key in aggregated and (key not in ignore_fields or sub_key not in ignore_fields):
if sub_key in aggregated[key]:
aggregate... | #print(cache_new)
return [item['data'] for item in cache_outofdate.values()]
# cache_outofdate: dict_values([{'data': {'b': 1, 'a': 2, 'c': 4}, 'timestamp': 1403523219}, {...} ])
# Return: [{'c': 2, 'b': 23, 'a': 25}, {'c': 2, 'b': 32, 'a': 29}, ...
| random_line_split |
cache.py | # Copyright (c) 2014 Alexander Bredo
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the
# following conditions are met:
#
# 1. Redistributions of source code must retain the above
# copyright notice, this list of conditions ... |
else:
print("ERROR: Stats-Aggregation. Fields not found")
#aggregated[key][sub_key] = dict()
#aggregated[key][sub_key] = sub_value
else:
aggregated[key] = dict() #copy?
print("ERROR: Stats-Aggregation. Fields not found")
elif key not in ignore_fields:
aggregated[key] ... | aggregated[key][sub_key] += sub_value | conditional_block |
medical_tags.py | from datetime import timedelta
from django import template
import ws.utils.dates as date_utils
import ws.utils.perms as perm_utils
from ws import forms
from ws.utils.itinerary import get_cars
register = template.Library()
@register.inclusion_tag('for_templatetags/show_wimp.html')
def show_wimp(wimp):
return {
... |
info_form = forms.TripInfoForm(instance=trip.info)
info_form.fields.pop('drivers')
info_form.fields.pop('accurate')
return {'info_form': info_form}
@register.inclusion_tag('for_templatetags/trip_info.html', takes_context=True)
def trip_info(context, trip, show_participants_if_no_itinerary=False):
... | return {'info_form': None} | conditional_block |
medical_tags.py | from datetime import timedelta
from django import template
import ws.utils.dates as date_utils
import ws.utils.perms as perm_utils
from ws import forms
from ws.utils.itinerary import get_cars
register = template.Library()
@register.inclusion_tag('for_templatetags/show_wimp.html')
def show_wimp(wimp):
return {
... | 'participants': (
trip.signed_up_participants.filter(signup__on_trip=True).select_related(
'emergency_info__emergency_contact'
)
),
'trip_leaders': (
trip.leaders.select_related('emergency_info__emergency_contact')
),
'cars': ge... |
return {
'trip': trip, | random_line_split |
medical_tags.py | from datetime import timedelta
from django import template
import ws.utils.dates as date_utils
import ws.utils.perms as perm_utils
from ws import forms
from ws.utils.itinerary import get_cars
register = template.Library()
@register.inclusion_tag('for_templatetags/show_wimp.html')
def show_wimp(wimp):
return {
... | participant = context['viewing_participant']
# After a sufficiently long waiting period, hide medical information
# (We could need medical info a day or two after a trip was due back)
# Some trips last for multiple days (trip date is Friday, return is Sunday)
# Because we only record a single trip date... | identifier_body | |
medical_tags.py | from datetime import timedelta
from django import template
import ws.utils.dates as date_utils
import ws.utils.perms as perm_utils
from ws import forms
from ws.utils.itinerary import get_cars
register = template.Library()
@register.inclusion_tag('for_templatetags/show_wimp.html')
def | (wimp):
return {
'participant': wimp,
}
@register.inclusion_tag('for_templatetags/trip_itinerary.html')
def trip_itinerary(trip):
"""Return a stripped form for read-only display.
Drivers will be displayed separately, and the 'accuracy' checkbox
isn't needed for display.
"""
if not... | show_wimp | identifier_name |
mocks.py | """ test """
import logging
import os
import tempfile
import sys
import random
from bzt.engine import Engine, Configuration, FileLister | from bzt.utils import load_class
from bzt.engine import Provisioning, ScenarioExecutor, Reporter, AggregatorListener
from bzt.modules.aggregator import ResultsReader
from tests import random_sample
try:
from exceptions import KeyboardInterrupt
except ImportError:
from builtins import KeyboardInterrupt
class ... | random_line_split | |
mocks.py | """ test """
import logging
import os
import tempfile
import sys
import random
from bzt.engine import Engine, Configuration, FileLister
from bzt.utils import load_class
from bzt.engine import Provisioning, ScenarioExecutor, Reporter, AggregatorListener
from bzt.modules.aggregator import ResultsReader
from tests import... |
class ResultChecker(AggregatorListener):
def __init__(self, callback):
super(ResultChecker, self).__init__()
self.callback = callback
def aggregated_second(self, data):
self.callback(data)
| pass | identifier_body |
mocks.py | """ test """
import logging
import os
import tempfile
import sys
import random
from bzt.engine import Engine, Configuration, FileLister
from bzt.utils import load_class
from bzt.engine import Provisioning, ScenarioExecutor, Reporter, AggregatorListener
from bzt.modules.aggregator import ResultsReader
from tests import... | (self, param):
"""
:type param: str
:return:
"""
name = self.settings.get(param, "")
if name:
cls = load_class(name)
return cls()
return None
def resource_files(self):
"""
:return:
"""
return [__file__... | get_exc | identifier_name |
mocks.py | """ test """
import logging
import os
import tempfile
import sys
import random
from bzt.engine import Engine, Configuration, FileLister
from bzt.utils import load_class
from bzt.engine import Provisioning, ScenarioExecutor, Reporter, AggregatorListener
from bzt.modules.aggregator import ResultsReader
from tests import... |
def startup(self):
"""
:raise self.startup_exc:
"""
self.log.info("Startup mock")
self.was_startup = True
if self.startup_exc:
raise self.startup_exc
def check(self):
"""
:return: :raise self.check_exc:
"""
self.was_c... | raise self.prepare_exc | conditional_block |
graph.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | assert!(counter < expected_incoming.len());
debug!("counter=%? expected=%? edge_index=%? edge=%?",
counter, expected_incoming[counter], edge_index, edge);
match expected_incoming[counter] {
(ref e, ref n) => {
assert_eq!(e, &edge... | do graph.each_incoming_edge(start_index) |edge_index, edge| {
assert_eq!(graph.edge_data(edge_index), &edge.data); | random_line_split |
graph.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&self) -> NodeIndex {
self.source
}
pub fn target(&self) -> NodeIndex {
self.target
}
}
#[cfg(test)]
mod test {
use middle::graph::*;
type TestNode = Node<&'static str>;
type TestEdge = Edge<&'static str>;
type TestGraph = Graph<&'static str, &'static str>;
fn create... | source | identifier_name |
graph.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub fn edge_data<'a>(&'a self, idx: EdgeIndex) -> &'a E {
&self.edges[*idx].data
}
pub fn edge<'a>(&'a self, idx: EdgeIndex) -> &'a Edge<E> {
&self.edges[*idx]
}
pub fn first_adjacent(&self, node: NodeIndex, dir: Direction) -> EdgeIndex {
//! Accesses the index of the fir... | {
&mut self.edges[*idx].data
} | identifier_body |
search.py | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from json import loads
from datetime import datetime
from functools import partial
from django.db.models import Q
from django.contrib.gis.measure import Distance
from django.contrib.g... |
else:
q = FilterContext()
if instance:
q = q & FilterContext(instance=instance)
return q
def _parse_filter(query, mapping):
if type(query) is dict:
return _parse_predicate(query, mapping)
elif type(query) is list:
predicates = [_parse_filter(p, mapping) for p in ... | query = loads(filterstr)
q = _parse_filter(query, mapping) | conditional_block |
search.py | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from json import loads
from datetime import datetime
from functools import partial
from django.db.models import Q
from django.contrib.gis.measure import Distance
from django.contrib.g... |
# a predicate_builder takes a value for the
# corresponding predicate type and returns
# a singleton dictionary with a mapping of
# predicate kwargs to pass to a Q object
PREDICATE_TYPES = {
'MIN': {
'combines_with': {'MAX'},
'predicate_builder': _parse_min_max_value_fn('__gt'),
},
'MAX': ... | """
django_hstore builds different sql for the __contains predicate
depending on whether the input value is a list or a single item
so this works for both 'IN' and 'IS'
"""
return {'__contains': {field: val}} | identifier_body |
search.py | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from json import loads
from datetime import datetime
from functools import partial
from django.db.models import Q
from django.contrib.gis.measure import Distance
from django.contrib.g... | (self, *args, **kwargs):
if 'basekey' in kwargs:
self.basekeys = {kwargs['basekey']}
del kwargs['basekey']
else:
self.basekeys = set()
super(FilterContext, self).__init__(*args, **kwargs)
# TODO: Nothing uses add, is it necessary?
def add(self, thin... | __init__ | identifier_name |
search.py | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from json import loads
from datetime import datetime
from functools import partial
from django.db.models import Q
from django.contrib.gis.measure import Distance
from django.contrib.g... | 'predicate_builder': _simple_pred('__isnull')
},
'WITHIN_RADIUS': {
'combines_with': set(),
'predicate_builder': _parse_within_radius_value,
},
'IN_BOUNDARY': {
'combines_with': set(),
'predicate_builder': _parse_in_boundary
}
}
HSTORE_PREDICATE_TYPES = {
... | 'predicate_builder': _simple_pred('__icontains')
},
'ISNULL': {
'combines_with': set(), | random_line_split |
TheFlatDictionary.py | def flatten(dictionary):
stack = [((), dictionary)]
result = {}
while stack:
path, current = stack.pop()
for k, v in current.items():
if isinstance(v, dict) and bool(v):
stack.append((path + (k,), v))
else:
whatadd = ""... | assert flatten({"key": "value"}) == {"key": "value"}, "Simple"
assert flatten(
{"key": {"deeper": {"more": {"enough": "value"}}}}
) == {"key/deeper/more/enough": "value"}, "Nested"
assert flatten({"empty": {}}) == {"empty": ""}, "Empty value"
assert flatten({"name": {
"fi... | conditional_block | |
TheFlatDictionary.py | def flatten(dictionary):
|
if __name__ == '__main__':
assert flatten({"key": "value"}) == {"key": "value"}, "Simple"
assert flatten(
{"key": {"deeper": {"more": {"enough": "value"}}}}
) == {"key/deeper/more/enough": "value"}, "Nested"
assert flatten({"empty": {}}) == {"empty": ""}, "Empty value"
assert fla... | stack = [((), dictionary)]
result = {}
while stack:
path, current = stack.pop()
for k, v in current.items():
if isinstance(v, dict) and bool(v):
stack.append((path + (k,), v))
else:
whatadd = "" if isinstance (v, dict) else... | identifier_body |
TheFlatDictionary.py | def flatten(dictionary):
stack = [((), dictionary)]
result = {}
while stack:
path, current = stack.pop()
for k, v in current.items():
if isinstance(v, dict) and bool(v):
stack.append((path + (k,), v))
else:
whatadd = ""... | "job": "scout",
"recent": "",
"additional/place/zone": "1",
"additional/place/cell": "2"} | random_line_split | |
TheFlatDictionary.py | def | (dictionary):
stack = [((), dictionary)]
result = {}
while stack:
path, current = stack.pop()
for k, v in current.items():
if isinstance(v, dict) and bool(v):
stack.append((path + (k,), v))
else:
whatadd = "" if isinsta... | flatten | identifier_name |
addrable-core.js | //////////////////////////////////////////////////////////
// Addrable core
//
// Michael Hausenblas, 2011.
//
// -------------------------------------------------------
// Includes code from jQuery JavaScript Library v1.5
// http://jquery.com/
//
// Copyright 2011, John Resig
// Dual licensed under the MIT or GPL... |
}
else return null; // signal process failed
},
/*
Indirect selection - produces a simple string representation of selected dimensions.
listDimensions('{'city': 'Galway', 'date' : '2011-03-03'}) -> 'city=Galway date=2011-03-03'
*/
listDimensions : function(seldimensions){
var b = "";
for (sdim in s... | {
if(addrablecase === ADDRABLE_SELECTOR_ROW) { // row selection case
return rowprocfun(data, selval, outp);
}
else {
if(addrablecase === ADDRABLE_SELECTOR_WHERE) { // indirect selection case
return whereprocfun(data, selval, outp);
}
}
} | conditional_block |
addrable-core.js | //////////////////////////////////////////////////////////
// Addrable core
//
// Michael Hausenblas, 2011.
//
// -------------------------------------------------------
// Includes code from jQuery JavaScript Library v1.5
// http://jquery.com/
//
// Copyright 2011, John Resig
// Dual licensed under the MIT or GPL... |
F.prototype = Addrable;
return new F();
}
//////////////////////////////////////////////////////////
// For client-side usage in a browser. Make sure to
// include both addrable-core.js and addrable-client.js.
//
// Addrable.init();
// Addrable.render(tableuri, "#someelement");
var Addrable = {
/*
I... | {} | identifier_body |
addrable-core.js | //////////////////////////////////////////////////////////
// Addrable core
//
// Michael Hausenblas, 2011.
//
// -------------------------------------------------------
// Includes code from jQuery JavaScript Library v1.5
// http://jquery.com/
//
// Copyright 2011, John Resig
// Dual licensed under the MIT or GPL... | () {}
F.prototype = Addrable;
return new F();
}
//////////////////////////////////////////////////////////
// For client-side usage in a browser. Make sure to
// include both addrable-core.js and addrable-client.js.
//
// Addrable.init();
// Addrable.render(tableuri, "#someelement");
var Addrable = {
/*... | F | identifier_name |
addrable-core.js | //////////////////////////////////////////////////////////
// Addrable core
//
// Michael Hausenblas, 2011.
//
// -------------------------------------------------------
// Includes code from jQuery JavaScript Library v1.5
// http://jquery.com/
//
// Copyright 2011, John Resig
// Dual licensed under the MIT or GPL... | var ADDRABLE_DEBUG = false; // debug messages flag
//////////////////////////////////////////////////////////
// For server-side usage with node.js.
//
// var addrable = require('./addrable-server');
// var adb = addrable.createAddrable();
// adb.init();
this.createAddrable = function() {
function F() {}
... | random_line_split | |
package.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class RDoparallel(RPackage):
"""Provides a parallel backend for the %dopar% function using the p... |
homepage = "https://cloud.r-project.org/package=doParallel"
url = "https://cloud.r-project.org/src/contrib/doParallel_1.0.10.tar.gz"
list_url = "https://cloud.r-project.org/src/contrib/Archive/doParallel"
version('1.0.15', sha256='71ad7ea69616468996aefdd8d02a4a234759a21ddde9ed1657e3c537145cd86e')... | random_line_split | |
package.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class | (RPackage):
"""Provides a parallel backend for the %dopar% function using the parallel
package."""
homepage = "https://cloud.r-project.org/package=doParallel"
url = "https://cloud.r-project.org/src/contrib/doParallel_1.0.10.tar.gz"
list_url = "https://cloud.r-project.org/src/contrib/Archive/do... | RDoparallel | identifier_name |
package.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class RDoparallel(RPackage):
| """Provides a parallel backend for the %dopar% function using the parallel
package."""
homepage = "https://cloud.r-project.org/package=doParallel"
url = "https://cloud.r-project.org/src/contrib/doParallel_1.0.10.tar.gz"
list_url = "https://cloud.r-project.org/src/contrib/Archive/doParallel"
v... | identifier_body | |
telemetryIpc.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | eventName: string;
data?: any;
}
export class TelemetryAppenderChannel implements IServerChannel {
constructor(private appender: ITelemetryAppender) { }
listen<T>(_: unknown, event: string): Event<T> {
throw new Error(`Event not found: ${event}`);
}
call(_: unknown, command: string, { eventName, data }: ITe... | import { ITelemetryAppender } from 'vs/platform/telemetry/common/telemetryUtils';
import { Event } from 'vs/base/common/event';
export interface ITelemetryLog { | random_line_split |
telemetryIpc.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (private appender: ITelemetryAppender) { }
listen<T>(_: unknown, event: string): Event<T> {
throw new Error(`Event not found: ${event}`);
}
call(_: unknown, command: string, { eventName, data }: ITelemetryLog): Promise<any> {
this.appender.log(eventName, data);
return Promise.resolve(null);
}
}
export clas... | constructor | identifier_name |
Tooltip.js | define([
"dojo/_base/array", // array.forEach array.indexOf array.map
"dojo/_base/declare", // declare
"dojo/_base/fx", // fx.fadeIn fx.fadeOut
"dojo/dom", // dom.byId
"dojo/dom-class", // domClass.add
"dojo/dom-geometry", // domGeometry.position
"dojo/dom-style", // domStyle.set, domStyle.get
"dojo/_base/lang"... | var Tooltip = declare("dijit.Tooltip", _Widget, {
// summary:
// Pops up a tooltip (a help message) when you hover over a node.
// Also provides static show() and hide() methods that can be used without instantiating a dijit/Tooltip.
// label: String
// HTML to display in the tooltip.
// Specified as ... | random_line_split | |
Tooltip.js | define([
"dojo/_base/array", // array.forEach array.indexOf array.map
"dojo/_base/declare", // declare
"dojo/_base/fx", // fx.fadeIn fx.fadeOut
"dojo/dom", // dom.byId
"dojo/dom-class", // domClass.add
"dojo/dom-geometry", // domGeometry.position
"dojo/dom-style", // domStyle.set, domStyle.get
"dojo/_base/lang"... |
var Tooltip = declare("dijit.Tooltip", _Widget, {
// summary:
// Pops up a tooltip (a help message) when you hover over a node.
// Also provides static show() and hide() methods that can be used without instantiating a dijit/Tooltip.
// label: String
// HTML to display in the tooltip.
// Specified a... | {} | identifier_body |
Tooltip.js | define([
"dojo/_base/array", // array.forEach array.indexOf array.map
"dojo/_base/declare", // declare
"dojo/_base/fx", // fx.fadeIn fx.fadeOut
"dojo/dom", // dom.byId
"dojo/dom-class", // domClass.add
"dojo/dom-geometry", // domGeometry.position
"dojo/dom-style", // domStyle.set, domStyle.get
"dojo/_base/lang"... | (){}
var Tooltip = declare("dijit.Tooltip", _Widget, {
// summary:
// Pops up a tooltip (a help message) when you hover over a node.
// Also provides static show() and hide() methods that can be used without instantiating a dijit/Tooltip.
// label: String
// HTML to display in the tooltip.
// Specifi... | noop | identifier_name |
Tooltip.js | define([
"dojo/_base/array", // array.forEach array.indexOf array.map
"dojo/_base/declare", // declare
"dojo/_base/fx", // fx.fadeIn fx.fadeOut
"dojo/dom", // dom.byId
"dojo/dom-class", // domClass.add
"dojo/dom-geometry", // domGeometry.position
"dojo/dom-style", // domStyle.set, domStyle.get
"dojo/_base/lang"... |
return Math.max(0, size.w - widthAvailable);
},
_onShow: function(){
// summary:
// Called at end of fade-in operation
// tags:
// protected
if(has("ie")){
// the arrow won't show up on a node w/an opacity filter
this.domNode.style.filter="";
}
},
hide: function(aroundNode){
... | {
// reset the tooltip back to the defaults
this.connectorNode.style.top = "";
this.connectorNode.style.bottom = "";
} | conditional_block |
User.ts | import {
InferAttributes,
BelongsTo,
BelongsToCreateAssociationMixin,
BelongsToGetAssociationMixin,
BelongsToSetAssociationMixin,
InferCreationAttributes,
CreationOptional,
DataTypes,
FindOptions,
Model,
ModelStatic,
Op
} from '@sequelize/core';
import { sequelize } from '../connection';
type N... | () {
return {};
}
},
indexes: [{
fields: ['firstName'],
using: 'BTREE',
name: 'firstNameIdx',
concurrently: true
}],
sequelize
}
);
User.afterSync(() => {
sequelize.getQueryInterface().addIndex(User.tableName, {
fields: ['lastName'],
using: 'BTREE',
... | custom2 | identifier_name |
User.ts | import {
InferAttributes,
BelongsTo,
BelongsToCreateAssociationMixin,
BelongsToGetAssociationMixin,
BelongsToSetAssociationMixin,
InferCreationAttributes,
CreationOptional,
DataTypes,
FindOptions,
Model,
ModelStatic,
Op
} from '@sequelize/core';
import { sequelize } from '../connection';
type N... |
// Model#addScope
User.addScope('withoutFirstName', {
where: {
firstName: {
[Op.is]: null
}
}
});
User.addScope(
'withFirstName',
(firstName: string) => ({
where: { firstName }
})
);
// associate
// it is important to import _after_ the model above is already exported so the circular refe... | }); | random_line_split |
app.js | var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express(... | });
/// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// produ... | err.status = 404;
next(err); | random_line_split |
app.js | var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express(... |
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
| {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
} | conditional_block |
sinumber.py | """
Functions for converting numbers with SI units to integers
"""
import copy
import re
si_multipliers = {
None: 1,
'': 1,
'k': 1000 ** 1,
'm': 1000 ** 2,
'g': 1000 ** 3,
't': 1000 ** 4,
'p': 1000 ** 5,
'e': 1000 ** 6,
'z': 1000 ** 7,
'y': 1000 ** 8,
'ki': 1024 ** 1,
... |
if number > value:
return number_format.format(number / value) + unit.title()
# no matches, must be less than anything so just return number
return number_format.format(number / value)
def si_range(value, default_lower=0):
"""Convert a range of SI numbers to a range of integers.
... | continue | conditional_block |
sinumber.py | """
Functions for converting numbers with SI units to integers
"""
import copy
import re
si_multipliers = {
None: 1,
'': 1,
'k': 1000 ** 1,
'm': 1000 ** 2,
'g': 1000 ** 3,
't': 1000 ** 4,
'p': 1000 ** 5,
'e': 1000 ** 6,
'z': 1000 ** 7,
'y': 1000 ** 8,
'ki': 1024 ** 1,
... | try:
integer = si_as_number(value)
print value, integer
except ValueError:
print value, "-> ValueError"
print
print "Ranges:"
for value in [
15,
"16ki",
{"upper": 1000},
{"lower": 1000, "upper": 2000},
... | 3.1415
]: | random_line_split |
sinumber.py | """
Functions for converting numbers with SI units to integers
"""
import copy
import re
si_multipliers = {
None: 1,
'': 1,
'k': 1000 ** 1,
'm': 1000 ** 2,
'g': 1000 ** 3,
't': 1000 ** 4,
'p': 1000 ** 5,
'e': 1000 ** 6,
'z': 1000 ** 7,
'y': 1000 ** 8,
'ki': 1024 ** 1,
... | (text):
"""Convert a string containing an SI value to an integer or return an
integer if that is what was passed in."""
if type(text) == int:
return text
if type(text) not in [str, unicode]:
raise ValueError("Source value must be string or integer")
matches = si_regex.search(text.... | si_as_number | identifier_name |
sinumber.py | """
Functions for converting numbers with SI units to integers
"""
import copy
import re
si_multipliers = {
None: 1,
'': 1,
'k': 1000 ** 1,
'm': 1000 ** 2,
'g': 1000 ** 3,
't': 1000 ** 4,
'p': 1000 ** 5,
'e': 1000 ** 6,
'z': 1000 ** 7,
'y': 1000 ** 8,
'ki': 1024 ** 1,
... |
def number_as_si(number, places=2, base=10):
"""Convert a number to the largest possible SI
representation of that number"""
# Try to cast any input to a float to make
# division able to get some deci places
number = float(number)
if base not in [2, 10]:
raise ValueError("base must ... | """Convert a string containing an SI value to an integer or return an
integer if that is what was passed in."""
if type(text) == int:
return text
if type(text) not in [str, unicode]:
raise ValueError("Source value must be string or integer")
matches = si_regex.search(text.lower(), 0)
... | identifier_body |
codegen_private_exports.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/ | export {registerModuleFactory as ɵregisterModuleFactory} from './linker/ng_module_factory_registration';
export {anchorDef as ɵand, ArgumentType as ɵArgumentType, BindingFlags as ɵBindingFlags, createComponentFactory as ɵccf, createNgModuleFactory as ɵcmf, createRendererType2 as ɵcrt, DepFlags as ɵDepFlags, directiveDe... |
export {CodegenComponentFactoryResolver as ɵCodegenComponentFactoryResolver} from './linker/component_factory_resolver'; | random_line_split |
sabpn.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Copyright (c) 2011 Chris D. Lasher & Phillip Whisenhunt
#
# This software is released under the MIT License. Please see
# LICENSE.txt for details.
"""A program to detect Process Linkage Networks using
Simulated Annealing.
"""
import collections
import itertools
impo... |
else:
links_state_class = states.ArrayLinksState
if input_data.detailed_transitions:
logger.info("Recording extra information for each state.")
transitions_csvfile = convutils.make_csv_dict_writer(
input_data.transitions_outfile,
DETAILED_TRANSITIONS_FIEL... | logger.info("Disabling swap transitions.")
links_state_class = states.NoSwapArrayLinksState | conditional_block |
sabpn.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Copyright (c) 2011 Chris D. Lasher & Phillip Whisenhunt
#
# This software is released under the MIT License. Please see
# LICENSE.txt for details.
"""A program to detect Process Linkage Networks using
Simulated Annealing.
"""
import collections
import itertools
impo... | (argv=None):
cli_parser = bpn.cli.SaCli()
input_data = cli_parser.parse_args(argv)
logger.info("Constructing supporting data structures; this may "
"take a while...")
annotated_interactions = bpn.structures.AnnotatedInteractionsArray(
input_data.interactions_graph,
i... | main | identifier_name |
sabpn.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Copyright (c) 2011 Chris D. Lasher & Phillip Whisenhunt
#
# This software is released under the MIT License. Please see
# LICENSE.txt for details.
"""A program to detect Process Linkage Networks using
Simulated Annealing.
"""
import collections
import itertools
impo... |
if __name__ == '__main__':
main()
| cli_parser = bpn.cli.SaCli()
input_data = cli_parser.parse_args(argv)
logger.info("Constructing supporting data structures; this may "
"take a while...")
annotated_interactions = bpn.structures.AnnotatedInteractionsArray(
input_data.interactions_graph,
input_data.annotat... | identifier_body |
sabpn.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Copyright (c) 2011 Chris D. Lasher & Phillip Whisenhunt
#
# This software is released under the MIT License. Please see
# LICENSE.txt for details.
"""A program to detect Process Linkage Networks using
Simulated Annealing.
"""
import collections
import itertools
impo... | links_state_class = states.NoSwapArrayLinksState
else:
links_state_class = states.ArrayLinksState
if input_data.detailed_transitions:
logger.info("Recording extra information for each state.")
transitions_csvfile = convutils.make_csv_dict_writer(
input_data.transi... | parameters_state_class = states.PLNParametersState
if input_data.disable_swaps:
logger.info("Disabling swap transitions.") | random_line_split |
type_allocation_places.rs | #![allow(dead_code)]
use crate::config::MovableTypesHookOutput;
use crate::cpp_data::{CppItem, CppPath};
use crate::cpp_type::{CppPointerLikeTypeKind, CppType};
use crate::processor::ProcessorData;
use log::{info, trace};
use ritual_common::errors::Result;
use std::collections::HashMap;
#[derive(Default, Debug)]
stru... |
CppType::PointerLike { kind, target, .. } => {
check_type(
target,
*kind == CppPointerLikeTypeKind::Pointer,
data_map,
item_text,
);
}
_ => {}
}
}
const MAX_ITEMS: usize = 10;
/// Detects the preferred... | {
let good_path = path.deinstantiate();
if let Some(stats) = data_map.get_mut(&good_path) {
if is_behind_pointer {
if stats.pointer_encounters.len() < MAX_ITEMS {
stats.pointer_encounters.push(item_text.to_string());
... | conditional_block |
type_allocation_places.rs | #![allow(dead_code)]
use crate::config::MovableTypesHookOutput;
use crate::cpp_data::{CppItem, CppPath};
use crate::cpp_type::{CppPointerLikeTypeKind, CppType};
use crate::processor::ProcessorData;
use log::{info, trace};
use ritual_common::errors::Result;
use std::collections::HashMap;
#[derive(Default, Debug)]
stru... | (data_map: &HashMap<CppPath, TypeStats>) {
for (name, stats) in data_map {
trace!("type = {}; stats = {:?}", name.to_cpp_pseudo_code(), stats);
}
for (path, stats) in data_map {
let suggestion = if stats.virtual_functions.is_empty() {
if stats.pointer_encounters.is_empty() {
... | log_results | identifier_name |
type_allocation_places.rs | #![allow(dead_code)]
use crate::config::MovableTypesHookOutput;
use crate::cpp_data::{CppItem, CppPath};
use crate::cpp_type::{CppPointerLikeTypeKind, CppType};
use crate::processor::ProcessorData;
use log::{info, trace};
use ritual_common::errors::Result;
use std::collections::HashMap;
#[derive(Default, Debug)]
stru... | }
info!("* pointer_encounters ({}):", stats.pointer_encounters.len());
for item in &stats.pointer_encounters {
info!("* * {}", item);
}
info!(
"* non_pointer_encounters ({}):",
stats.non_pointer_encounters.len()
);
for item in &... | for item in &stats.virtual_functions {
info!("* * {}", item); | random_line_split |
type_allocation_places.rs | #![allow(dead_code)]
use crate::config::MovableTypesHookOutput;
use crate::cpp_data::{CppItem, CppPath};
use crate::cpp_type::{CppPointerLikeTypeKind, CppType};
use crate::processor::ProcessorData;
use log::{info, trace};
use ritual_common::errors::Result;
use std::collections::HashMap;
#[derive(Default, Debug)]
stru... |
const MAX_ITEMS: usize = 10;
/// Detects the preferred type allocation place for each type based on
/// API of all known methods. Doesn't actually change the data,
/// only suggests stack allocated types for manual configuration.
pub fn suggest_allocation_places(data: &mut ProcessorData<'_>) -> Result<()> {
let ... | {
match cpp_type {
CppType::Class(path) => {
let good_path = path.deinstantiate();
if let Some(stats) = data_map.get_mut(&good_path) {
if is_behind_pointer {
if stats.pointer_encounters.len() < MAX_ITEMS {
stats.pointer_enco... | identifier_body |
join_room_by_id_or_alias.rs | //! [POST /_matrix/client/r0/join/{roomIdOrAlias}](https://matrix.org/docs/spec/client_server/r0.6.0#post-matrix-client-r0-join-roomidoralias)
use ruma_api::ruma_api;
use ruma_identifiers::{RoomId, RoomIdOrAliasId};
use super::ThirdPartySigned;
ruma_api! {
metadata {
description: "Join a room using its I... | /// The room where the user should be invited.
#[ruma_api(path)]
pub room_id_or_alias: RoomIdOrAliasId,
/// The servers to attempt to join the room through. One of the servers
/// must be participating in the room.
#[ruma_api(query)]
#[serde(default)]
pub... | rate_limited: true,
requires_authentication: true,
}
request { | random_line_split |
binary_tree.py | from typing import List
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val: int = 0, left: "TreeNode" = None, right: "TreeNode" = None):
self.val = val
self.left = left
self.right = right
@classmethod
def | (cls, root: "TreeNode") -> str:
"""Encodes a tree to a single string."""
buffer = []
def _serialize(root: "TreeNode"):
if root is None:
buffer.append("#")
return
buffer.append(str(root.val))
_serialize(root.left)
_s... | serialize | identifier_name |
binary_tree.py | from typing import List
# Definition for a binary tree node.
class TreeNode:
|
if __name__ == "__main__":
tests = [
"#",
"1,#,#",
"1,2,#,#,#",
"1,#,2,#,#",
"1,2,#,#,3,#,#",
"1,2,#,#,3,4,5,#,#,#,#",
]
for t in tests:
actual = TreeNode.serialize(TreeNode.deserialize(t))
print("serialize(deserialize) ->", actual)
... | def __init__(self, val: int = 0, left: "TreeNode" = None, right: "TreeNode" = None):
self.val = val
self.left = left
self.right = right
@classmethod
def serialize(cls, root: "TreeNode") -> str:
"""Encodes a tree to a single string."""
buffer = []
def _serialize(... | identifier_body |
binary_tree.py | from typing import List
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val: int = 0, left: "TreeNode" = None, right: "TreeNode" = None):
self.val = val
self.left = left
self.right = right
@classmethod
def serialize(cls, root: "TreeNode") -> str:
"""... |
buffer.append(str(root.val))
_serialize(root.left)
_serialize(root.right)
_serialize(root)
return ",".join(buffer)
@classmethod
def deserialize(cls, data: str) -> "TreeNode":
"""Decodes your encoded data to tree."""
buffer = data.split(",")
... | buffer.append("#")
return | conditional_block |
binary_tree.py | from typing import List
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val: int = 0, left: "TreeNode" = None, right: "TreeNode" = None):
self.val = val
self.left = left
self.right = right
@classmethod
def serialize(cls, root: "TreeNode") -> str:
"""... | node.right = _deserialize(buffer)
return node
return _deserialize(buffer)
if __name__ == "__main__":
tests = [
"#",
"1,#,#",
"1,2,#,#,#",
"1,#,2,#,#",
"1,2,#,#,3,#,#",
"1,2,#,#,3,4,5,#,#,#,#",
]
for t in tests:
actual... | node.left = _deserialize(buffer) | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.