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
commands.py
import re, shlex import hangups from hangupsbot.utils import text_to_segments from hangupsbot.handlers import handler, StopEventHandling from hangupsbot.commands import command default_bot_alias = '/bot' def find_bot_alias(aliases_list, text): """Return True if text starts with bot alias""" command = text...
# Get list of bot aliases aliases_list = bot.get_config_suboption(event.conv_id, 'commands_aliases') if not aliases_list: aliases_list = [default_bot_alias] # Test if message starts with bot alias if not find_bot_alias(aliases_list, event.text): return # Test if command handl...
return
conditional_block
commands.py
import re, shlex import hangups from hangupsbot.utils import text_to_segments from hangupsbot.handlers import handler, StopEventHandling from hangupsbot.commands import command default_bot_alias = '/bot' def find_bot_alias(aliases_list, text): """Return True if text starts with bot alias""" command = text...
# Get list of bot aliases aliases_list = bot.get_config_suboption(event.conv_id, 'commands_aliases') if not aliases_list: aliases_list = [default_bot_alias] # Test if message starts with bot alias if not find_bot_alias(aliases_list, event.text): return # Test if command handlin...
random_line_split
compiletest.rs
N-TARGET"), reqopt("", "mode", "which sort of compile tests to run", "(compile-fail|run-fail|run-pass|run-pass-valgrind|pretty|debug-info)"), optflag("", "ignored", "run tests marked as ignored"), optopt("", "runtool", "supervisor program to run tests under \ ...
<'a>(maybestr: &'a Option<String>) -> &'a str { match *maybestr { None => "(none)", Some(ref s) => s, } } pub fn opt_str2(maybestr: Option<String>) -> String { match maybestr { None => "(none)".to_string(), Some(s) => s, } } pub fn run_tests(config: &Config) { if co...
opt_str
identifier_name
compiletest.rs
&groups)); println!(""); panic!() } fn opt_path(m: &getopts::Matches, nm: &str) -> Path { match m.opt_str(nm) { Some(s) => Path::new(s), None => panic!("no option (=path) found for {}", nm), } } let filter = if !matches.free.is_empty() { ...
{ let filename = path.filename_str(); let p = path.dir_path(); let dir = p.filename_str(); format!("{}/{}", dir.unwrap_or(""), filename.unwrap_or("")) }
identifier_body
compiletest.rs
("adb-test-dir")), opt_str2(matches.opt_str("target"))), adb_device_status: opt_str2(matches.opt_str("target")).contains("android") && "(none)" != opt_str2(matches.opt_str("adb-test-dir")) && !opt_str2(matches.opt_str("adb-test-dir")).is_empty(), lldb_pyth...
full_version_line); None
random_line_split
User.js
"use strict"; const mongoose = require('mongoose'); const Schema = mongoose.Schema; const userSchema = new Schema({ /* * The UTC datetime that the user account was created on Twitter. * * Example: "created_at": "Mon Nov 29 21:18:15 +0000 2010" */ created_at: String, /* * When tru...
* The number of public lists that this user is a member of. */ listed_count: Number, /* * Nullable. The user-defined location for this accountโ€™s profile. * Not necessarily a location nor parseable. * This field will occasionally be fuzzily interpreted by the Search service. * ...
* May or may not have anything to do with the content of their Tweets. */ lang: String, /*
random_line_split
test_security.py
# Copyright 2012-2015 Mattias Fliesberg # # This file is part of opmuse. # # opmuse is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later versi...
def setup_method(self): setup_db(self) def teardown_method(self): teardown_db(self) def test_login(self): user = self.session.query(User).filter_by(login="admin").one() hashed = hash_password("admin", user.salt) assert hashed == user.password hashed = hash_pa...
identifier_body
test_security.py
# Copyright 2012-2015 Mattias Fliesberg # # This file is part of opmuse. # # opmuse is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later versi...
hashed = hash_password("admin", user.salt) assert hashed == user.password hashed = hash_password("wrong", user.salt) assert hashed != user.password
random_line_split
test_security.py
# Copyright 2012-2015 Mattias Fliesberg # # This file is part of opmuse. # # opmuse is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later versi...
(self): user = self.session.query(User).filter_by(login="admin").one() hashed = hash_password("admin", user.salt) assert hashed == user.password hashed = hash_password("wrong", user.salt) assert hashed != user.password
test_login
identifier_name
Mooc.js
import React from 'react'; import { Link } from 'react-router-dom'; import Main from '../layouts/Main'; import data from '../data/mooc'; const tableStyle = { border: '1px solid black', borderCollapse: 'collapse', textAlign: 'center', width: '100%' } const tdStyle = { // border: '1px solid #85C1E9...
<th style={thStyle}>#</th> <th style={thStyle}>Name</th> <th style={thStyle}>Year</th> <th style={thStyle}>Platform</th> </tr> {data.map(({ id, name, year, platform, href }) => ( <tr key={id}> <td style={tdStyl...
<div> <table style={tableStyle}> <tbody> <tr>
random_line_split
fast_nonprogressive_emojipicker_test.js
.events'); goog.require('goog.events.EventType'); goog.require('goog.net.EventType'); goog.require('goog.style'); goog.require('goog.testing.AsyncTestCase'); goog.require('goog.testing.jsunit'); goog.require('goog.ui.emoji.Emoji'); goog.require('goog.ui.emoji.EmojiPicker'); goog.require('goog.ui.emoji.SpriteInfo'); goo...
var url = emojiInfo[0]; // url of the animated emoji var spriteInfo = emojiInfo[2]; if (spriteInfo) { assertEquals(inner.tagName, 'DIV'); if (spriteInfo.isAnimated()) { var img = images[id]; checkPathsEndWithSameFile( goog.style.getStyle(inner, 'background-image'), ...
// Now check the contents of the cells
random_line_split
fast_nonprogressive_emojipicker_test.js
.events'); goog.require('goog.events.EventType'); goog.require('goog.net.EventType'); goog.require('goog.style'); goog.require('goog.testing.AsyncTestCase'); goog.require('goog.testing.jsunit'); goog.require('goog.ui.emoji.Emoji'); goog.require('goog.ui.emoji.EmojiPicker'); goog.require('goog.ui.emoji.SpriteInfo'); goo...
else { checkPathsEndWithSameFile( goog.style.getStyle(inner, 'background-image'), spriteInfo.getUrl()); assertEquals(spriteInfo.getWidthCssValue(), goog.style.getStyle(inner, 'width')); assertEquals(spriteInfo.getHeightCssValue(), go...
{ assertTrue('Sprite should have its CSS class set', goog.dom.classlist.contains(inner, cssClass)); }
conditional_block
fast_nonprogressive_emojipicker_test.js
.events'); goog.require('goog.events.EventType'); goog.require('goog.net.EventType'); goog.require('goog.style'); goog.require('goog.testing.AsyncTestCase'); goog.require('goog.testing.jsunit'); goog.require('goog.ui.emoji.Emoji'); goog.require('goog.ui.emoji.EmojiPicker'); goog.require('goog.ui.emoji.SpriteInfo'); goo...
assertEquals(inner.tagName, 'DIV'); if (spriteInfo.isAnimated()) { var img = images[id]; checkPathsEndWithSameFile( goog.style.getStyle(inner, 'background-image'), url); assertEquals(String(img.width), goog.style.getStyle(inner, 'width'). replace(/...
{ for (var i = 0; i < emoji[1].length; i++) { palette.setSelectedIndex(i); var emojiInfo = emoji[1][i]; var cell = palette.getSelectedItem(); var id = cell.getAttribute(goog.ui.emoji.Emoji.ATTRIBUTE); var inner = /** @type {Element} */ (cell.firstChild); // Check that the cell is a div wrappe...
identifier_body
fast_nonprogressive_emojipicker_test.js
.events'); goog.require('goog.events.EventType'); goog.require('goog.net.EventType'); goog.require('goog.style'); goog.require('goog.testing.AsyncTestCase'); goog.require('goog.testing.jsunit'); goog.require('goog.ui.emoji.Emoji'); goog.require('goog.ui.emoji.EmojiPicker'); goog.require('goog.ui.emoji.SpriteInfo'); goo...
(path1, path2) { var pieces1 = path1.split('/'); var file1 = pieces1[pieces1.length - 1]; var pieces2 = path2.split('/'); var file2 = pieces2[pieces2.length - 1]; return file1 == file2; } /** * Checks and verifies the structure of a non-progressive fast-loading picker * after the animated emoji have load...
checkPathsEndWithSameFile
identifier_name
__init__.py
# -*- encoding: utf-8 -*- ################################################################################ # # # Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol # # ...
# (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of ...
random_line_split
query.py
from ..base import BaseQuery class LexiconQuery(BaseQuery): def __init__(self, corpus, to_find): super(LexiconQuery, self).__init__(corpus, to_find) def create_subset(self, label): """ Set properties of the returned tokens. """ labels_to_add = [] if self.to_fin...
def set_properties(self, **kwargs): """ Set properties of the returned tokens. """ props_to_remove = [] props_to_add = [] for k, v in kwargs.items(): if v is None: props_to_remove.append(k) else: if not self.co...
""" removes all token labels""" super(LexiconQuery, self).remove_subset(label) self.corpus.hierarchy.remove_type_labels(self.corpus, self.to_find.node_type, [label])
identifier_body
query.py
from ..base import BaseQuery class LexiconQuery(BaseQuery): def __init__(self, corpus, to_find): super(LexiconQuery, self).__init__(corpus, to_find) def create_subset(self, label): """ Set properties of the returned tokens. """ labels_to_add = [] if self.to_fin...
self.corpus.hierarchy.remove_type_properties(self.corpus, self.to_find.node_type, props_to_remove)
conditional_block
query.py
from ..base import BaseQuery class LexiconQuery(BaseQuery): def
(self, corpus, to_find): super(LexiconQuery, self).__init__(corpus, to_find) def create_subset(self, label): """ Set properties of the returned tokens. """ labels_to_add = [] if self.to_find.node_type not in self.corpus.hierarchy.subset_types or \ ...
__init__
identifier_name
query.py
from ..base import BaseQuery class LexiconQuery(BaseQuery): def __init__(self, corpus, to_find): super(LexiconQuery, self).__init__(corpus, to_find) def create_subset(self, label): """ Set properties of the returned tokens. """ labels_to_add = [] if self.to_fin...
props_to_add.append((k, type(kwargs[k]))) super(LexiconQuery, self).set_properties(**kwargs) if props_to_add: self.corpus.hierarchy.add_type_properties(self.corpus, self.to_find.node_type, props_to_add) if props_to_remove: self.corpus.hierarchy.remove_...
if not self.corpus.hierarchy.has_type_property(self.to_find.node_type, k):
random_line_split
bit_distributor.rs
incremented to create the next pair. In this case, the pairs will be /// $(0, 0), (0, 1), (1, 0), (1, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 0), (2, 1), \ldots$. /// /// If you think of these pairs as coordinates in the $xy$-plane, they are traversed along a Z-order /// curve. Every pair of unsigned integers will be ...
/// if `max_bits` wasn't specified, but will stop growing once it reaches $2^b-1$. #[derive(Clone, Debug, Eq, PartialEq, Hash)] pub struct BitDistributor { pub output_types: Vec<BitDistributorOutputType>, bit_map: [usize; COUNTER_WIDTH], counter: [bool; COUNTER_WIDTH], } impl BitDistributor { fn new_wi...
/// type. But if `max_bits` is set to $b$, then the corresponding element will start growing just as
random_line_split
bit_distributor.rs
to create the next pair. In this case, the pairs will be /// $(0, 0), (0, 1), (1, 0), (1, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 0), (2, 1), \ldots$. /// /// If you think of these pairs as coordinates in the $xy$-plane, they are traversed along a Z-order /// curve. Every pair of unsigned integers will be generated ex...
else { ni -= 1; } weight_counter = self.output_types[normal_output_type_indices[ni]].weight; } } else { if tiny_output_type_indices.is_empty() { self.bit_map[i] = usize::MAX; ...
{ ni = normal_output_type_indices.len() - 1; }
conditional_block
bit_distributor.rs
to create the next pair. In this case, the pairs will be /// $(0, 0), (0, 1), (1, 0), (1, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 0), (2, 1), \ldots$. /// /// If you think of these pairs as coordinates in the $xy$-plane, they are traversed along a Z-order /// curve. Every pair of unsigned integers will be generated ex...
fn update_bit_map(&mut self) { let (mut normal_output_type_indices, mut tiny_output_type_indices): ( Vec<usize>, Vec<usize>, ) = (0..self.output_types.len()).partition(|&i| self.output_types[i].weight != 0); let mut normal_output_types_bits_used = vec![0; normal_out...
{ self.bit_map.as_ref() }
identifier_body
bit_distributor.rs
-1$. #[derive(Clone, Debug, Eq, PartialEq, Hash)] pub struct BitDistributor { pub output_types: Vec<BitDistributorOutputType>, bit_map: [usize; COUNTER_WIDTH], counter: [bool; COUNTER_WIDTH], } impl BitDistributor { fn new_without_init(output_types: &[BitDistributorOutputType]) -> BitDistributor { ...
set_max_bits
identifier_name
setlog.py
# Dict'O'nator - A dictation plugin for gedit. # Copyright (C) <2016> <Abhinav Singh> #
# (at your option) any later version. # # Dict'O'nator is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of...
# This file is part of Dict'O'nator. # # Dict'O'nator 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 3 of the License, or
random_line_split
setlog.py
# Dict'O'nator - A dictation plugin for gedit. # Copyright (C) <2016> <Abhinav Singh> # # This file is part of Dict'O'nator. # # Dict'O'nator 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 3 o...
setup_logger()
formatter = logging.Formatter('%(threadName)s - %(levelname)s - %(message)s') logger.setLevel(logging.DEBUG) # file location debug_log = LOG_DIR_PATH + 'log.txt' # adding handler for console logs sh = logging.StreamHandler() sh.setFormatter(formatter) logger.addHandler(sh) # adding han...
identifier_body
setlog.py
# Dict'O'nator - A dictation plugin for gedit. # Copyright (C) <2016> <Abhinav Singh> # # This file is part of Dict'O'nator. # # Dict'O'nator 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 3 o...
(): # setting format of log formatter = logging.Formatter('%(threadName)s - %(levelname)s - %(message)s') logger.setLevel(logging.DEBUG) # file location debug_log = LOG_DIR_PATH + 'log.txt' # adding handler for console logs sh = logging.StreamHandler() sh.setFormatter(formatter) log...
setup_logger
identifier_name
setlog.py
# Dict'O'nator - A dictation plugin for gedit. # Copyright (C) <2016> <Abhinav Singh> # # This file is part of Dict'O'nator. # # Dict'O'nator 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 3 o...
LOG_DIR_PATH = GEDIT_PLUGIN_PATH + "/.logs/" def setup_logger(): # setting format of log formatter = logging.Formatter('%(threadName)s - %(levelname)s - %(message)s') logger.setLevel(logging.DEBUG) # file location debug_log = LOG_DIR_PATH + 'log.txt' # adding handler for console logs sh...
os.makedirs(GEDIT_PLUGIN_PATH + '/.logs')
conditional_block
test_noninstantiable.py
import warnings from apification.utils import Noninstantiable, NoninstantiableMeta def test_noninstantiable(): e, o = None, None try: o = Noninstantiable() except TypeError as e: pass assert o is None assert isinstance(e, TypeError) def test_noninstantiable_keyword_self_check_invalid():...
(self, a, b=1): pass assert len(w) == 1 assert issubclass(w[0].category, SyntaxWarning) assert issubclass(C, Noninstantiable) def test_noninstantiable_keyword_self_check_valid(): C = None with warnings.catch_warnings(record=True) as w: class C(Noninstantiable): ...
func
identifier_name
test_noninstantiable.py
import warnings from apification.utils import Noninstantiable, NoninstantiableMeta def test_noninstantiable(): e, o = None, None try: o = Noninstantiable() except TypeError as e: pass assert o is None assert isinstance(e, TypeError) def test_noninstantiable_keyword_self_check_invalid():...
except TypeError as e: pass assert e is None
pass
identifier_body
test_noninstantiable.py
import warnings from apification.utils import Noninstantiable, NoninstantiableMeta def test_noninstantiable(): e, o = None, None try: o = Noninstantiable() except TypeError as e: pass assert o is None assert isinstance(e, TypeError) def test_noninstantiable_keyword_self_check_invalid():...
def test_noninstantable_inheritance(): class A(object): _allow_self_as_first_arg = True e = None try: class B(A): __metaclass__ = NoninstantiableMeta def a(self): pass except TypeError as e: pass assert e is None
random_line_split
custom_build.rs
pub fn prepare<'a, 'cfg>(cx: &mut Context<'a, 'cfg>, unit: &Unit<'a>) -> CargoResult<(Work, Work, Freshness)> { let _p = profile::start(format!("build script prepare: {}/{}", unit.pkg, unit.target.name())); let overridden = cx.build_state.has_override...
} fn build_work<'a, 'cfg>(cx: &mut Context<'a, 'cfg>, unit: &Unit<'a>) -> CargoResult<(Work, Work)> { let (script_output, build_output) = { (cx.layout(unit.pkg, Kind::Host).build(unit.pkg), cx.layout(unit.pkg, unit.kind).build_out(unit.pkg)) }; // Building the comm...
Ok((work_dirty.then(dirty), work_fresh.then(fresh), freshness))
random_line_split
custom_build.rs
pub fn prepare<'a, 'cfg>(cx: &mut Context<'a, 'cfg>, unit: &Unit<'a>) -> CargoResult<(Work, Work, Freshness)> { let _p = profile::start(format!("build script prepare: {}/{}", unit.pkg, unit.target.name())); let overridden = cx.build_state.has_override...
(path: &Path, pkg_name: &str) -> CargoResult<BuildOutput> { let contents = try!(paths::read_bytes(path)); BuildOutput::parse(&contents, pkg_name) } // Parses the output of a script. // The `pkg_name` is used for error messages. pub fn parse(input: &[u8], pkg_name: &str) -> CargoResult<B...
parse_file
identifier_name
gulpfile.js
// npm install -g gulp // npm install --save-dev gulp // npm install --save-dev gulp-uglify // npm install --save-dev gulp-concat // npm install --save-dev gulp-rename // npm install --save-dev gulp-clean // npm install --save-dev gulp-typescript // npm install --save-dev gulp-sourcemaps // npm install --save-dev gulp-...
gulp.task('scripts', function () { return gulp.src(jsFiles) .pipe(concat('build.js')) .pipe(gulp.dest('dist/lib')) .pipe(rename('build.min.js')) .pipe(uglify()) .pipe(gulp.dest('dist/lib')); }); gulp.task('clean', function () { gulp.src('dist', { read: false }) ...
random_line_split
app.js
var express = require('express') , routes = require('./routes') , user = require('./routes/user') , http = require('http') , path = require('path') , expressBundles = require('./../..') , stylus = require('stylus'); var app = express(); app.configure(function(){ app.set('port', process.env.PORT || 3000...
/** * Module dependencies. */
random_line_split
bug1132128.js
if (getJitCompilerOptions()["ion.warmup.trigger"] > 20) setJitCompilerOption("ion.warmup.trigger", 20); function callRegExpTest(i)
function callRegExpExec(i) { var s = "" + i; var re = /(\d+)/; var res = re.exec(s); assertEq(RegExp.$1, s); return res; } function callRegExpReplace(i) { var s = "" + i; var re = /(\d+)/; s.replace(re, ""); assertEq(RegExp.$1, s); } for (var i = 0; i < 60; i++) { callRegExpTest...
{ var s = "" + i; var re = /(\d+)/; re.test(s); assertEq(RegExp.$1, s); }
identifier_body
bug1132128.js
if (getJitCompilerOptions()["ion.warmup.trigger"] > 20) setJitCompilerOption("ion.warmup.trigger", 20); function callRegExpTest(i) { var s = "" + i; var re = /(\d+)/; re.test(s); assertEq(RegExp.$1, s); } function
(i) { var s = "" + i; var re = /(\d+)/; var res = re.exec(s); assertEq(RegExp.$1, s); return res; } function callRegExpReplace(i) { var s = "" + i; var re = /(\d+)/; s.replace(re, ""); assertEq(RegExp.$1, s); } for (var i = 0; i < 60; i++) { callRegExpTest(i); callRegExpExec(...
callRegExpExec
identifier_name
polymer.d.ts
// Type definitions for polymer v1.1.6 // Project: https://github.com/Polymer/polymer // Definitions by: Louis Grignon <https://github.com/lgrignon>, Suguru Inatomi <https://github.com/laco0416> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped ///<reference path="../webcomponents.js/webcomponents.js....
// Template { instanceTemplate?(template: HTMLElement): DocumentFragment; /* polymer-standard */ // Annotations $?: any; // Events listeners?: {[key:string]:string;}; listen?(node: Element, eventName: string, methodName: string): void; unlisten?(node: Element, eventName: str...
distributeContent?(): void; elementMatches?(selector: string, node?: Element): boolean;
random_line_split
board.js
; } // Continue with connection routine attempts this.info( "Serial", "Found possible serial port" + ( length > 1 ? "s" : "" ), ports.toString().grey ); // Get the first available device path from the list of // detected ports callback.call( this, port...
if ( filter ) { data[ prop ] = filter( prop, data[ prop ], device ); } } return data; }, {}); }, this) ); }; Board.prototype.serialize.blacklist = [ "board", "firmata", "_events" ]; Board.prototype.serialize.special = { mode: function(value) { retur...
data[ prop ] = special[ prop ] ? special[ prop ]( value ) : value;
random_line_split
board.js
; } // Continue with connection routine attempts this.info( "Serial", "Found possible serial port" + ( length > 1 ? "s" : "" ), ports.toString().grey ); // Get the first available device path from the list of // detected ports callback.call( this, port...
// Initialize instance property to reference firmata board this.firmata = null; // Registry of devices by pin address this.register = []; // Identify for connected hardware cache if ( !this.id ) { this.id = __.uid(); } // If no debug flag, default to false // TODO: Remove override this.debug ...
{ if ( !(this instanceof Board) ) { return new Board( opts ); } // Ensure opts is an object opts = opts || {}; var inject, timer; inject = {}; // Initialize this Board instance with // param specified properties. _.assign( this, opts ); // Easily track state of hardware this.ready = fals...
identifier_body
board.js
; } // Continue with connection routine attempts this.info( "Serial", "Found possible serial port" + ( length > 1 ? "s" : "" ), ports.toString().grey ); // Get the first available device path from the list of // detected ports callback.call( this, port...
if ( isBigEndian ) { for ( mask = 128; mask > 0; mask = mask >> 1 ) { write( value, mask ); } } else { for ( mask = 0; mask < 128; mask = mask << 1 ) { write( value, mask ); } } }; Board.prototype.log = function( /* type, module, message [, long description] */ ) { var args = [].s...
{ value = arguments[2]; isBigEndian = true; }
conditional_block
board.js
; } // Continue with connection routine attempts this.info( "Serial", "Found possible serial port" + ( length > 1 ? "s" : "" ), ports.toString().grey ); // Get the first available device path from the list of // detected ports callback.call( this, port...
( opts ) { if ( !(this instanceof Board) ) { return new Board( opts ); } // Ensure opts is an object opts = opts || {}; var inject, timer; inject = {}; // Initialize this Board instance with // param specified properties. _.assign( this, opts ); // Easily track state of hardware this.rea...
Board
identifier_name
script_msg.rs
ervoUrl, HistoryEntryReplacement), /// HTMLIFrameElement Forward or Back traversal. TraverseHistory(TraversalDirection), /// Inform the constellation of a pushed history state. PushHistoryState(HistoryStateId, ServoUrl), /// Inform the constellation of a replaced history state. ReplaceHistorySta...
pub enum JobResultValue {
random_line_split
script_msg.rs
(Debug, Deserialize, Serialize)] pub enum HistoryEntryReplacement { /// Traverse the history with replacement enabled. Enabled, /// Traverse the history with replacement disabled. Disabled, } /// Messages from the script to the constellation. #[derive(Deserialize, Serialize)] pub enum ScriptMsg { /...
{ use self::ScriptMsg::*; let variant = match *self { CompleteMessagePortTransfer(..) => "CompleteMessagePortTransfer", MessagePortTransferResult(..) => "MessagePortTransferResult", NewMessagePortRouter(..) => "NewMessagePortRouter", RemoveMessagePortRoute...
identifier_body
script_msg.rs
by web content DefaultPrevented, } /// A log entry reported to the constellation /// We don't report all log entries, just serious ones. /// We need a separate type for this because `LogLevel` isn't serializable. #[derive(Clone, Debug, Deserialize, Serialize)] pub enum LogEntry { /// Panic, with a reason and ...
{ /// Request to complete the transfer of a set of ports to a router. CompleteMessagePortTransfer(MessagePortRouterId, Vec<MessagePortId>), /// The results of attempting to complete the transfer of a batch of ports. MessagePortTransferResult( /* The router whose transfer of ports succeeded, if ...
ScriptMsg
identifier_name
impact.js
/*global Raphael:true */ var impact = function (data) { 'use strict'; var COL_WIDTH = 100, COL_SEP = 50, UNIT_HEIGHT = 10, PATH_SEP = 3, colLblAttr = {font: '9px "Arial"', stroke: 'none', fill: '#aaa'}, pathLblAttr = {font: '9px "Arial"', stroke: 'none', fill: '#fff'}, ...
function changeVal(col, id, newVal) { var bar = data.columns[col].bars.filter(function(b){return b.id === id;}); if(bar.length !== 1){ return; } bar = bar[0]; bar.value = newVal; var barIdx = data.columns[col].bars.indexOf(bar), afterBars = da...
} applyMouseEvents(id); }
random_line_split
impact.js
/*global Raphael:true */ var impact = function (data) { 'use strict'; var COL_WIDTH = 100, COL_SEP = 50, UNIT_HEIGHT = 10, PATH_SEP = 3, colLblAttr = {font: '9px "Arial"', stroke: 'none', fill: '#aaa'}, pathLblAttr = {font: '9px "Arial"', stroke: 'none', fill: '#fff'}, ...
paths[id] = paper.path().attr({fill: clr, stroke: clr}); paths[id].attr({path: path}); labels[id].toFront(); handles[id].hide(); if(currentDragging !== null){ paths[currentDragging].toFront(); labels[currentDragging].toFront(); } applyMous...
{ clr = Raphael.getColor(); }
conditional_block
impact.js
/*global Raphael:true */ var impact = function (data) { 'use strict'; var COL_WIDTH = 100, COL_SEP = 50, UNIT_HEIGHT = 10, PATH_SEP = 3, colLblAttr = {font: '9px "Arial"', stroke: 'none', fill: '#aaa'}, pathLblAttr = {font: '9px "Arial"', stroke: 'none', fill: '#fff'}, ...
function handleDragStart(){ /*jshint validthis:true */ this.oy = this.attr('cy'); currentDragging = this.data('id'); handles[this.data('id')].exclude(this); handles[this.data('id')].hide(); } function handleDragEnd(){ /*jshint validthis:true */ this...
{ /*jshint validthis:true */ if(Math.abs(dy - Math.round(dy / UNIT_HEIGHT) * UNIT_HEIGHT) < 5){ this.valueDiff = Math.max(this.data('origValue') * -1, Math.round(dy / UNIT_HEIGHT)); this.attr({cy: this.oy + this.valueDiff * UNIT_HEIGHT}); changeVal(this.data('col'), t...
identifier_body
impact.js
/*global Raphael:true */ var impact = function (data) { 'use strict'; var COL_WIDTH = 100, COL_SEP = 50, UNIT_HEIGHT = 10, PATH_SEP = 3, colLblAttr = {font: '9px "Arial"', stroke: 'none', fill: '#aaa'}, pathLblAttr = {font: '9px "Arial"', stroke: 'none', fill: '#fff'}, ...
(){ /*jshint validthis:true */ this.oy = this.attr('cy'); currentDragging = this.data('id'); handles[this.data('id')].exclude(this); handles[this.data('id')].hide(); } function handleDragEnd(){ /*jshint validthis:true */ this.data('origValue', this.data('...
handleDragStart
identifier_name
issue-64655-allow-unwind-when-calling-panic-directly.rs
// run-pass // ignore-wasm32-bare compiled with panic=abort by default // ignore-emscripten no threads support // rust-lang/rust#64655: with panic=unwind, a panic from a subroutine // should still run destructors as it unwinds the stack. However, // bugs with how the nounwind LLVM attribute was applied led to this // ...
; impl Drop for Droppable { fn drop(&mut self) { SHARED.fetch_add(1, Ordering::SeqCst); } } let _guard = Droppable; core::panicking::panic("???"); }); let wait = handle.join(); // Reinstate handler to ease observation of assertion fa...
Droppable
identifier_name
issue-64655-allow-unwind-when-calling-panic-directly.rs
// run-pass // ignore-wasm32-bare compiled with panic=abort by default // ignore-emscripten no threads support // rust-lang/rust#64655: with panic=unwind, a panic from a subroutine // should still run destructors as it unwinds the stack. However, // bugs with how the nounwind LLVM attribute was applied led to this // ...
SHARED.fetch_add(1, Ordering::SeqCst); } } let _guard = Droppable; core::panicking::panic("???"); }); let wait = handle.join(); // Reinstate handler to ease observation of assertion failures. std::panic::set_hook(old_hook); assert!(wait.is_err(...
let handle = std::thread::spawn(|| { struct Droppable; impl Drop for Droppable { fn drop(&mut self) {
random_line_split
users.js
// ## Module dependencies var mongoose = require('mongoose'); var User = require('../models/users'); // ## Posts users = { // #### List // returns list of all users list: function list(req,res) { User.find(function(err, users) { return res.json(users); }); }, // ####...
usr.save(function (err, usrS) { if (err) return res.send(500, {'flash': 'Veuillez rentrer des informations correctes' }); res.json({'flash': 'Vos informations personnelles ont bien รฉtรฉ modifiรฉs'}); req.session.user = usrS; }); }); }, ...
User.findOne(req.session.user._id, function(err, usr) { usr.firstName = newU.firstName; usr.lastName = newU.lastName; usr.phone = newU.phone;
random_line_split
notification-messages-service.js
import Ember from 'ember'; const assign = Ember.assign || Ember.merge; export default Ember.ArrayProxy.extend({ content: Ember.A(), defaultClearDuration: 3200, defaultAutoClear: false, addNotification(options) { // If no message is set, throw an error if (!options.message) { ...
() { this.set('content', Ember.A()); }, setDefaultAutoClear(autoClear) { if (Ember.typeOf(autoClear) !== 'boolean') { throw new Error('Default auto clear preference must be a boolean'); } this.set('defaultAutoClear', autoClear); }, setDefaultClearNotification(clearDu...
clearAll
identifier_name
notification-messages-service.js
import Ember from 'ember'; const assign = Ember.assign || Ember.merge; export default Ember.ArrayProxy.extend({ content: Ember.A(), defaultClearDuration: 3200, defaultAutoClear: false, addNotification(options) { // If no message is set, throw an error if (!options.message) { ...
this.set('defaultAutoClear', autoClear); }, setDefaultClearNotification(clearDuration) { if (Ember.typeOf(clearDuration) !== 'number') { throw new Error('Clear duration must be a number'); } this.set('defaultClearDuration', clearDuration); } });
{ throw new Error('Default auto clear preference must be a boolean'); }
conditional_block
notification-messages-service.js
import Ember from 'ember'; const assign = Ember.assign || Ember.merge; export default Ember.ArrayProxy.extend({ content: Ember.A(), defaultClearDuration: 3200, defaultAutoClear: false, addNotification(options) { // If no message is set, throw an error if (!options.message) { ...
}); this.pushObject(notification); if (notification.autoClear) { notification.set('remaining', notification.get('clearDuration')); this.setupAutoClear(notification); } return notification; }, // Helper methods for each type of notification ...
autoClear: (Ember.isEmpty(options.autoClear) ? this.get('defaultAutoClear') : options.autoClear), clearDuration: options.clearDuration || this.get('defaultClearDuration'), onClick: options.onClick, htmlContent: options.htmlContent || false
random_line_split
notification-messages-service.js
import Ember from 'ember'; const assign = Ember.assign || Ember.merge; export default Ember.ArrayProxy.extend({ content: Ember.A(), defaultClearDuration: 3200, defaultAutoClear: false, addNotification(options) { // If no message is set, throw an error if (!options.message) { ...
, setDefaultClearNotification(clearDuration) { if (Ember.typeOf(clearDuration) !== 'number') { throw new Error('Clear duration must be a number'); } this.set('defaultClearDuration', clearDuration); } });
{ if (Ember.typeOf(autoClear) !== 'boolean') { throw new Error('Default auto clear preference must be a boolean'); } this.set('defaultAutoClear', autoClear); }
identifier_body
sys3_process.py
# -*- coding: utf-8 -*- import win32process import win32api import win32con import ctypes import os, sys, string TH32CS_SNAPPROCESS = 0x00000002 class PROCESSENTRY32(ctypes.Structure): _fields_ = [("dwSize", ctypes.c_ulong), ("cntUsage", ctypes.c_ulong), ("th32P...
ist = getProcList() for proc in procList: count+=1 print("name=%s\tfather=%d\tid=%d" % (proc.szExeFile, proc.th32ParentProcessID, proc.th32ProcessID)) try: TempGet=GetProcessModules(proc.th32ProcessID) except Exception, e: print "pid:%d can't rea...
count = 0 procL
conditional_block
sys3_process.py
# -*- coding: utf-8 -*- import win32process import win32api import win32con import ctypes import os, sys, string TH32CS_SNAPPROCESS = 0x00000002 class PROCESSENTRY32(ctypes.Structure):
def getProcList(): CreateToolhelp32Snapshot = ctypes.windll.kernel32.CreateToolhelp32Snapshot Process32First = ctypes.windll.kernel32.Process32First Process32Next = ctypes.windll.kernel32.Process32Next CloseHandle = ctypes.windll.kernel32.CloseHandle hProcessSnap = CreateToolhel...
_fields_ = [("dwSize", ctypes.c_ulong), ("cntUsage", ctypes.c_ulong), ("th32ProcessID", ctypes.c_ulong), ("th32DefaultHeapID", ctypes.c_ulong), ("th32ModuleID", ctypes.c_ulong), ("cntThreads", ctypes.c_ulong), ...
identifier_body
sys3_process.py
# -*- coding: utf-8 -*- import win32process import win32api import win32con import ctypes import os, sys, string TH32CS_SNAPPROCESS = 0x00000002 class
(ctypes.Structure): _fields_ = [("dwSize", ctypes.c_ulong), ("cntUsage", ctypes.c_ulong), ("th32ProcessID", ctypes.c_ulong), ("th32DefaultHeapID", ctypes.c_ulong), ("th32ModuleID", ctypes.c_ulong), ("cntThreads", ctype...
PROCESSENTRY32
identifier_name
sys3_process.py
# -*- coding: utf-8 -*- import win32process import win32api import win32con import ctypes import os, sys, string TH32CS_SNAPPROCESS = 0x00000002 class PROCESSENTRY32(ctypes.Structure): _fields_ = [("dwSize", ctypes.c_ulong), ("cntUsage", ctypes.c_ulong), ("th32P...
pe32 = PROCESSENTRY32() pe32.dwSize = ctypes.sizeof(PROCESSENTRY32) if Process32First(hProcessSnap,ctypes.byref(pe32)) == False: return while True: yield pe32 if Process32Next(hProcessSnap,ctypes.byref(pe32)) == False: break CloseHandle(hProcessSna...
Process32Next = ctypes.windll.kernel32.Process32Next CloseHandle = ctypes.windll.kernel32.CloseHandle hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)
random_line_split
import_users_from_csv.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Script takes a CSV list of users and does a 'bulk' insertion into mysql. # # Copyright (C) 2009 Simone Piccardi # # 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 Softw...
# build query data for mailbox table mailbox['username']=row["user"]+'@'+row["domain"] encpass=crypt(row["password"], gen_seed(seed_len,chars)) mailbox['password'] = encpass mailbox['name'] = row["name"] mailbox['maildir'] = row["domain"]+'/'+row["user"]+'/' mailbox['local_part'] =row["use...
for i in def_alias: aliases['address']= i+'@'+row["domain"] aliases['goto']= aliases['address'] aliases['domain'] = row["domain"] if optval.has_key('-t'): print "Inserting alias" print aliases...
conditional_block
import_users_from_csv.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Script takes a CSV list of users and does a 'bulk' insertion into mysql. # # Copyright (C) 2009 Simone Piccardi # # 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 Softw...
# read and convert CSV data lista = csv.DictReader(open(args[0])) def gen_seed(seed_len, chars): return '$1$'+''.join([random.choice(chars) for _ in xrange(seed_len)])+'$' def insert_record(cursor,table,record): columns = record.keys() query = "INSERT INTO " + table + "(" + ','.join(columns) + ") VALUES ...
# Main body # NOW = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
random_line_split
import_users_from_csv.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Script takes a CSV list of users and does a 'bulk' insertion into mysql. # # Copyright (C) 2009 Simone Piccardi # # 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 Softw...
print "the 'name' column is optional, other columns will be ignored" print print "Known restrictions:" print "* this script only works with MySQL" print "* mailbox paths are hardcoded to domain/username/" # option parsing try: opts, args = getopt.getopt(sys.argv[1:], 'u:p:d:D:H:htdA') opt...
print "Usage: inspostadmusers.py [options] users.csv" print " -h print this help" print " -t test run, do not insert, just print" print " -u DB user" print " -p DB password" print " -D DB name" print " -H DB host" ...
identifier_body
import_users_from_csv.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Script takes a CSV list of users and does a 'bulk' insertion into mysql. # # Copyright (C) 2009 Simone Piccardi # # 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 Softw...
(): print "Usage: inspostadmusers.py [options] users.csv" print " -h print this help" print " -t test run, do not insert, just print" print " -u DB user" print " -p DB password" print " -D DB name" print " -H DB ho...
usage
identifier_name
moo12.slickspec.js
var setupMethods = function(specs, window){ var Element = window.Element || global.Element; global.disableNegNth = true; global.cannotDisableQSA = true; window.SELECT = function(context, selector, append){ return Element.getElements(context, selector); }; window.SELECT1 = function(context, selector){ ...
}; var verifySetupContext = function(specs, context){ describe('Verify Context',function(){ it('should set the context properly', function(){ expect(context.document).toBeDefined(); expect(context.document.nodeType).toEqual(9); var title = context.document.getElementsByTagName('title'); f...
});
random_line_split
login.rs
use std::io; use cargo::ops; use cargo::core::{MultiShell, SourceId, Source}; use cargo::sources::RegistrySource; use cargo::util::{CliResult, CliError, Config}; #[derive(RustcDecodable)] struct Options { flag_host: Option<String>, arg_token: Option<String>, flag_verbose: bool, } pub const USAGE: &'stati...
"; pub fn execute(options: Options, shell: &mut MultiShell) -> CliResult<Option<()>> { shell.set_verbose(options.flag_verbose); let token = match options.arg_token.clone() { Some(token) => token, None => { let err = (|:| { let config = try!(Config::new(shell, None, N...
-h, --help Print this message --host HOST Host to set the token for -v, --verbose Use verbose output
random_line_split
login.rs
use std::io; use cargo::ops; use cargo::core::{MultiShell, SourceId, Source}; use cargo::sources::RegistrySource; use cargo::util::{CliResult, CliError, Config}; #[derive(RustcDecodable)] struct
{ flag_host: Option<String>, arg_token: Option<String>, flag_verbose: bool, } pub const USAGE: &'static str = " Save an api token from the registry locally Usage: cargo login [options] [<token>] Options: -h, --help Print this message --host HOST Host to set the token...
Options
identifier_name
test_inverse_kinematics.py
import platform import pytest import math import numpy as np import dartpy as dart def test_solve_for_free_joint(): ''' Very simple test of InverseKinematics module, applied to a FreeJoint to ensure that the target is reachable ''' skel = dart.dynamics.Skeleton() [joint0, body0] = skel.create...
ik = body.getIK(True) solver = FailingSolver(10) ik.setSolver(solver) dofs = skel.getNumDofs() skel.resetPositions() assert not ik.solveAndApply(allowIncompleteResult=False) assert np.isclose(skel.getPositions(), np.zeros(dofs)).all() assert not ik.solveAndApply(allowIncompleteResult=...
def test_do_not_apply_solution_on_failure(): skel = dart.dynamics.Skeleton() [joint, body] = skel.createFreeJointAndBodyNodePair()
random_line_split
test_inverse_kinematics.py
import platform import pytest import math import numpy as np import dartpy as dart def test_solve_for_free_joint(): ''' Very simple test of InverseKinematics module, applied to a FreeJoint to ensure that the target is reachable ''' skel = dart.dynamics.Skeleton() [joint0, body0] = skel.create...
dim = problem.getDimension() wrong_solution = np.ones(dim) * self.constant problem.setOptimalSolution(wrong_solution) return False def getType(self): return 'FailingSolver' def clone(self): return FailingSolver(self.constant) def test_do_not_apply_solution_...
print('[FailingSolver::solve] Attempting to solve a nullptr problem! We will return false.') return False
conditional_block
test_inverse_kinematics.py
import platform import pytest import math import numpy as np import dartpy as dart def test_solve_for_free_joint(): ''' Very simple test of InverseKinematics module, applied to a FreeJoint to ensure that the target is reachable ''' skel = dart.dynamics.Skeleton() [joint0, body0] = skel.create...
(self): return FailingSolver(self.constant) def test_do_not_apply_solution_on_failure(): skel = dart.dynamics.Skeleton() [joint, body] = skel.createFreeJointAndBodyNodePair() ik = body.getIK(True) solver = FailingSolver(10) ik.setSolver(solver) dofs = skel.getNumDofs() skel.reset...
clone
identifier_name
test_inverse_kinematics.py
import platform import pytest import math import numpy as np import dartpy as dart def test_solve_for_free_joint(): ''' Very simple test of InverseKinematics module, applied to a FreeJoint to ensure that the target is reachable ''' skel = dart.dynamics.Skeleton() [joint0, body0] = skel.create...
def clone(self): return FailingSolver(self.constant) def test_do_not_apply_solution_on_failure(): skel = dart.dynamics.Skeleton() [joint, body] = skel.createFreeJointAndBodyNodePair() ik = body.getIK(True) solver = FailingSolver(10) ik.setSolver(solver) dofs = skel.getNumDofs()...
return 'FailingSolver'
identifier_body
dispatcher.py
import re import asyncio import threading from collections import defaultdict def connector(bot, dispatcher, NICK, CHANNELS, PASSWORD=None): @bot.on('client_connect') async def connect(**kwargs): bot.send('USER', user=NICK, realname=NICK) if PASSWORD: bot.send('PASS', password=PAS...
ret = func(*args, **kwargs) user_cd.lock() return ret return inner return decorator
return
conditional_block
dispatcher.py
import re import asyncio import threading from collections import defaultdict def
(bot, dispatcher, NICK, CHANNELS, PASSWORD=None): @bot.on('client_connect') async def connect(**kwargs): bot.send('USER', user=NICK, realname=NICK) if PASSWORD: bot.send('PASS', password=PASSWORD) bot.send('NICK', nick=NICK) # Don't try to join channels until the s...
connector
identifier_name
dispatcher.py
import re import asyncio import threading from collections import defaultdict def connector(bot, dispatcher, NICK, CHANNELS, PASSWORD=None): @bot.on('client_connect') async def connect(**kwargs): bot.send('USER', user=NICK, realname=NICK) if PASSWORD: bot.send('PASS', password=PAS...
user_cd = func.__cooldowns[nick] if user_cd.locked: return ret = func(*args, **kwargs) user_cd.lock() return ret return inner return decorator
random_line_split
dispatcher.py
import re import asyncio import threading from collections import defaultdict def connector(bot, dispatcher, NICK, CHANNELS, PASSWORD=None): @bot.on('client_connect') async def connect(**kwargs): bot.send('USER', user=NICK, realname=NICK) if PASSWORD: bot.send('PASS', password=PAS...
def unlock(self): self.locked = False return self.locked def cooldown(delay): def decorator(func): if not hasattr(func, "__cooldowns"): func.__cooldowns = defaultdict(lambda: Locker(delay)) def inner(*args, **kwargs): nick = args[1] user_...
if not self.locked: if self.delay > 0: self.locked = True t = threading.Timer(self.delay, self.unlock, ()) t.daemon = True t.start() return self.locked
identifier_body
structured_errors.rs
// Copyright 2018 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 ...
fn common(&self) -> DiagnosticBuilder<'tcx> { if self.expr_ty.references_error() { self.sess.diagnostic().struct_dummy() } else { self.sess.struct_span_fatal_with_code( self.span, &format!("cannot cast thin pointer `{}` to fat pointer `{}`", ...
{ __diagnostic_used!(E0607); DiagnosticId::Error("E0607".to_owned()) }
identifier_body
structured_errors.rs
// Copyright 2018 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 ...
(sess: &'tcx Session, span: Span, expr_ty: Ty<'tcx>, cast_ty: String) -> SizedUnsizedCastError<'tcx> { SizedUnsizedCastError { sess, span, expr_ty, cast_ty } } } impl<'tcx> StructuredDiagnostic<'tcx> for SizedUnsizedCastError<'tcx> { fn session(&self) -> &Se...
new
identifier_name
structured_errors.rs
// Copyright 2018 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 ...
err } fn extended(&self, mut err: DiagnosticBuilder<'tcx>) -> DiagnosticBuilder<'tcx> { err.note(&format!("certain types, like `{}`, must be cast before passing them to a \ variadic function, because of arcane ABI rules dictated by the C \ ...
{ err.help(&format!("cast the value to `{}`", self.cast_ty)); }
conditional_block
structured_errors.rs
// Copyright 2018 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 ...
} } impl<'tcx> StructuredDiagnostic<'tcx> for SizedUnsizedCastError<'tcx> { fn session(&self) -> &Session { self.sess } fn code(&self) -> DiagnosticId { __diagnostic_used!(E0607); DiagnosticId::Error("E0607".to_owned()) } fn common(&self) -> DiagnosticBuilder<'tcx> { if se...
random_line_split
CertificationRequestInfo.d.ts
declare namespace jsrsasign.KJUR.asn1.csr { /** * ASN.1 CertificationRequestInfo structure class * @param params associative array of parameters (ex. {}) * @description * ``` * // -- DEFINITION OF ASN.1 SYNTAX -- * // CertificationRequestInfo ::= SEQUENCE { * // version IN...
extends ASN1Object { constructor(); _initialize(): void; /** * set subject name field by parameter * @param x500NameParam X500Name parameter * @description * @example * csri.setSubjectByParam({'str': '/C=US/CN=b'}); * @see KJUR.asn1.x509.X...
CertificationRequestInfo
identifier_name
CertificationRequestInfo.d.ts
declare namespace jsrsasign.KJUR.asn1.csr { /** * ASN.1 CertificationRequestInfo structure class * @param params associative array of parameters (ex. {}) * @description * ``` * // -- DEFINITION OF ASN.1 SYNTAX -- * // CertificationRequestInfo ::= SEQUENCE { * // version IN...
* o.appendExtensionByName('CRLDistributionPoints', {uri: 'http://aaa.com/a.crl'}); * o.appendExtensionByName('ExtKeyUsage', {array: [{name: 'clientAuth'}]}); * o.appendExtensionByName('AuthorityKeyIdentifier', {kid: '1234ab..'}); * o.appendExtensionByName('AuthorityInfoAccess', {arra...
* o.appendExtensionByName('KeyUsage', {'bin':'11'});
random_line_split
MovieClip.d.ts
import FrameLabel from "./FrameLabel"; import Sprite from "./Sprite"; declare namespace openfl.display { /** * The MovieClip class inherits from the following classes: Sprite, * DisplayObjectContainer, InteractiveObject, DisplayObject, and * EventDispatcher. * * Unlike the Sprite object, a MovieClip ob...
extends Sprite { /** * Specifies the number of the frame in which the playhead is located in the * timeline of the MovieClip instance. If the movie clip has multiple scenes, * this value is the frame number in the current scene. */ public readonly currentFrame:number; protected get_currentFr...
MovieClip
identifier_name
MovieClip.d.ts
import FrameLabel from "./FrameLabel"; import Sprite from "./Sprite"; declare namespace openfl.display { /** * The MovieClip class inherits from the following classes: Sprite, * DisplayObjectContainer, InteractiveObject, DisplayObject, and * EventDispatcher. * * Unlike the Sprite object, a MovieClip ob...
* representing the label of the frame, to which the playhead is * sent. If you specify a number, it is relative to the scene * you specify. If you do not specify a scene, the current scene * determines the global frame number to play. If you do specify ...
random_line_split
epoll.rs
use nix::fcntl::Fd; use nix::sys::epoll::*; use nix::unistd::close; use io; use os::event::{IoEvent, Interest, PollOpt}; pub struct Selector { epfd: Fd } impl Selector { pub fn new() -> io::Result<Selector> { let epfd = try!(epoll_create().map_err(io::from_nix_error)); Ok(Selector { epfd: epf...
Ok(()) } /// Register event interests for the given IO handle with the OS pub fn register(&mut self, fd: Fd, token: usize, interests: Interest, opts: PollOpt) -> io::Result<()> { let info = EpollEvent { events: ioevent_to_epoll(interests, opts), data: token as u64 ...
let cnt = try!(epoll_wait(self.epfd, dst, timeout_ms) .map_err(io::from_nix_error)); unsafe { evts.events.set_len(cnt); }
random_line_split
epoll.rs
use nix::fcntl::Fd; use nix::sys::epoll::*; use nix::unistd::close; use io; use os::event::{IoEvent, Interest, PollOpt}; pub struct
{ epfd: Fd } impl Selector { pub fn new() -> io::Result<Selector> { let epfd = try!(epoll_create().map_err(io::from_nix_error)); Ok(Selector { epfd: epfd }) } /// Wait for events from the OS pub fn select(&mut self, evts: &mut Events, timeout_ms: usize) -> io::Result<()> { ...
Selector
identifier_name
epoll.rs
use nix::fcntl::Fd; use nix::sys::epoll::*; use nix::unistd::close; use io; use os::event::{IoEvent, Interest, PollOpt}; pub struct Selector { epfd: Fd } impl Selector { pub fn new() -> io::Result<Selector> { let epfd = try!(epoll_create().map_err(io::from_nix_error)); Ok(Selector { epfd: epf...
if interest.is_hup() { kind.insert(EPOLLRDHUP); } if opts.is_edge() { kind.insert(EPOLLET); } if opts.is_oneshot() { kind.insert(EPOLLONESHOT); } if opts.is_level() { kind.remove(EPOLLET); } kind } impl Drop for Selector { fn drop(&mut self)...
{ kind.insert(EPOLLOUT); }
conditional_block
math.rs
use std::mem; pub use vecmath::{ Vector3, Matrix4, vec3_add, vec3_sub, vec3_scale, row_mat4_mul, row_mat4_transform, mat4_transposed, mat4_inv, mat4_id, }; pub use quaternion::id as quaternion_id; pub use quaternion::mul as quaternion_mul; pub use quaternion::conj as quaternion...
if m[2][2] > m[i][i] { i = 2; } let j = next[i]; let k = next[j]; let t = (m[i][i] - (m[j][j] + m[k][k])) + 1.0; let s = inv_sqrt(t) * 0.5; q[i] = s * t; q[3] = (m[j][k] - m[k][j]) * s; q[j] = (m[i][j] + m[j][i]) * s; q[k] ...
{ i = 1; }
conditional_block
math.rs
use std::mem; pub use vecmath::{ Vector3, Matrix4, vec3_add, vec3_sub, vec3_scale, row_mat4_mul, row_mat4_transform, mat4_transposed, mat4_inv, mat4_id, }; pub use quaternion::id as quaternion_id; pub use quaternion::mul as quaternion_mul; pub use quaternion::conj as quaternion...
/// Dual-quaternion linear blending. See http://dcgi.felk.cvut.cz/home/zara/papers/TCD-CS-2006-46.pdf pub fn lerp_dual_quaternion(q1: DualQuaternion<f32>, q2: DualQuaternion<f32>, blend_factor: f32) -> DualQuaternion<f32> { let dot = dual_quaternion::dot(q1, q2); let s = 1.0 - blend_factor; let t: f32 = ...
{ let dot = q1.0 * q2.0 + q1.1[0] * q2.1[0] + q1.1[1] * q2.1[1] + q1.1[2] * q2.1[2]; let s = 1.0 - blend_factor; let t: f32 = if dot > 0.0 { *blend_factor } else { -blend_factor }; let w = s * q1.0 + t * q2.0; let x = s * q1.1[0] + t * q2.1[0]; let y = s * q1.1[1] + t * q2.1[1]; let z = s...
identifier_body
math.rs
use std::mem; pub use vecmath::{ Vector3, Matrix4, vec3_add, vec3_sub, vec3_scale, row_mat4_mul, row_mat4_transform, mat4_transposed, mat4_inv, mat4_id, }; pub use quaternion::id as quaternion_id; pub use quaternion::mul as quaternion_mul; pub use quaternion::conj as quaternion...
let mut i: i32 = unsafe { mem::transmute(y) }; i = 0x5f3759df - (i >> 1); y = unsafe { mem::transmute(i) }; y = y * (1.5 - (x2 * y * y)); y }
pub fn inv_sqrt(x: f32) -> f32 { let x2: f32 = x * 0.5; let mut y: f32 = x;
random_line_split
math.rs
use std::mem; pub use vecmath::{ Vector3, Matrix4, vec3_add, vec3_sub, vec3_scale, row_mat4_mul, row_mat4_transform, mat4_transposed, mat4_inv, mat4_id, }; pub use quaternion::id as quaternion_id; pub use quaternion::mul as quaternion_mul; pub use quaternion::conj as quaternion...
(q1: &Quaternion<f32>, q2: &Quaternion<f32>, blend_factor: &f32) -> Quaternion<f32> { let dot = q1.0 * q2.0 + q1.1[0] * q2.1[0] + q1.1[1] * q2.1[1] + q1.1[2] * q2.1[2]; let s = 1.0 - blend_factor; let t: f32 = if dot > 0.0 { *blend_factor } else { -blend_factor }; let w = s * q1.0 + t * q2.0; let...
lerp_quaternion
identifier_name
conf.py
# -*- coding: utf-8 -*- # # Bread documentation build configuration file, created by # sphinx-quickstart on Wed Aug 7 20:51:04 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All c...
# pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last...
# The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
random_line_split
setup.py
# -*- coding: utf-8 -*- import os try: from setuptools import setup except ImportError: from distutils.core import setup import sy, sy.path setup( name='sy', version=sy.__version__, url='http://sy.afajl.com', license='BSD', author='Paul Diaconescu', author_email='p@afajl.com', de...
'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: Unix', 'Programming Language :: Python', 'Topic :: System :: Systems Administration', 'Topic :: Software Development :: Libraries :: Python ...
long_description=sy.path.slurp('README.rst'), classifiers=[ 'Development Status :: 3 - Alpha',
random_line_split
index.d.ts
// Type definitions for promise-pg // Project: https://bitbucket.org/lplabs/promise-pg // Definitions by: Chris Charabaruk <http://github.com/coldacid> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference types="node" /> /// <reference types="q" /> import * as stream from 'stream'; import...
export declare class Client { constructor(connection: string); constructor(config: ClientConfig); raw: pg.Client; connect(): Q.Promise<void>; end(): Q.Promise<void>; query(queryText: string): Query; query(config: QueryConfig): Query; query(queryText: string, values: any[]): Query; ...
export declare function end(): Q.Promise<void>; export interface QueryConfig extends pg.QueryConfig { buffer?: boolean; }
random_line_split
index.d.ts
// Type definitions for promise-pg // Project: https://bitbucket.org/lplabs/promise-pg // Definitions by: Chris Charabaruk <http://github.com/coldacid> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference types="node" /> /// <reference types="q" /> import * as stream from 'stream'; import...
extends pg.Query { promise: Q.Promise<QueryResult>; }
Query
identifier_name
crypto.py
import sys from Crypto.Cipher import AES, PKCS1_OAEP from Crypto.PublicKey import RSA from Crypto import Random #AES key size AES_KEY_SIZE = 32 # Uses null character as the padding character PADDING_VALUE = '/0' def padAES(message): lacking_char_num = (AES.block_size - (len(message) % AES.block_size)) % AES.blo...
(message): # Get a random AES_BLOCK_SIZE byte key for AES aes_key = Random.new().read(AES_KEY_SIZE) # Initialization Vector iv = Random.new().read(AES.block_size) # Create a cipher using CFB mode cipher = AES.new(aes_key, AES.MODE_CFB, iv) # Encrypt the padded message encrypted_msg = ...
encryptAES
identifier_name
crypto.py
import sys from Crypto.Cipher import AES, PKCS1_OAEP from Crypto.PublicKey import RSA from Crypto import Random #AES key size AES_KEY_SIZE = 32 # Uses null character as the padding character PADDING_VALUE = '/0' def padAES(message): lacking_char_num = (AES.block_size - (len(message) % AES.block_size)) % AES.blo...
def getRSAKey(): random_generator = Random.new().read rsa_key = RSA.generate(1024, random_generator) return rsa_key def encryptRSA(message, rsaPU): # encrypted_msg = rsaPU.encrypt(message, 32)[0] return encrypted_msg def decryptRSA(ciphertext, rsa_key): msg = rsa_key.decrypt(ciphertext) ...
random_line_split
crypto.py
import sys from Crypto.Cipher import AES, PKCS1_OAEP from Crypto.PublicKey import RSA from Crypto import Random #AES key size AES_KEY_SIZE = 32 # Uses null character as the padding character PADDING_VALUE = '/0' def padAES(message): lacking_char_num = (AES.block_size - (len(message) % AES.block_size)) % AES.blo...
def decryptAES(iv, aesKey, message): #Create cipher cipher = AES.new(aesKey, AES.MODE_CFB, iv) #Decipher the message decrypted_msg = cipher.decrypt(message) # Strip padding chars decrypted_msg = decrypted_msg.rstrip(PADDING_VALUE) return decrypted_msg def getRSAKey(): random_gene...
aes_key = Random.new().read(AES_KEY_SIZE) # Initialization Vector iv = Random.new().read(AES.block_size) # Create a cipher using CFB mode cipher = AES.new(aes_key, AES.MODE_CFB, iv) # Encrypt the padded message encrypted_msg = cipher.encrypt(padAES(message)) return [iv, aes_key, encrypted...
identifier_body
msg_filterload.rs
use std; use ::serialize::{self, Serializable}; #[derive(Debug,Default,Clone)] pub struct FilterLoadMessage { pub data: Vec<u8>, pub hash_funcs: u32, pub tweak: u32, pub flags: u8, } impl super::Message for FilterLoadMessage { fn get_command(&self) -> [u8; super::message_header::COMMAND_SIZE] { su...
(&mut self, io:&mut std::io::Read, ser:&serialize::SerializeParam) -> serialize::Result { let mut r:usize = 0; r += try!(self.data.deserialize(io,ser)); r += try!(self.hash_funcs.deserialize(io,ser)); r += try!(self.tweak.deserialize(io,ser)); r += try!(self.flags.deserialize(io,ser)); ...
deserialize
identifier_name
msg_filterload.rs
use std; use ::serialize::{self, Serializable}; #[derive(Debug,Default,Clone)] pub struct FilterLoadMessage { pub data: Vec<u8>, pub hash_funcs: u32, pub tweak: u32, pub flags: u8, } impl super::Message for FilterLoadMessage { fn get_command(&self) -> [u8; super::message_header::COMMAND_SIZE] { su...
let mut r:usize = 0; r += try!(self.data.serialize(io,ser)); r += try!(self.hash_funcs.serialize(io,ser)); r += try!(self.tweak.serialize(io,ser)); r += try!(self.flags.serialize(io,ser)); Ok(r) } fn deserialize(&mut self, io:&mut std::io::Read, ser:&serialize::SerializeParam) ...
random_line_split
footer.tsx
import * as React from 'react'; import { Link } from 'react-router'; const styles: any = require('./footer.scss'); const logo: any = require('../../../content/image/logo.png'); export const FooterComponent: React.StatelessComponent<{}> = () => ( <footer className={styles.footer}> <hr className={styles.separator}...
</footer> );
</div>
random_line_split
group-types-panel.module.ts
import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { RouterModule } from '@angular/router'; import { WidgetsModule } from 'ngx-widgets'; import { TruncateModule } from 'ng2-truncate'; import { TooltipModule } from 'ngx-boots...
{ }
GroupTypesModule
identifier_name