file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
wordomat.py | .w.setDefaultButton(self.w.submit)
self.w.open()
def loadPrefs(self):
"""Load the saved preferences into the program."""
self.requiredLetters = []
self.requiredGroups = [[], [], []]
self.banRepetitions = False
# preset character groups
self.groupPresets = ... | else:
message ("word-o-mat: Sorry, matching by glyph name is only supported when a font is open. Character \"%s\" will be skipped." % c)
else: # character values
result2.append(c)
result = [s for s in result2 if s] | random_line_split | |
wordomat.py | "Recent: " + ", ".join(self.requiredGroups[i]))
attrName = attrNameTemplate % j
setattr(self.g2.textMode, attrName, ComboBox((bPadd+2, y2, -bPadd, 19), optionsList, sizeStyle="small"))
groupBoxes = [self.g2.textMode.group1box, self.g2.textMode.group2box, self.g2.textMode.group3box]
... | nder):
"""Loads the RE syntax reference in a webbrowser."""
url = "https://docs.python.org/3.6/library/re.html#regular-expression-syntax"
webbrowser.open(url, new=2, autoraise=True)
def readExtDefaultBoolean(self, string):
"""Read a Boolean saved as a string from the prefs."""
... | erence(self, se | identifier_name |
Scripting.py | config)
env['hash'] = conf.hash
env['files'] = conf.files
env['environ'] = dict(conf.environ)
env['cwd'] = os.path.split(Utils.g_module.root_path)[0]
if Utils.g_module.root_path != src:
# in case the source dir is somewhere else
env.store(os.path.join(src, Options.lockfile))
env.store(Options.lockfile)
Op... | '''checks if the sources compile (tarball from 'dist')'''
import tempfile, tarfile
if not appname: appname = Utils.g_module.APPNAME | random_line_split | |
Scripting.py | != 'shutdown':
info('%r finished successfully%s' % (x, ela))
if not commands and x != 'shutdown':
commands.append('shutdown')
def configure(conf):
src = getattr(Options.options, SRCDIR, None)
if not src: src = getattr(Utils.g_module, SRCDIR, None)
if not src: src = getattr(Utils.g_module, 'top', None)
i... | dist | identifier_name | |
Scripting.py | bld = getattr(Options.options, BLDDIR, None)
if not bld: bld = getattr(Utils.g_module, BLDDIR, None)
if not bld: bld = getattr(Utils.g_module, 'out', None)
if not bld:
bld = 'build'
incomplete_bld = 1
if bld == '.':
raise Utils.WafError('Setting blddir="." may cause distclean problems')
bld = os.path.abspat... | arch_name = tmp_folder + '.' + 'zip' | conditional_block | |
Scripting.py | afdir':wafdir},
'profi.txt')
p = pstats.Stats('profi.txt')
p.sort_stats('time').print_stats(45)
#"""
def main():
global commands
commands = Options.arg_line[:]
while commands:
x = commands.pop(0)
ini = datetime.datetime.now()
if x == 'configure':
fun = configure
elif x == 'build':
fun = build
... | names = os.listdir(src)
os.makedirs(dst)
for name in names:
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
if dont_dist(name, src, build_dir):
continue
if os.path.isdir(srcname):
copytree(srcname, dstname, build_dir)
else:
shutil.copy2(srcname, dstname) | identifier_body | |
addpd.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*; | use ::Reg::*;
use ::RegScale::*;
fn addpd_1() {
run_test(&Instruction { mnemonic: Mnemonic::ADDPD, operand1: Some(Direct(XMM3)), operand2: Some(Direct(XMM3)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 88, 219], OperandS... | use ::Operand::*; | random_line_split |
addpd.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn addpd_1() {
run_test(&Instruction { mnemonic: Mnemonic::ADDPD, operand1: Some(Direct(XMM3)), operand2: Some(Direct(XMM3... |
fn addpd_3() {
run_test(&Instruction { mnemonic: Mnemonic::ADDPD, operand1: Some(Direct(XMM4)), operand2: Some(Direct(XMM3)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 88, 227], OperandSize::Qword)
}
fn addpd_4() {
... | {
run_test(&Instruction { mnemonic: Mnemonic::ADDPD, operand1: Some(Direct(XMM3)), operand2: Some(IndirectDisplaced(EDX, 627557726, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 88, 154, 9... | identifier_body |
addpd.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn addpd_1() {
run_test(&Instruction { mnemonic: Mnemonic::ADDPD, operand1: Some(Direct(XMM3)), operand2: Some(Direct(XMM3... | () {
run_test(&Instruction { mnemonic: Mnemonic::ADDPD, operand1: Some(Direct(XMM3)), operand2: Some(IndirectDisplaced(EDX, 627557726, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 88, 154... | addpd_2 | identifier_name |
output_buffer.rs | use sys::*;
use std::cmp::min;
use std::ptr::null_mut;
/// This trait is intended to extend `usize` with safe downsize casts, so we can pass it as buffer
/// length into odbc functions.
pub trait OutputBuffer {
fn buf_len<T>(&self) -> T
where
T: BufferLength;
fn mut_buf_ptr(&mut self) -> *mut u8;
}... |
}
impl BufferLength for SQLLEN {
fn max_value() -> usize {
Self::max_value() as usize
}
fn from_usize(len: usize) -> Self {
len as Self
}
}
| {
len as Self
} | identifier_body |
output_buffer.rs | use sys::*; | pub trait OutputBuffer {
fn buf_len<T>(&self) -> T
where
T: BufferLength;
fn mut_buf_ptr(&mut self) -> *mut u8;
}
impl OutputBuffer for [u8] {
fn buf_len<T>(&self) -> T
where
T: BufferLength,
{
T::from_usize(min(self.len(), T::max_value()))
}
fn mut_buf_ptr(&mut... | use std::cmp::min;
use std::ptr::null_mut;
/// This trait is intended to extend `usize` with safe downsize casts, so we can pass it as buffer
/// length into odbc functions. | random_line_split |
output_buffer.rs | use sys::*;
use std::cmp::min;
use std::ptr::null_mut;
/// This trait is intended to extend `usize` with safe downsize casts, so we can pass it as buffer
/// length into odbc functions.
pub trait OutputBuffer {
fn buf_len<T>(&self) -> T
where
T: BufferLength;
fn mut_buf_ptr(&mut self) -> *mut u8;
}... | (&mut self) -> *mut u8 {
if self.is_empty() {
null_mut()
} else {
self.as_mut_ptr()
}
}
}
pub trait BufferLength {
fn max_value() -> usize;
fn from_usize(len: usize) -> Self;
}
impl BufferLength for SQLSMALLINT {
fn max_value() -> usize {
Self::m... | mut_buf_ptr | identifier_name |
output_buffer.rs | use sys::*;
use std::cmp::min;
use std::ptr::null_mut;
/// This trait is intended to extend `usize` with safe downsize casts, so we can pass it as buffer
/// length into odbc functions.
pub trait OutputBuffer {
fn buf_len<T>(&self) -> T
where
T: BufferLength;
fn mut_buf_ptr(&mut self) -> *mut u8;
}... | else {
self.as_mut_ptr()
}
}
}
pub trait BufferLength {
fn max_value() -> usize;
fn from_usize(len: usize) -> Self;
}
impl BufferLength for SQLSMALLINT {
fn max_value() -> usize {
Self::max_value() as usize
}
fn from_usize(len: usize) -> Self {
len as Self... | {
null_mut()
} | conditional_block |
Battleship.py | #importing randint
from random import randint
#creating an empty list
board = []
#filling up the list by O and creating a two dimensionall array
for x in range(5):
board.append(["O"] * 5)
#printing function which also includes a spaces to show clear grid
def print_board(board):
for row in board:
prin... |
#remembering the ship
ship_row = random_row(board)
ship_col = random_col(board)
#game loop
for turn in range(4):
guess_row = int(raw_input("Guess Row:"))
guess_col = int(raw_input("Guess Col:"))
if guess_row == ship_row and guess_col == ship_col:
print "Congratulations! You sunk my battlesh... | return randint(0, len(board[0]) - 1) | identifier_body |
Battleship.py | #importing randint
from random import randint
#creating an empty list
board = []
#filling up the list by O and creating a two dimensionall array
for x in range(5):
board.append(["O"] * 5)
#printing function which also includes a spaces to show clear grid
def print_board(board):
for row in board:
prin... |
elif(board[guess_row][guess_col] == "X"):
print "You guessed that one already."
else:
print "You missed my battleship!"
board[guess_row][guess_col] = "X"
if(turn == 3):
print "Game Over"
print (turn+1)
print_board(board)
| print "Oops, that's not even in the ocean." | conditional_block |
Battleship.py | #importing randint
from random import randint
#creating an empty list
board = []
#filling up the list by O and creating a two dimensionall array
for x in range(5):
board.append(["O"] * 5)
#printing function which also includes a spaces to show clear grid
def print_board(board):
for row in board:
prin... | board[guess_row][guess_col] = "X"
if(turn == 3):
print "Game Over"
print (turn+1)
print_board(board) | random_line_split | |
Battleship.py | #importing randint
from random import randint
#creating an empty list
board = []
#filling up the list by O and creating a two dimensionall array
for x in range(5):
board.append(["O"] * 5)
#printing function which also includes a spaces to show clear grid
def print_board(board):
for row in board:
prin... | (board):
return randint(0, len(board) - 1)
def random_col(board):
return randint(0, len(board[0]) - 1)
#remembering the ship
ship_row = random_row(board)
ship_col = random_col(board)
#game loop
for turn in range(4):
guess_row = int(raw_input("Guess Row:"))
guess_col = int(raw_input("Guess Col:"))
... | random_row | identifier_name |
builder.py | import os
class generic(object):
def __init__(self,myspec):
self.settings=myspec
self.settings.setdefault('CHROOT', 'chroot')
def setarch(self, arch):
"""Set the chroot wrapper to run through `setarch |arch|`
Useful for building x86-on-amd64 and such.
"""
if os.uname()[0] == 'Linux':
self.settings['... | def umount_all(self):
"""unmount all bind mounts"""
pass |
def mount_all(self):
"""do all bind mounts"""
pass
| random_line_split |
builder.py | import os
class generic(object):
def | (self,myspec):
self.settings=myspec
self.settings.setdefault('CHROOT', 'chroot')
def setarch(self, arch):
"""Set the chroot wrapper to run through `setarch |arch|`
Useful for building x86-on-amd64 and such.
"""
if os.uname()[0] == 'Linux':
self.settings['CHROOT'] = 'setarch %s %s' % (arch, self.settin... | __init__ | identifier_name |
builder.py | import os
class generic(object):
def __init__(self,myspec):
self.settings=myspec
self.settings.setdefault('CHROOT', 'chroot')
def setarch(self, arch):
"""Set the chroot wrapper to run through `setarch |arch|`
Useful for building x86-on-amd64 and such.
"""
if os.uname()[0] == 'Linux':
|
def mount_safety_check(self):
"""
Make sure that no bind mounts exist in chrootdir (to use before
cleaning the directory, to make sure we don't wipe the contents of
a bind mount
"""
pass
def mount_all(self):
"""do all bind mounts"""
pass
def umount_all(self):
"""unmount all bind mounts"""
pas... | self.settings['CHROOT'] = 'setarch %s %s' % (arch, self.settings['CHROOT']) | conditional_block |
builder.py | import os
class generic(object):
def __init__(self,myspec):
|
def setarch(self, arch):
"""Set the chroot wrapper to run through `setarch |arch|`
Useful for building x86-on-amd64 and such.
"""
if os.uname()[0] == 'Linux':
self.settings['CHROOT'] = 'setarch %s %s' % (arch, self.settings['CHROOT'])
def mount_safety_check(self):
"""
Make sure that no bind mounts ... | self.settings=myspec
self.settings.setdefault('CHROOT', 'chroot') | identifier_body |
auto_args.rs | Delegate::new(self.into());
$(
build_rpc_trait!(WRAP del =>
( $($t)* )
fn $m_name ( $($p)* ) $( -> Result<$out, Error> )*
);
)*
del
}
}
};
( WRAP $del: expr =>
(name = $name: expr)
fn $method: ident (&self $(, $param: ty)*) -> Result<$out: ty, Error>
) => {
$del.add_meth... | .map(|($($x,)+)| ($($x,)+ TRAILING::default())),
1 => from_params::<($($x,)+ TRAILING)>(params)
.map(|($($x,)+ id)| ($($x,)+ id)),
_ => Err(Error::invalid_params()), | random_line_split | |
auto_args.rs | definition.
///
/// This just copies out all the methods, docs, and adds another
/// function `to_delegate` which will automatically wrap each strongly-typed
/// function in a wrapper which handles parameter and output type serialization.
///
/// RPC functions may come in a couple forms: async and synchronous.
/// The... |
}
impl<B, OUT, T> WrapAsync<B> for fn(&B, Ready<OUT>, Trailing<T>)
where B: Send + Sync + 'static, OUT: Serialize, T: Default + Deserialize
{
fn wrap_rpc(&self, base: &B, params: Params, ready: ::jsonrpc_core::Ready) {
let len = match params {
Params::Array(ref v) => v.len(),
Params::None => 0,
_ => retu... | {
let len = match params {
Params::Array(ref v) => v.len(),
Params::None => 0,
_ => return Err(errors::invalid_params("not an array", "")),
};
let (id,) = match len {
0 => (T::default(),),
1 => try!(from_params::<(T,)>(params)),
_ => return Err(Error::invalid_params()),
};
(self)(base, Tra... | identifier_body |
auto_args.rs | definition.
///
/// This just copies out all the methods, docs, and adds another
/// function `to_delegate` which will automatically wrap each strongly-typed
/// function in a wrapper which handles parameter and output type serialization.
///
/// RPC functions may come in a couple forms: async and synchronous.
/// The... | (&self, base: &B, params: Params) -> Result<Value, Error> {
::v1::helpers::params::expect_no_params(params)
.and_then(|()| (self)(base))
.map(to_value)
}
}
impl<B, OUT> WrapAsync<B> for fn(&B, Ready<OUT>)
where B: Send + Sync + 'static, OUT: Serialize
{
fn wrap_rpc(&self, base: &B, params: Params, ready: ::... | wrap_rpc | identifier_name |
indent.rs | //! Indentation functions
use remacs_macros::lisp_fn;
use remacs_sys;
use lisp::LispObject;
use lisp::defsubr;
/// Return the horizontal position of point.
/// Beginning of line is column 0.
/// This is calculated by adding together the widths of all the
/// displayed representations of the character between the sta... | /// end of line when `selective-display' is t. Text that has an
/// invisible property is considered as having width 0, unless
/// `buffer-invisibility-spec' specifies that it is replaced by an
/// ellipsis.
#[lisp_fn]
pub fn current_column() -> LispObject {
LispObject::from_natnum(unsafe { remacs_sys::current_colu... | /// width of frame, which means that this function may return values
/// greater than (frame-width). Whether the line is visible (if
/// `selective-display' is t) has no effect; however, ^M is treated as | random_line_split |
indent.rs | //! Indentation functions
use remacs_macros::lisp_fn;
use remacs_sys;
use lisp::LispObject;
use lisp::defsubr;
/// Return the horizontal position of point.
/// Beginning of line is column 0.
/// This is calculated by adding together the widths of all the
/// displayed representations of the character between the sta... |
include!(concat!(env!("OUT_DIR"), "/indent_exports.rs"));
| {
LispObject::from_natnum(unsafe { remacs_sys::current_column() })
} | identifier_body |
indent.rs | //! Indentation functions
use remacs_macros::lisp_fn;
use remacs_sys;
use lisp::LispObject;
use lisp::defsubr;
/// Return the horizontal position of point.
/// Beginning of line is column 0.
/// This is calculated by adding together the widths of all the
/// displayed representations of the character between the sta... | () -> LispObject {
LispObject::from_natnum(unsafe { remacs_sys::current_column() })
}
include!(concat!(env!("OUT_DIR"), "/indent_exports.rs"));
| current_column | identifier_name |
testdrive.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: LiSnB
# @Date: 2014-06-06 23:03:54
# @Last Modified by: LiSnB
# @Last Modified time: 2014-06-07 17:24:00
# @Email: lisnb.h@gmail.com
"""
# @comment here:
"""
from configs.config import ISWINDOWS
import intelliSeg
def | ():
s="""
以下内容将被分词:\n\n“小编总结一下:考前上厕所,考中别抄袭,(don't cheat in the exam),考完别对题,报考大学需谨慎,看看留言里那些拼命劝人不要考自己大学的小伙伴就知道了…”
同时,位于test目录下的 Mr.Zong.txt 中的内容也将被分词,并生成文件。
"""
if ISWINDOWS:
print s.decode('utf-8').encode('gbk')
else:
print s
intelliSeg.seg(s)
intelliSeg.seg('./test/Mr.Zong.txt',handlers='fvmx... | foo | identifier_name |
testdrive.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: LiSnB
# @Date: 2014-06-06 23:03:54
# @Last Modified by: LiSnB
# @Last Modified time: 2014-06-07 17:24:00
# @Email: lisnb.h@gmail.com
"""
# @comment here:
"""
from configs.config import ISWINDOWS
import intelliSeg
def foo():
| s="""
以下内容将被分词:\n\n“小编总结一下:考前上厕所,考中别抄袭,(don't cheat in the exam),考完别对题,报考大学需谨慎,看看留言里那些拼命劝人不要考自己大学的小伙伴就知道了…”
同时,位于test目录下的 Mr.Zong.txt 中的内容也将被分词,并生成文件。
"""
if ISWINDOWS:
print s.decode('utf-8').encode('gbk')
else:
print s
intelliSeg.seg(s)
intelliSeg.seg('./test/Mr.Zong.txt',handlers='fvmx',is_f... | identifier_body | |
testdrive.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: LiSnB
# @Date: 2014-06-06 23:03:54
# @Last Modified by: LiSnB
# @Last Modified time: 2014-06-07 17:24:00
# @Email: lisnb.h@gmail.com
"""
# @comment here:
"""
from configs.config import ISWINDOWS
import intelliSeg
|
同时,位于test目录下的 Mr.Zong.txt 中的内容也将被分词,并生成文件。
"""
if ISWINDOWS:
print s.decode('utf-8').encode('gbk')
else:
print s
intelliSeg.seg(s)
intelliSeg.seg('./test/Mr.Zong.txt',handlers='fvmx',is_file=True)
if __name__ == '__main__':
foo() | def foo():
s="""
以下内容将被分词:\n\n“小编总结一下:考前上厕所,考中别抄袭,(don't cheat in the exam),考完别对题,报考大学需谨慎,看看留言里那些拼命劝人不要考自己大学的小伙伴就知道了…”
| random_line_split |
testdrive.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: LiSnB
# @Date: 2014-06-06 23:03:54
# @Last Modified by: LiSnB
# @Last Modified time: 2014-06-07 17:24:00
# @Email: lisnb.h@gmail.com
"""
# @comment here:
"""
from configs.config import ISWINDOWS
import intelliSeg
def foo():
s="""
以下内容将被... | conditional_block | ||
dummy.py | # -*- coding: utf-8 -*-
#
# Dummy parameters for models created in unit tests
#
from datetime import datetime
credentials = '''{
"invalid": false,
"token_uri": "https://accounts.google.com/o/oauth2/token",
"refresh_token": "",
"client_id": "351298984682.apps.googleusercontent.com",
"token_expiry": "2050-11-... | 'google_spreadsheet': u'dummy_key',
'google_worksheet': u'dummy_id',
'licence': u'Do What You Like',
'slug': u'data-1',
'tags': u'Apples, Oranges, Pears',
'tbl_stars': 5,
'title': u'Dummy Data',
}
# Params for valid data view m... | data_source_json = {
'description': u'A Dummy Data Source', | random_line_split |
index.js | const express = require('express');
const find = require('array-find');
const Archive = require('./archive');
const ServerConfig = require('../utils/server-config');
const BLP = require('blizzardry/lib/blp');
const {DecodeStream} = require('blizzardry/lib/restructure');
const DBC = require('blizzardry/lib/dbc/entities'... |
} else {
res.send(dbc.records);
}
} else {
err = new Error('entity definition not found');
err.status = 404;
throw err;
}
}
find(req, res) {
res.send(this.archive.files.find(req.params.query));
}
serve(req, res) {
res.send(req.resource.data);
}
};
| {
err = new Error('entity not found');
err.status = 404;
throw err;
} | conditional_block |
index.js | const express = require('express');
const find = require('array-find');
const Archive = require('./archive');
const ServerConfig = require('../utils/server-config');
const BLP = require('blizzardry/lib/blp');
const {DecodeStream} = require('blizzardry/lib/restructure');
const DBC = require('blizzardry/lib/dbc/entities'... |
resource(req, res, next, path) {
req.resourcePath = path;
if (req.resource = this.archive.files.get(path)) {
next();
} else {
const err = new Error('resource not found');
err.status = 404;
throw err;
}
}
blp(req, res) {
BLP.from(req.resource.data, function(blp) {
... | {
this._archive = this._archive || Archive.build(this.constructor.DATA_DIR);
return this._archive;
} | identifier_body |
index.js | const express = require('express');
const find = require('array-find');
const Archive = require('./archive');
const ServerConfig = require('../utils/server-config');
const BLP = require('blizzardry/lib/blp');
const {DecodeStream} = require('blizzardry/lib/restructure');
const DBC = require('blizzardry/lib/dbc/entities'... | () {
this.router = express();
this.router.param('resource', this.resource.bind(this));
this.router.get('/:resource(*.blp).png', this.blp.bind(this));
this.router.get('/:resource(*.dbc)/:id(*)?.json', this.dbc.bind(this));
this.router.get('/find/:query', this.find.bind(this));
this.router.get('/:... | constructor | identifier_name |
index.js | const express = require('express');
const find = require('array-find');
const Archive = require('./archive');
const ServerConfig = require('../utils/server-config');
const BLP = require('blizzardry/lib/blp');
const {DecodeStream} = require('blizzardry/lib/restructure');
const DBC = require('blizzardry/lib/dbc/entities'... | }
}
find(req, res) {
res.send(this.archive.files.find(req.params.query));
}
serve(req, res) {
res.send(req.resource.data);
}
}; | err = new Error('entity definition not found');
err.status = 404;
throw err; | random_line_split |
imperative_grad.py | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | (tape,
target,
sources,
output_gradients=None,
sources_raw=None,
unconnected_gradients=UnconnectedGradients.NONE):
"""Computes gradients from the imperatively defined tape on top of the stack.
Works by filtering the... | imperative_grad | identifier_name |
imperative_grad.py | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | target: either a Tensor or list of Tensors to be differentiated.
sources: list of Tensors for which we want gradients
output_gradients: if not None, a list of gradient provided for each Target,
or None if we are to use the target's computed downstream gradient.
sources_raw: if not None, a list of the so... | random_line_split | |
imperative_grad.py | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | the gradient wrt each of the sources.
Raises:
ValueError: if the arguments are invalid.
RuntimeError: if something goes wrong.
"""
try:
unconnected_gradients = UnconnectedGradients(unconnected_gradients)
except ValueError:
raise ValueError(
"Unknown value for unconnected_gradients: %... | """Computes gradients from the imperatively defined tape on top of the stack.
Works by filtering the tape, computing how many downstream usages are of each
tensor and entry, and repeatedly applying backward functions until we have
gradients for all sources.
Args:
tape: the gradient tape which stores the tr... | identifier_body |
aframe-inspector.js | /* Reload the aframe dynamically, as needed
*/
$(function(){
var x = "";
var debuging = {};
var gui;
// We describe specific elements using the path from the a-scene,
// as a list of children #'s, from top to bottom.
// This returns a jquery selector
function sceneElementSelector(o) {
... |
}
}
rec("")
return r
}
gui = new dat.GUI();
dat.GUI.prototype.removeFolder = function(name) {
var folder = this.__folders[name];
if (!folder) {
return;
}
folder.close();
this.__ul.removeChild(folder.domElement.parentNode);
delete this.__fol... | {
r.push(p)
rec(p)
} | conditional_block |
aframe-inspector.js | /* Reload the aframe dynamically, as needed
*/
$(function(){
var x = "";
var debuging = {};
var gui;
// We describe specific elements using the path from the a-scene,
// as a list of children #'s, from top to bottom.
// This returns a jquery selector
function sceneElementSelector(o) {
... | for (var i in defaults) {
// TODO: if/then/else
if (typeof(defaults[i]) == "boolean") {
reloadGUI[i] && gui.remove(reloadGUI[i])
} else {
gui.removeFolder(i)
}
}
// And refill it
reloadGUI.entity = gui.add(active, 'entity', entityDict );
reloa... | reloadGUI.entity && gui.remove(reloadGUI.entity) | random_line_split |
aframe-inspector.js | /* Reload the aframe dynamically, as needed
*/
$(function(){
var x = "";
var debuging = {};
var gui;
// We describe specific elements using the path from the a-scene,
// as a list of children #'s, from top to bottom.
// This returns a jquery selector
function sceneElementSelector(o) {
... |
rec("")
return r
}
gui = new dat.GUI();
dat.GUI.prototype.removeFolder = function(name) {
var folder = this.__folders[name];
if (!folder) {
return;
}
folder.close();
this.__ul.removeChild(folder.domElement.parentNode);
delete this.__folders[name];
this.onRes... | {
var ch = $(sceneElementSelector(o)).children();
for(var i = 0;i < ch.length;i++) {
var p = (o == "")?(o + (i+1)):(o + "." + (i+1))
if ($(sceneElementSelector(p)).prop("tagName").substring(0,2) == "A-") {
r.push(p)
rec(p)
}
}
} | identifier_body |
aframe-inspector.js | /* Reload the aframe dynamically, as needed
*/
$(function(){
var x = "";
var debuging = {};
var gui;
// We describe specific elements using the path from the a-scene,
// as a list of children #'s, from top to bottom.
// This returns a jquery selector
function sceneElementSelector(o) {
... | () {
console.log("sceneElements")
var r = []
function rec(o) {
var ch = $(sceneElementSelector(o)).children();
for(var i = 0;i < ch.length;i++) {
var p = (o == "")?(o + (i+1)):(o + "." + (i+1))
if ($(sceneElementSelector(p)).prop("tagName").substring(0,2) == "A-") {... | sceneElements | identifier_name |
update_doc_utils.py | ##############################################################################
# Name: misc/scripts/update_doc_utils.py
# Purpose: base utilities for others update_doc_*.py scripts
# Created: 2007-08-1
# RCS-ID: $Id$
# Copyright: (c) 2007 Francesco Montorsi
# Licence: wxWindows licence
#############... |
print " file %s contains %d class declarations" % (f, classdecl)
return count
| line = content[i]
if "\class{" in line:
classdecl = classdecl + 1
# polish the class name
classname = line
classname = classname[classname.find("\class{"):]
classname = classname[classname.find("{")+1:classname.find("}")]
... | conditional_block |
update_doc_utils.py | ##############################################################################
# Name: misc/scripts/update_doc_utils.py
# Purpose: base utilities for others update_doc_*.py scripts
# Created: 2007-08-1
# RCS-ID: $Id$
# Copyright: (c) 2007 Francesco Montorsi
# Licence: wxWindows licence
#############... |
print " file %s contains %d class declarations" % (f, classdecl)
return count | if not callback(classname, f, content, i):
return count | random_line_split |
update_doc_utils.py | ##############################################################################
# Name: misc/scripts/update_doc_utils.py
# Purpose: base utilities for others update_doc_*.py scripts
# Created: 2007-08-1
# RCS-ID: $Id$
# Copyright: (c) 2007 Francesco Montorsi
# Licence: wxWindows licence
#############... | (callback):
count = 0
for f in glob.glob(DOCS_PATH + '/*.tex'):
file = open(f, "r")
if not file:
print "could not open %s" % f
continue
print "opened file %s" % f
count = count + 1
# search \class tags
content = file.readlines()
cl... | scanTexFiles | identifier_name |
update_doc_utils.py | ##############################################################################
# Name: misc/scripts/update_doc_utils.py
# Purpose: base utilities for others update_doc_*.py scripts
# Created: 2007-08-1
# RCS-ID: $Id$
# Copyright: (c) 2007 Francesco Montorsi
# Licence: wxWindows licence
#############... | classname = classname[classname.find("{")+1:classname.find("}")]
print " the class declared is named '%s'" % classname
# process this \class
if not callback(classname, f, content, i):
return count
print " file %s contains %d c... | count = 0
for f in glob.glob(DOCS_PATH + '/*.tex'):
file = open(f, "r")
if not file:
print "could not open %s" % f
continue
print "opened file %s" % f
count = count + 1
# search \class tags
content = file.readlines()
classdecl = 0
... | identifier_body |
glue.rs | //!
//
// Code relating to drop glue.
use crate::common::IntPredicate;
use crate::meth;
use crate::traits::*;
use rustc_middle::ty::{self, Ty};
pub fn size_and_align_of_dst<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
bx: &mut Bx,
t: Ty<'tcx>,
info: Option<Bx::Value>,
) -> (Bx::Value, Bx::Value) {
let lay... |
// Choose max of two known alignments (combined value must
// be aligned according to more restrictive of the two).
let align = match (
bx.const_to_opt_u128(sized_align, false),
bx.const_to_opt_u128(unsized_align, false),
) {
... | {
if def.repr.packed() {
unsized_align = sized_align;
}
} | conditional_block |
glue.rs | //!
//
// Code relating to drop glue.
use crate::common::IntPredicate;
use crate::meth;
use crate::traits::*;
use rustc_middle::ty::{self, Ty};
pub fn size_and_align_of_dst<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
bx: &mut Bx,
t: Ty<'tcx>,
info: Option<Bx::Value>,
) -> (Bx::Value, Bx::Value) {
let lay... | ) {
(Some(sized_align), Some(unsized_align)) => {
// If both alignments are constant, (the sized_align should always be), then
// pick the correct alignment statically.
bx.const_usize(std::cmp::max(sized_align, unsized_align) as u64... | random_line_split | |
glue.rs | //!
//
// Code relating to drop glue.
use crate::common::IntPredicate;
use crate::meth;
use crate::traits::*;
use rustc_middle::ty::{self, Ty};
pub fn | <'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
bx: &mut Bx,
t: Ty<'tcx>,
info: Option<Bx::Value>,
) -> (Bx::Value, Bx::Value) {
let layout = bx.layout_of(t);
debug!("size_and_align_of_dst(ty={}, info={:?}): layout: {:?}", t, info, layout);
if !layout.is_unsized() {
let size = bx.const_usize(l... | size_and_align_of_dst | identifier_name |
glue.rs | //!
//
// Code relating to drop glue.
use crate::common::IntPredicate;
use crate::meth;
use crate::traits::*;
use rustc_middle::ty::{self, Ty};
pub fn size_and_align_of_dst<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
bx: &mut Bx,
t: Ty<'tcx>,
info: Option<Bx::Value>,
) -> (Bx::Value, Bx::Value) | let unit = layout.field(bx, 0);
// The info in this case is the length of the str, so the size is that
// times the unit size.
(
bx.mul(info.unwrap(), bx.const_usize(unit.size.bytes())),
bx.const_usize(unit.align.abi.bytes()),
)... | {
let layout = bx.layout_of(t);
debug!("size_and_align_of_dst(ty={}, info={:?}): layout: {:?}", t, info, layout);
if !layout.is_unsized() {
let size = bx.const_usize(layout.size.bytes());
let align = bx.const_usize(layout.align.abi.bytes());
return (size, align);
}
match t.ki... | identifier_body |
benchmark.array.js | /**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by a... |
main();
| {
var len;
var min;
var max;
var f;
var i;
min = 1; // 10^min
max = 6; // 10^max
for ( i = min; i <= max; i++ ) {
len = pow( 10, i );
f = createBenchmark( len );
bench( pkg+'::array:len='+len, f );
}
} | identifier_body |
benchmark.array.js | /**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by a... |
b.pass( 'benchmark finished' );
b.end();
}
}
// MAIN //
/**
* Main execution sequence.
*
* @private
*/
function main() {
var len;
var min;
var max;
var f;
var i;
min = 1; // 10^min
max = 6; // 10^max
for ( i = min; i <= max; i++ ) {
len = pow( 10, i );
f = createBenchmark( len );
bench( pkg+':... | {
b.fail( 'should return an array' );
} | conditional_block |
benchmark.array.js | /**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by a... | () {
var len;
var min;
var max;
var f;
var i;
min = 1; // 10^min
max = 6; // 10^max
for ( i = min; i <= max; i++ ) {
len = pow( 10, i );
f = createBenchmark( len );
bench( pkg+'::array:len='+len, f );
}
}
main();
| main | identifier_name |
benchmark.array.js | /**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by a... | var x = filled( -3.0, len );
return benchmark;
/**
* Benchmark function.
*
* @private
* @param {Benchmark} b - benchmark instance
*/
function benchmark( b ) {
var out;
var i;
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
out = map( x, abs );
if ( out.length !== len ) {
b.fail( 'unexpected... | * @param {PositiveInteger} len - array length
* @returns {Function} benchmark function
*/
function createBenchmark( len ) { | random_line_split |
bloom.py |
#
# bloom.py
#
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
"""Bloom filter support"""
from __future__ import absolute_import, division, print_function, unicode_literals
import struct
import sys
import math
import bit... | hash function It should generally always be a random value (and is
largely only exposed for unit testing)
nFlags should be one of the UPDATE_* enums (but not _MASK)
"""
LN2SQUARED = 0.4804530139182014246671025263266649717305529515945455
LN2 = 0.69314718055994530941723212... | MAX_BLOOM_FILTER_SIZE = 36000
MAX_HASH_FUNCS = 50
UPDATE_NONE = 0
UPDATE_ALL = 1
UPDATE_P2PUBKEY_ONLY = 2
UPDATE_MASK = 3
def __init__(self, nElements, nFPRate, nTweak, nFlags):
"""Create a new bloom filter
The filter will have a given false-positive rate when filled with the
... | identifier_body |
bloom.py |
#
# bloom.py
#
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
"""Bloom filter support"""
from __future__ import absolute_import, division, print_function, unicode_literals
import struct
import sys
import math
import bit... | (self):
return len(self.vData) <= self.MAX_BLOOM_FILTER_SIZE and self.nHashFuncs <= self.MAX_HASH_FUNCS
def IsRelevantAndUpdate(tx, tx_hash):
# Not useful for a client, so not implemented yet.
raise NotImplementedError
__struct = struct.Struct(b'<IIB')
@classmethod
def stream_d... | IsWithinSizeConstraints | identifier_name |
bloom.py | #
# bloom.py
#
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
"""Bloom filter support"""
from __future__ import absolute_import, division, print_function, unicode_literals
import struct
import sys
import math
import bitc... |
def MurmurHash3(nHashSeed, vDataToHash):
"""MurmurHash3 (x86_32)
Used for bloom filters. See http://code.google.com/p/smhasher/source/browse/trunk/MurmurHash3.cpp
"""
assert nHashSeed <= 0xFFFFFFFF
h1 = nHashSeed
c1 = 0xcc9e2d51
c2 = 0x1b873593
# body
i = 0
while i < len(vDa... | return ((x << r) & 0xFFFFFFFF) | (x >> (32 - r)) | random_line_split |
bloom.py |
#
# bloom.py
#
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
"""Bloom filter support"""
from __future__ import absolute_import, division, print_function, unicode_literals
import struct
import sys
import math
import bit... |
return True
def IsWithinSizeConstraints(self):
return len(self.vData) <= self.MAX_BLOOM_FILTER_SIZE and self.nHashFuncs <= self.MAX_HASH_FUNCS
def IsRelevantAndUpdate(tx, tx_hash):
# Not useful for a client, so not implemented yet.
raise NotImplementedError
__struct = str... | return False | conditional_block |
inferred-suffix-in-pattern-range.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 ... | 0 .. 1 => { ~"not many" }
_ => { ~"lots" }
};
assert_eq!(x_message, ~"lots");
let y = 2i;
let y_message = match y {
0 .. 1 => { ~"not many" }
_ => { ~"lots" }
};
assert_eq!(y_message, ~"lots");
let z = 1u64;
let z_message = match z {
... | let x = 2;
let x_message = match x { | random_line_split |
inferred-suffix-in-pattern-range.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 ... | () {
let x = 2;
let x_message = match x {
0 .. 1 => { ~"not many" }
_ => { ~"lots" }
};
assert_eq!(x_message, ~"lots");
let y = 2i;
let y_message = match y {
0 .. 1 => { ~"not many" }
_ => { ~"lots" }
};
assert_eq!(y_message, ~"lots");
... | main | identifier_name |
inferred-suffix-in-pattern-range.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_eq!(z_message, ~"not many");
}
| {
let x = 2;
let x_message = match x {
0 .. 1 => { ~"not many" }
_ => { ~"lots" }
};
assert_eq!(x_message, ~"lots");
let y = 2i;
let y_message = match y {
0 .. 1 => { ~"not many" }
_ => { ~"lots" }
};
assert_eq!(y_message, ~"lots");
... | identifier_body |
cli.py | """
Lua pattern matcher based on a NFA
inspired by
http://swtch.com/~rsc/regexp/regexp1.html
"""
from rpyre.interface.lua import compile_re
from rpyre.matching import find
def main(args):
n = 20
s = args[1]
#s = "(a|b)*a%sa(a|b)*$" % ("(a|b)" * n, )
print s
evilregex = compile_re(s)
import os... |
chunks.append(s)
s = "".join(chunks)
print len(s)
print find(evilregex, s, 0)
"""
for x in find2(evilregex, s, 0):
print x
"""
return 0
# needed for the PyPy translation toolchain
def target(*args):
return main, None
def jitpolicy(*args):
from rpython.jit.codewri... | break | conditional_block |
cli.py | """
Lua pattern matcher based on a NFA
inspired by
http://swtch.com/~rsc/regexp/regexp1.html
"""
from rpyre.interface.lua import compile_re
from rpyre.matching import find
def main(args):
n = 20
s = args[1]
#s = "(a|b)*a%sa(a|b)*$" % ("(a|b)" * n, )
print s
evilregex = compile_re(s)
import os... | return main, None
def jitpolicy(*args):
from rpython.jit.codewriter.policy import JitPolicy
return JitPolicy()
if __name__ == '__main__':
import sys
sys.exit(main(sys.argv)) | random_line_split | |
cli.py | """
Lua pattern matcher based on a NFA
inspired by
http://swtch.com/~rsc/regexp/regexp1.html
"""
from rpyre.interface.lua import compile_re
from rpyre.matching import find
def main(args):
n = 20
s = args[1]
#s = "(a|b)*a%sa(a|b)*$" % ("(a|b)" * n, )
print s
evilregex = compile_re(s)
import os... |
if __name__ == '__main__':
import sys
sys.exit(main(sys.argv))
| from rpython.jit.codewriter.policy import JitPolicy
return JitPolicy() | identifier_body |
cli.py | """
Lua pattern matcher based on a NFA
inspired by
http://swtch.com/~rsc/regexp/regexp1.html
"""
from rpyre.interface.lua import compile_re
from rpyre.matching import find
def | (args):
n = 20
s = args[1]
#s = "(a|b)*a%sa(a|b)*$" % ("(a|b)" * n, )
print s
evilregex = compile_re(s)
import os
chunks = []
# use os.read to be RPython compatible
while True:
s = os.read(0, 4096)
if not s:
break
chunks.append(s)
s = "".join(c... | main | identifier_name |
learn_images.py | # coding: utf-8
"""
labeled_images文件夹中:
1. 包含的文件夹名为标记名
2. 标记名下的文件夹中包含了学习图片
"""
import os
from sklearn import svm
from PIL import Image
from numpy import array
from utils import *
clf = None
def get_image_fit_data(dir_name):
"""读取labeled_images文件夹的图片,返回图片的特征矩阵及相应标记"""
X = []
Y = []
... | i = Image.open(os.path.join(dir_name, name, img))
X.append(array(i).flatten())
Y.append(name)
return X, Y
def get_classifier_from_learn():
"""学习数据获取分类器"""
global clf
if not clf:
clf = svm.SVC()
X, Y = get_image_fit_data("labeled_images")
c... | conditional_block | |
learn_images.py | # coding: utf-8
"""
labeled_images文件夹中:
1. 包含的文件夹名为标记名
2. 标记名下的文件夹中包含了学习图片
"""
import os
from sklearn import svm
from PIL import Image
from numpy import array
from utils import *
clf = None
def get_image_fit_data(dir_name):
"""读取labeled_images文件夹的图片,返回图片的特征矩阵及相应标记"""
X = []
Y = []
... |
def get_classifier_from_learn():
"""学习数据获取分类器"""
global clf
if not clf:
clf = svm.SVC()
X, Y = get_image_fit_data("labeled_images")
clf.fit(X, Y)
return clf
def main():
clf = get_classifier_from_learn()
print(clf)
PX, PY = get_image_fit_data("predic... |
return X, Y
| random_line_split |
learn_images.py | # coding: utf-8
"""
labeled_images文件夹中:
1. 包含的文件夹名为标记名
2. 标记名下的文件夹中包含了学习图片
"""
import os
from sklearn import svm
from PIL import Image
from numpy import array
from utils import *
clf = None
def get_image_fit_data(dir_name):
"""读取labeled_images文件夹的图片,返回图片的特征矩阵及相应标记"""
X = []
Y = | m.SVC()
X, Y = get_image_fit_data("labeled_images")
clf.fit(X, Y)
return clf
def main():
clf = get_classifier_from_learn()
print(clf)
PX, PY = get_image_fit_data("predict_images")
for x, y in zip(PX, PY):
r = clf.predict(x.reshape(1, -1))
print(r, y)
... | []
name_list = os.listdir(dir_name)
for name in name_list:
if not os.path.isdir(os.path.join(dir_name, name)):
continue
image_files = os.listdir(os.path.join(dir_name, name))
for img in image_files:
i = Image.open(os.path.join(dir_name, name, img))
... | identifier_body |
learn_images.py | # coding: utf-8
"""
labeled_images文件夹中:
1. 包含的文件夹名为标记名
2. 标记名下的文件夹中包含了学习图片
"""
import os
from sklearn import svm
from PIL import Image
from numpy import array
from utils import *
clf = None
def get_image_fit_data(dir_name):
"""读取labeled_images文件夹的图片,返回图 | X = []
Y = []
name_list = os.listdir(dir_name)
for name in name_list:
if not os.path.isdir(os.path.join(dir_name, name)):
continue
image_files = os.listdir(os.path.join(dir_name, name))
for img in image_files:
i = Image.open(os.path.join(dir_name, na... | 片的特征矩阵及相应标记"""
| identifier_name |
resource_task.rs | ://mozilla.org/MPL/2.0/. */
//! A task that takes a URL and streams back the binary data.
use about_loader;
use data_loader;
use file_loader;
use http_loader;
use cookie_storage::CookieStorage;
use cookie;
use mime_classifier::MIMEClassifier;
use net_traits::{ControlMsg, LoadData, LoadResponse, LoadConsumer, CookieS... | (&self, host: &str) -> bool {
self.hsts_list.lock().unwrap().is_host_secure(host)
}
fn load(&mut self, mut load_data: LoadData, consumer: LoadConsumer) {
self.user_agent.as_ref().map(|ua| {
load_data.preserved_headers.set(UserAgent(ua.clone()));
});
fn from_factory(... | is_host_sts | identifier_name |
resource_task.rs | ://mozilla.org/MPL/2.0/. */
//! A task that takes a URL and streams back the binary data.
use about_loader;
use data_loader;
use file_loader;
use http_loader;
use cookie_storage::CookieStorage;
use cookie;
use mime_classifier::MIMEClassifier;
use net_traits::{ControlMsg, LoadData, LoadResponse, LoadConsumer, CookieS... | match result {
Ok(_) => Ok(ProgressSender::Channel(progress_chan)),
Err(_) => Err(())
}
}
LoadConsumer::Listener(target) => {
target.invoke_with_listener(ResponseAction::HeadersAvailable(metadata));
Ok(ProgressSender::Listen... | let result = start_chan.send(LoadResponse {
metadata: metadata,
progress_port: progress_port,
}); | random_line_split |
stats.rs | // Copyright (c) 2015-2017 Ivo Wetzel
// 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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except accordi... |
/// Returns the calculated averages from the last tick.
pub fn average(&self) -> Stats {
self.averages
}
/// Resets the internal data used for average calculation, but does not
/// reset the last calculated averages.
pub fn reset(&mut self) {
self.averages.bytes_sent = 0;
... |
/// Steps the internal tick value used for average calculation.
pub fn tick(&mut self) {
self.tick = (self.tick + 1) % (self.config.send_rate + 1);
} | random_line_split |
stats.rs | // Copyright (c) 2015-2017 Ivo Wetzel
// 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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except accordi... | (config: Config) -> StatsCollector {
StatsCollector {
tick: 0,
config: config,
buckets: (0..config.send_rate + 1).map(|_| {
Stats::default()
}).collect::<Vec<Stats>>(),
averages: Stats::default()
}
}
/// Overrides the ... | new | identifier_name |
stats.rs | // Copyright (c) 2015-2017 Ivo Wetzel
// 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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except accordi... |
/// Sets the number of bytes sent for the current tick.
pub fn set_bytes_sent(&mut self, bytes: u32) {
let old_index = (self.tick as i32 + 1) % (self.config.send_rate + 1) as i32;
let old_bytes = self.buckets[old_index as usize].bytes_sent;
self.averages.bytes_sent = (self.averages.byt... | {
self.config = config;
self.buckets = (0..config.send_rate + 1).map(|_| {
Stats::default()
}).collect::<Vec<Stats>>()
} | identifier_body |
controller.js | fs = require('fs');
function ControllerObject(command, mediaName){
this.command = command;
this.mediaName = mediaName;
};
var Search = require('./apiSearch.js') | newSearch.tweets(this.command, this.mediaName, this.display2Console, this.write2File);
};
ControllerObject.prototype.getSong = function(){
if(this.mediaName == ''){this.mediaName = 'the sign ace of base'};
newSearch.song(this.command, this.mediaName, this.display2Console, this.write2File);
};
ControllerObject.... | var newSearch = new Search();
ControllerObject.prototype.getTweets = function(){ | random_line_split |
controller.js | fs = require('fs');
function | (command, mediaName){
this.command = command;
this.mediaName = mediaName;
};
var Search = require('./apiSearch.js')
var newSearch = new Search();
ControllerObject.prototype.getTweets = function(){
newSearch.tweets(this.command, this.mediaName, this.display2Console, this.write2File);
};
ControllerObject.prototy... | ControllerObject | identifier_name |
controller.js | fs = require('fs');
function ControllerObject(command, mediaName) | ;
var Search = require('./apiSearch.js')
var newSearch = new Search();
ControllerObject.prototype.getTweets = function(){
newSearch.tweets(this.command, this.mediaName, this.display2Console, this.write2File);
};
ControllerObject.prototype.getSong = function(){
if(this.mediaName == ''){this.mediaName = 'the sign ... | {
this.command = command;
this.mediaName = mediaName;
} | identifier_body |
gymnast.service.spec.ts | import { Test, TestingModule } from '@nestjs/testing';
import { GymnastService } from './gymnast.service';
import { Repository } from 'typeorm';
import { Gymnast } from './gymnast.model';
import { PubSub } from 'graphql-subscriptions';
export class | extends Repository<Gymnast> { }
describe('GymnastService', () => {
let service: GymnastService;
beforeAll(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
GymnastService,
{ provide: 'GymnastRepository', useClass: GymnastRepository },
{ pr... | GymnastRepository | identifier_name |
gymnast.service.spec.ts | import { Test, TestingModule } from '@nestjs/testing';
import { GymnastService } from './gymnast.service';
import { Repository } from 'typeorm';
import { Gymnast } from './gymnast.model';
import { PubSub } from 'graphql-subscriptions';
export class GymnastRepository extends Repository<Gymnast> { }
describe('GymnastSe... | }).compile();
service = module.get<GymnastService>(GymnastService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
}); | { provide: 'PubSubInstance', useValue: new PubSub() }
], | random_line_split |
segment.py | """ :mod:`eleve.segment`
==========================
The segmenter is available by importing ``eleve.Segmenter``. It is used to
segment sentences (regroup tokens that goes together).
"""
import logging
from math import isnan
logger = logging.getLogger(__name__)
class Segmenter:
def __init__(self, storage, max_... | (sent):
return " ".join([c for w in sent for c in Segmenter.tokenInWord(w)])
def segmentSentenceTIW(self, sent: str) -> str:
return Segmenter.formatSentenceTokenInWord(self.segment(tuple(sent.split(" "))))
def segmentSentenceTIWBIES(self, sent:str) -> str:
tokens = tuple(sent.split("... | formatSentenceTokenInWord | identifier_name |
segment.py | """ :mod:`eleve.segment`
==========================
The segmenter is available by importing ``eleve.Segmenter``. It is used to
segment sentences (regroup tokens that goes together).
"""
import logging
from math import isnan
logger = logging.getLogger(__name__)
class Segmenter:
def __init__(self, storage, max_... | bies.append(i + "-I")
bies.append(w[-1] + "-E")
return " ".join(bies) | for i in w[1:-1]: | random_line_split |
segment.py | """ :mod:`eleve.segment`
==========================
The segmenter is available by importing ``eleve.Segmenter``. It is used to
segment sentences (regroup tokens that goes together).
"""
import logging
from math import isnan
logger = logging.getLogger(__name__)
class Segmenter:
def __init__(self, storage, max_... | logger.warning(
"consider n-grams of size %d at max, BUT storage backend has a default ngram length of %s."
% (max_ngram_length, storage.default_ngram_length)
)
self.max_ngram_length = max_ngram_length
def segment(self, sentence):... | """ Create a segmenter.
:param storage: A storage object that has been trained on a corpus (should have a ``query_autonomy`` method).
:param max_ngram_length: The maximum length of n-gram that can be "merged".
It should be strictly smaller to the storage's n-gram length.
"""
... | identifier_body |
segment.py | """ :mod:`eleve.segment`
==========================
The segmenter is available by importing ``eleve.Segmenter``. It is used to
segment sentences (regroup tokens that goes together).
"""
import logging
from math import isnan
logger = logging.getLogger(__name__)
class Segmenter:
def __init__(self, storage, max_... |
# keep the best segmentation and remove the None
best_segmentation = best_segmentation[len(sentence)]
best_segmentation = list(filter(None, best_segmentation))
# best_segmentation.pop(0)
# best_segmentation.pop()
return best_segmentation
def segment_nbest(self, se... | for j in range(1, order + 1):
if i - j < 0:
break
a = query_autonomy(sentence[i - j : i])
if isnan(a):
a = -100.0
score = best_score[i - j] + a * j
if score > best_score[i]:
best_s... | conditional_block |
config.js | /*************************************************************
*
* MathJax/jax/output/HTML-CSS/config.js
*
* Initializes the HTML-CCS OutputJax (the main definition is in
* MathJax/jax/input/HTML-CSS/jax.js, which is loaded when needed).
*
* ---------------------------------------------------------... | HUB.Startup.signal.Post("MathJax not supported");
}
},MathJax.Hub,MathJax.OutputJax["HTML-CSS"]]);
MathJax.OutputJax["HTML-CSS"].loadComplete("config.js"); | if (HUB.Browser.version !== "0.0" &&
!HUB.Browser.versionAtLeast(CONFIG.minBrowserVersion[HUB.Browser]||0.0)) {
HTMLCSS.Translate = CONFIG.minBrowserTranslate;
HUB.Config({showProcessingMessages: false});
MathJax.Message.Set("Your browser does not support MathJax",null,4000);
| random_line_split |
config.js | /*************************************************************
*
* MathJax/jax/output/HTML-CSS/config.js
*
* Initializes the HTML-CCS OutputJax (the main definition is in
* MathJax/jax/input/HTML-CSS/jax.js, which is loaded when needed).
*
* ---------------------------------------------------------... |
MathJax.Hub.Register.StartupHook("End Config",[function (HUB,HTMLCSS) {
var CONFIG = HUB.Insert({
//
// The minimum versions that HTML-CSS supports
//
minBrowserVersion: {
Firefox: 3.0,
Opera: 9.52,
MSIE: 6.0,
Chrome: 0.3,
Safari: 2.0,
Konqueror: 4... | {MathJax.OutputJax["HTML-CSS"].Register("jax/mml")} | conditional_block |
test_loaders.py | # AMDG
import unittest
from datetime import datetime
from balance import BasicLoader, RepayLoader
from base_test import BaseTest
class | (BaseTest, unittest.TestCase):
def test_basic_loader(self):
loader = BasicLoader('tests/data/basic_loader')
entries, errors = loader.load(return_errors=True)
self.assertEquals(1, len(entries))
entry = entries[0]
self.assertEquals(-5.00, entry.amount)
self.assertEquals... | LoaderTests | identifier_name |
test_loaders.py | # AMDG
import unittest
from datetime import datetime
from balance import BasicLoader, RepayLoader
from base_test import BaseTest
class LoaderTests(BaseTest, unittest.TestCase):
def test_basic_loader(self):
loader = BasicLoader('tests/data/basic_loader')
entries, errors = loader.load(return_errors=... | unittest.main() | conditional_block | |
test_loaders.py | # AMDG
import unittest
from datetime import datetime
from balance import BasicLoader, RepayLoader
from base_test import BaseTest
class LoaderTests(BaseTest, unittest.TestCase):
def test_basic_loader(self):
loader = BasicLoader('tests/data/basic_loader')
entries, errors = loader.load(return_errors=... | self.assertEquals('repay', entry.category)
self.assertEquals('#2', entry.description)
self.assertEquals('Joe', entry.vendor)
self.assertEquals('cash', entry.method)
self.assertEquals(datetime(2014,10,3), entry.date)
for e in entries:
self.assertTrue(e.method i... | random_line_split | |
test_loaders.py | # AMDG
import unittest
from datetime import datetime
from balance import BasicLoader, RepayLoader
from base_test import BaseTest
class LoaderTests(BaseTest, unittest.TestCase):
def test_basic_loader(self):
loader = BasicLoader('tests/data/basic_loader')
entries, errors = loader.load(return_errors=... |
if __name__ == '__main__':
unittest.main()
| loader = RepayLoader('tests/data/repay_loader')
entries, errors = loader.load(return_errors=True)
self.assertEquals(4, len(entries))
entry = entries.pop()
self.assertEquals(-11.00, entry.amount)
self.assertEquals('repay', entry.category)
self.assertEquals('#2', entry.desc... | identifier_body |
rx.coincidence-lite.d.ts | // DefinitelyTyped: partial
// This file contains common part of defintions for rx.time.d.ts and rx.lite.d.ts
|
///<reference path="rx-lite.d.ts" />
declare module Rx {
interface Observable<T> {
/**
* Returns a new observable that triggers on the second and subsequent triggerings of the input observable.
* The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pai... | // Do not include the file separately.
| random_line_split |
qa_probe_avg_mag_sqrd.py | #!/usr/bin/env python
#
# Copyright 2012,2013 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
import math
from gnuradio import gr, gr_unittest, analog, blocks
def avg_mag_sqrd_c(x, alpha):
y = [0, ]
for xi in x:
tmp = alpha * (xi.r... | src = blocks.vector_source_c(src_data)
op = analog.probe_avg_mag_sqrd_cf(0, alpha)
dst = blocks.vector_sink_f()
self.tb.connect(src, op)
self.tb.connect(op, dst)
self.tb.run()
result_data = dst.data()
self.assertComplexTuplesAlmostEqual(expected_result, ... | random_line_split | |
qa_probe_avg_mag_sqrd.py | #!/usr/bin/env python
#
# Copyright 2012,2013 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
import math
from gnuradio import gr, gr_unittest, analog, blocks
def avg_mag_sqrd_c(x, alpha):
y = [0, ]
for xi in x:
tmp = alpha * (xi.r... | (gr_unittest.TestCase):
def setUp(self):
self.tb = gr.top_block()
def tearDown(self):
self.tb = None
def test_c_001(self):
alpha = 0.0001
src_data = [
1.0 + 1.0j,
2.0 + 2.0j,
3.0 + 3.0j,
4.0 + 4.0j,
5.0 + 5.0j,
... | test_probe_avg_mag_sqrd | identifier_name |
qa_probe_avg_mag_sqrd.py | #!/usr/bin/env python
#
# Copyright 2012,2013 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
import math
from gnuradio import gr, gr_unittest, analog, blocks
def avg_mag_sqrd_c(x, alpha):
y = [0, ]
for xi in x:
tmp = alpha * (xi.r... |
class test_probe_avg_mag_sqrd(gr_unittest.TestCase):
def setUp(self):
self.tb = gr.top_block()
def tearDown(self):
self.tb = None
def test_c_001(self):
alpha = 0.0001
src_data = [
1.0 + 1.0j,
2.0 + 2.0j,
3.0 + 3.0j,
4.0 + ... | y = [0, ]
for xi in x:
tmp = alpha * (xi * xi) + (1 - alpha) * y[-1]
y.append(tmp)
return y | identifier_body |
qa_probe_avg_mag_sqrd.py | #!/usr/bin/env python
#
# Copyright 2012,2013 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
import math
from gnuradio import gr, gr_unittest, analog, blocks
def avg_mag_sqrd_c(x, alpha):
y = [0, ]
for xi in x:
tmp = alpha * (xi.r... |
return y
class test_probe_avg_mag_sqrd(gr_unittest.TestCase):
def setUp(self):
self.tb = gr.top_block()
def tearDown(self):
self.tb = None
def test_c_001(self):
alpha = 0.0001
src_data = [
1.0 + 1.0j,
2.0 + 2.0j,
3.0 + 3.0j,
... | tmp = alpha * (xi * xi) + (1 - alpha) * y[-1]
y.append(tmp) | conditional_block |
lib.rs | //! Clients for comunicating with a [Kafka](http://kafka.apache.org/)
//! cluster. These are:
//!
//! - `kafka::producer::Producer` - for sending message to Kafka
//! - `kafka::consumer::Consumer` - for retrieving/consuming messages from Kafka
//! - `kafka::client::KafkaClient` - a lower-level, general purpose client ... | where J: AsRef<client::ProduceMessage<'a, 'b>>, I: IntoIterator<Item=J>;
} | &mut self, ack: client::RequiredAcks, ack_timeout: i32, messages: I)
-> Result<Vec<client::TopicPartitionOffset>> | random_line_split |
test_ossaudiodev.py | from test import test_support
test_support.requires('audio')
from test.test_support import verbose, findfile, TestFailed, TestSkipped
import errno
import fcntl
import ossaudiodev
import os
import sys
import select
import sunaudio
import time
import audioop
# Arggh, AFMT_S16_NE not defined on all platforms -- seems t... |
SND_FORMAT_MULAW_8 = 1
def read_sound_file(path):
fp = open(path, 'rb')
size, enc, rate, nchannels, extra = sunaudio.gethdr(fp)
data = fp.read()
fp.close()
if enc != SND_FORMAT_MULAW_8:
print "Expect .au file with 8-bit mu-law samples"
return
# Convert the data to 16-bit si... | AFMT_S16_NE = ossaudiodev.AFMT_S16_BE | conditional_block |
test_ossaudiodev.py | from test import test_support
test_support.requires('audio')
from test.test_support import verbose, findfile, TestFailed, TestSkipped
import errno
import fcntl
import ossaudiodev
import os
import sys
import select
import sunaudio
import time
import audioop
# Arggh, AFMT_S16_NE not defined on all platforms -- seems t... | % expected_time)
t1 = time.time()
dsp.write(data)
dsp.close()
t2 = time.time()
elapsed_time = t2 - t1
percent_diff = (abs(elapsed_time - expected_time) / expected_time) * 100
_assert(percent_diff <= 10.0, \
("elapsed time (%.2f sec) > 10%% off of expected time (%.2f s... | print ("playing test sound file (expected running time: %.2f sec)" | random_line_split |
test_ossaudiodev.py | from test import test_support
test_support.requires('audio')
from test.test_support import verbose, findfile, TestFailed, TestSkipped
import errno
import fcntl
import ossaudiodev
import os
import sys
import select
import sunaudio
import time
import audioop
# Arggh, AFMT_S16_NE not defined on all platforms -- seems t... | (expr, message=None):
if not expr:
raise AssertionError(message or "assertion failed")
def play_sound_file(data, rate, ssize, nchannels):
try:
dsp = ossaudiodev.open('w')
except IOError, msg:
if msg[0] in (errno.EACCES, errno.ENOENT, errno.ENODEV, errno.EBUSY):
raise Tes... | _assert | identifier_name |
test_ossaudiodev.py | from test import test_support
test_support.requires('audio')
from test.test_support import verbose, findfile, TestFailed, TestSkipped
import errno
import fcntl
import ossaudiodev
import os
import sys
import select
import sunaudio
import time
import audioop
# Arggh, AFMT_S16_NE not defined on all platforms -- seems t... | for attr in ('closed', 'name', 'mode'):
try:
setattr(dsp, attr, 42)
raise RuntimeError("dsp.%s not read-only" % attr)
except TypeError:
pass
# Compute expected running time of sound sample (in seconds).
expected_time = float(len(data)) / (ssize/8) / nchan... | try:
dsp = ossaudiodev.open('w')
except IOError, msg:
if msg[0] in (errno.EACCES, errno.ENOENT, errno.ENODEV, errno.EBUSY):
raise TestSkipped, msg
raise TestFailed, msg
# at least check that these methods can be invoked
dsp.bufsize()
dsp.obufcount()
dsp.obuffree(... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.