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
vtable.py
import logging from ..analyses import AnalysesHub from . import Analysis, CFGFast l = logging.getLogger(name=__name__) class Vtable: """ This contains the addr, size and function addresses of a Vtable """ def __init__(self, vaddr, size, func_addrs=None): self.vaddr = vaddr ...
return None AnalysesHub.register_default("VtableFinder", VtableFinder)
random_line_split
vtable.py
import logging from ..analyses import AnalysesHub from . import Analysis, CFGFast l = logging.getLogger(name=__name__) class Vtable: """ This contains the addr, size and function addresses of a Vtable """ def __init__(self, vaddr, size, func_addrs=None): self.vaddr = vaddr ...
(Analysis): """ This analysis locates Vtables in a binary based on heuristics taken from - "Reconstruction of Class Hierarchies for Decompilation of C++ Programs" """ def __init__(self): if "CFGFast" not in self.project.kb.cfgs: # populate knowledge base sel...
VtableFinder
identifier_name
vtable.py
import logging from ..analyses import AnalysesHub from . import Analysis, CFGFast l = logging.getLogger(name=__name__) class Vtable: """ This contains the addr, size and function addresses of a Vtable """ def __init__(self, vaddr, size, func_addrs=None): self.vaddr = vaddr ...
def is_cross_referenced(self, addr): return addr in self.project.kb.xrefs.xrefs_by_dst def is_function(self, addr): return addr in self.project.kb.functions def analyze(self): # finding candidate starting vtable addresses # "current location is referenced from a...
if "CFGFast" not in self.project.kb.cfgs: # populate knowledge base self.project.analyses[CFGFast].prep()(cross_references=True) skip_analysis = True # check if the sections exist for sec in self.project.loader.main_object.sections: if sec.name in [".d...
identifier_body
vtable.py
import logging from ..analyses import AnalysesHub from . import Analysis, CFGFast l = logging.getLogger(name=__name__) class Vtable: """ This contains the addr, size and function addresses of a Vtable """ def __init__(self, vaddr, size, func_addrs=None): self.vaddr = vaddr ...
return list_vtables def create_extract_vtable(self, start_addr, sec_size): # using the starting address extracting the vtable # "Other elements of vtable must be unreferenced pointers to function" # "Vtable ends with the first location that is either referenced from the pro...
if sec.name in [".data.rel.ro", ".rodata", ".data.rel.ro.local"]: for offset in range(0, sec.memsize, self.project.arch.bytes): cur_addr = sec.vaddr + offset possible_func_addr = self.project.loader.memory.unpack_word( cur_addr ...
conditional_block
get-flavor.rs
// Copyright 2018 Dmitry Tantsur <divius.inside@gmail.com> // // 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 ap...
}
fn main() { panic!("This example cannot run with 'compute' feature disabled");
random_line_split
get-flavor.rs
// Copyright 2018 Dmitry Tantsur <divius.inside@gmail.com> // // 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 ap...
() { panic!("This example cannot run with 'compute' feature disabled"); }
main
identifier_name
get-flavor.rs
// Copyright 2018 Dmitry Tantsur <divius.inside@gmail.com> // // 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 ap...
#[cfg(not(feature = "compute"))] fn main() { panic!("This example cannot run with 'compute' feature disabled"); }
{ env_logger::init(); let os = openstack::Cloud::from_env() .expect("Failed to create an identity provider from the environment"); let id = env::args().nth(1).expect("Provide a flavor ID"); let flavor = os.get_flavor(id).expect("Cannot get a flavor"); println!( "ID = {}, Name = {}...
identifier_body
test-largestOfFour.js
describe('largestOfFour', function() { it('should return [27,5,39,1001] when arr is [[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]', function() { assert.deepEqual([27,5,39,1001], largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]])); }); ...
var assert = require('assert'); var largestOfFour = require('../basic/largestOfFour').largestOfFour;
random_line_split
htmlframeelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLFrameElementBinding; use dom::bindings::codegen::InheritTypes::HTMLFrame...
{ htmlelement: HTMLElement } impl HTMLFrameElementDerived for EventTarget { fn is_htmlframeelement(&self) -> bool { *self.type_id() == EventTargetTypeId::Node( NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLFrameElement))) } } impl HTMLFrameEleme...
HTMLFrameElement
identifier_name
htmlframeelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLFrameElementBinding; use dom::bindings::codegen::InheritTypes::HTMLFrame...
#[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLFrameElement> { let element = HTMLFrameElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, documen...
{ HTMLFrameElement { htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLFrameElement, localName, prefix, document) } }
identifier_body
htmlframeelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLFrameElementBinding; use dom::bindings::codegen::InheritTypes::HTMLFrame...
impl HTMLFrameElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLFrameElement { HTMLFrameElement { htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLFrameElement, localName, prefix, document) } } #[allow(un...
*self.type_id() == EventTargetTypeId::Node( NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLFrameElement))) } }
random_line_split
fast_consensus.py
""" @author waziz """ import logging import sys import traceback import os import argparse import numpy as np from functools import partial from multiprocessing import Pool from chisel.decoder import MBR, MAP, consensus from chisel.util.iotools import read_sampled_derivations, read_block, list_numbered_files from chise...
(job_desc, headers, options): # this code runs in a Pool, thus we wrap in try/except in order to have more informative exceptions jid, path = job_desc try: derivations, q_wmap, p_wmap = read_sampled_derivations(smart_ropen(path)) logging.debug('job=%d derivations=%d empdist...', jid, len(de...
make_decisions
identifier_name
fast_consensus.py
""" @author waziz """ import logging import sys import traceback import os import argparse import numpy as np from functools import partial from multiprocessing import Pool from chisel.decoder import MBR, MAP, consensus from chisel.util.iotools import read_sampled_derivations, read_block, list_numbered_files from chise...
get_yield=lambda d: d.tree.projection, empirical_q=True, alpha=1.0, beta=1.0) # TODO: make option logging.info('job=%d derivations=%d strings=%d', jid, len(derivations), len(support)) logging.debug('job=%s consensus...', jid) scorer = DecodingB...
random_line_split
fast_consensus.py
""" @author waziz """ import logging import sys import traceback import os import argparse import numpy as np from functools import partial from multiprocessing import Pool from chisel.decoder import MBR, MAP, consensus from chisel.util.iotools import read_sampled_derivations, read_block, list_numbered_files from chise...
main()
conditional_block
fast_consensus.py
""" @author waziz """ import logging import sys import traceback import os import argparse import numpy as np from functools import partial from multiprocessing import Pool from chisel.decoder import MBR, MAP, consensus from chisel.util.iotools import read_sampled_derivations, read_block, list_numbered_files from chise...
def argparse_and_config(): parser = argparse.ArgumentParser(description='Applies a decision rule to a sample.', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('config', type=str, help="configura...
jid, path = job_desc try: # make decisions ranking = make_decisions(job_desc, headers, options) # write to file if necessary with smart_wopen('{0}/{1}.gz'.format(output_dir, jid)) as out: # TODO: save nbest out.write('{0}\n'.format('\t'.join(['#target', '#p',...
identifier_body
diffuse.ts
"use strict"; import Vector from '../../general/vector'; import Color from '../../general/color'; import Halton from '../halton'; import Constant from '../constant'; import * as GeneralMaterial from './general-material'; import BRDFSample = GeneralMaterial.BRDFSample; import MaterialModel = GeneralMaterial.MaterialMod...
O = Vector.norm(O); var P: Vector = Vector.cross(N, O); var toL = Vector.plus( Vector.times(Math.cos(theta), N), Vector.plus( Vector.times(Math.sin(theta) * Math.cos(phi), O), Vector.times(Math.sin(theta) * Math.sin(phi), P)) ); ...
{ O = Vector.cross(N, y); }
conditional_block
diffuse.ts
"use strict"; import Vector from '../../general/vector'; import Color from '../../general/color'; import Halton from '../halton'; import Constant from '../constant'; import * as GeneralMaterial from './general-material'; import BRDFSample = GeneralMaterial.BRDFSample; import MaterialModel = GeneralMaterial.MaterialMod...
public nextDirection(L: Vector, N: Vector, V: Vector): BRDFSample { var u = Halton.UNIFORM(13); var v = Halton.UNIFORM(17); var theta = Math.asin(Math.sqrt(u)); var phi = Constant.PI * 2.0 * v; var z: Vector = Vector.ZUNIT; var y: Vector = Vector.YUNIT; var ...
{ return this.kd; }
identifier_body
diffuse.ts
"use strict"; import Vector from '../../general/vector'; import Color from '../../general/color'; import Halton from '../halton'; import Constant from '../constant'; import * as GeneralMaterial from './general-material'; import BRDFSample = GeneralMaterial.BRDFSample; import MaterialModel = GeneralMaterial.MaterialMod...
(L: Vector, N: Vector, V: Vector): BRDFSample { var u = Halton.UNIFORM(13); var v = Halton.UNIFORM(17); var theta = Math.asin(Math.sqrt(u)); var phi = Constant.PI * 2.0 * v; var z: Vector = Vector.ZUNIT; var y: Vector = Vector.YUNIT; var O: Vector = Vector.cross(N...
nextDirection
identifier_name
diffuse.ts
"use strict"; import Vector from '../../general/vector'; import Color from '../../general/color'; import Halton from '../halton'; import Constant from '../constant'; import * as GeneralMaterial from './general-material'; import BRDFSample = GeneralMaterial.BRDFSample; import MaterialModel = GeneralMaterial.MaterialMod...
var P: Vector = Vector.cross(N, O); var toL = Vector.plus( Vector.times(Math.cos(theta), N), Vector.plus( Vector.times(Math.sin(theta) * Math.cos(phi), O), Vector.times(Math.sin(theta) * Math.sin(phi), P)) ); L.assign(toL); ...
if (Vector.mag(O) < Constant.EPSILON) { O = Vector.cross(N, y); } O = Vector.norm(O);
random_line_split
mediaquerylist.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNul...
(&self) -> DOMString { let mut s = String::new(); self.media_query_list.to_css(&mut s).unwrap(); DOMString::from_string(s) } // https://drafts.csswg.org/cssom-view/#dom-mediaquerylist-matches fn Matches(&self) -> bool { match self.last_match_state.get() { None =>...
Media
identifier_name
mediaquerylist.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNul...
fn evaluate_changes(&self) -> MediaQueryListMatchState { let matches = self.evaluate(); let result = if let Some(old_matches) = self.last_match_state.get() { if old_matches == matches { MediaQueryListMatchState::Same(matches) } else { MediaQue...
} } impl MediaQueryList {
random_line_split
lib.rs
opy, Clone, PartialEq, PartialOrd, Debug)] pub struct LogLevel(pub u32); impl fmt::Display for LogLevel { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let LogLevel(level) = *self; match LOG_LEVEL_NAMES.get(level as usize - 1) { Some(ref name) => fmt::Display::fmt(name, fmt),...
match_default
identifier_name
lib.rs
!(level)` - returns true if logging of the given level is enabled //! //! # Enabling logging //! //! Log levels are controlled on a per-module basis, and by default all logging is //! disabled except for `error!` (a log level of 1). Logging is controlled via the //! `RUST_LOG` environment variable. The value of this en...
} } } /// This function is called directly by the compiler when using the logging /// macros. This function does not take into account whether the log level /// specified is active or not, it will always log something if this method is /// called. /// /// It is not recommended to call this function direct...
{}
conditional_block
lib.rs
!(level)` - returns true if logging of the given level is enabled //! //! # Enabling logging //! //! Log levels are controlled on a per-module basis, and by default all logging is //! disabled except for `error!` (a log level of 1). Logging is controlled via the //! `RUST_LOG` environment variable. The value of this en...
let mut logger: Box<Logger + Send> = LOCAL_LOGGER.with(|s| { s.borrow_mut().take() }).unwrap_or_else(|| { box DefaultLogger { handle: io::stderr() } }); logger.log(&LogRecord { level: LogLevel(level), args: args, file: loc.file, module_path: loc.module_pat...
{ // Test the literal string from args against the current filter, if there // is one. unsafe { let _g = LOCK.lock(); match FILTER as usize { 0 => {} 1 => panic!("cannot log after main thread has exited"), n => { let filter = mem::transmute...
identifier_body
lib.rs
environment variable is a //! comma-separated list of logging directives. A logging directive is of the form: //! //! ```text //! path::to::module=log_level //! ``` //! //! The path to the module is rooted in the name of the crate it was compiled for, //! so if your program is contained in a file `hello.rs`, for examp...
random_line_split
server.js
/** * Created by Stefan on 9/19/2017 */ /** * Created by Stefan Endres on 08/16/2017. */ 'use strict' var http = require('http'), https = require('https'), url = require('url'), util = require('util'), fs = require('fs'), path = require('path'), sessions = require('./sessions'), EventE...
return next && next(); } var self = this; var url_parts = url.parse(req.url); var requestPath = path.normalize(url_parts.pathname ).replace(/^(\.\.(\/|\\|$))+/, ''); if(requestPath === '/'){ requestPath = '/index.html' } var filePath = path.join(this.options['static'],request...
random_line_split
server.js
/** * Created by Stefan on 9/19/2017 */ /** * Created by Stefan Endres on 08/16/2017. */ 'use strict' var http = require('http'), https = require('https'), url = require('url'), util = require('util'), fs = require('fs'), path = require('path'), sessions = require('./sessions'), EventE...
(res,code) { res.statusCode = code; } function header(res, key, value) { if(typeof res.headerValues === 'undefined'){ res.headerValues = {}; } res.headerValues[key] = value } function redirect(res,url) { var address = url; var status = 302; if (arguments.length === 3) { if ...
status
identifier_name
server.js
/** * Created by Stefan on 9/19/2017 */ /** * Created by Stefan Endres on 08/16/2017. */ 'use strict' var http = require('http'), https = require('https'), url = require('url'), util = require('util'), fs = require('fs'), path = require('path'), sessions = require('./sessions'), EventE...
} LHServer.prototype.getFunctionList = function(requestPath, method) { var ret = []; if(this.options['static']) { ret.push(readStaticFile.bind(this)); } for(var i in this.fnStack) { var pathMatch = ( this.fnStack[i].options && this.fnStack[i].options.partialPath ? ...
{ try { this.viewEngine = require(value); } catch (err) { this.emit('error',err); } }
conditional_block
server.js
/** * Created by Stefan on 9/19/2017 */ /** * Created by Stefan Endres on 08/16/2017. */ 'use strict' var http = require('http'), https = require('https'), url = require('url'), util = require('util'), fs = require('fs'), path = require('path'), sessions = require('./sessions'), EventE...
function render(res,template,options,callback){ if(res.finished){ return; } var self = this; if(typeof self.viewEngine === 'undefined') { return callback && callback(); } if(self.viewEngine.renderFile) { return self.viewEngine.renderFile( (self.options['view...
{ if(res.finished){ return; } var contentType = 'text/html'; var responseBody = data; if(typeof data === 'object') { contentType = 'application/json' responseBody = JSON.stringify(data); } res.header('Content-Type', contentType) res.header('Content-Length', Buffer...
identifier_body
get_fileservers.py
class Module: def __init__(self, mainMenu, params=[]): # metadata info about the module, not modified during runtime self.info = { # name for the module that will appear in module menus 'Name': 'Get FileServers', # list of one or more authors for the module ...
def generate(self, obfuscate=False, obfuscationCommand=""): LDAPAddress = self.options['LDAPAddress']['Value'] BindDN = self.options['BindDN']['Value'] password = self.options['Password']['Value'] # the Python script itself, with the command to invoke # for execution ap...
option, value = param if option in self.options: self.options[option]['Value'] = value
conditional_block
get_fileservers.py
class
: def __init__(self, mainMenu, params=[]): # metadata info about the module, not modified during runtime self.info = { # name for the module that will appear in module menus 'Name': 'Get FileServers', # list of one or more authors for the module 'Au...
Module
identifier_name
get_fileservers.py
class Module: def __init__(self, mainMenu, params=[]): # metadata info about the module, not modified during runtime self.info = { # name for the module that will appear in module menus 'Name': 'Get FileServers', # list of one or more authors for the module ...
# The 'Agent' option is the only one that MUST be in a module 'Description' : 'LDAP IP/Hostname', 'Required' : True, 'Value' : '' }, 'BindDN' : { # The 'Agent' option is the only one that MUST be...
'LDAPAddress' : {
random_line_split
get_fileservers.py
class Module:
'NeedsAdmin' : False, # True if the method doesn't touch disk/is reasonably opsec safe 'OpsecSafe' : True, # the module language 'Language' : 'python', # the minimum language version needed 'MinLanguageVersion' : '2.6', ...
def __init__(self, mainMenu, params=[]): # metadata info about the module, not modified during runtime self.info = { # name for the module that will appear in module menus 'Name': 'Get FileServers', # list of one or more authors for the module 'Author': ...
identifier_body
group_mod.py
"""Modify Group Entry Message.""" from enum import IntEnum from pyof.foundation.base import GenericMessage from pyof.foundation.basic_types import ( FixedTypeList, Pad, UBInt8, UBInt16, UBInt32) from pyof.v0x04.common.header import Header, Type from pyof.v0x04.controller2switch.common import Bucket __all__ = ('Gr...
OFPGT_FF = 3 class ListOfBuckets(FixedTypeList): """List of buckets. Represented by instances of Bucket. """ def __init__(self, items=None): """Create a ListOfBuckets with the optional parameters below. Args: items (Bucket): Instance or a list of instances. "...
#: Fast failover group.
random_line_split
group_mod.py
"""Modify Group Entry Message.""" from enum import IntEnum from pyof.foundation.base import GenericMessage from pyof.foundation.basic_types import ( FixedTypeList, Pad, UBInt8, UBInt16, UBInt32) from pyof.v0x04.common.header import Header, Type from pyof.v0x04.controller2switch.common import Bucket __all__ = ('Gr...
(GenericMessage): """Group setup and teardown (controller -> datapath).""" header = Header(message_type=Type.OFPT_GROUP_MOD) command = UBInt16(enum_ref=GroupModCommand) group_type = UBInt8() #: Pad to 64 bits. pad = Pad(1) group_id = UBInt32() buckets = ListOfBuckets() def __init__...
GroupMod
identifier_name
group_mod.py
"""Modify Group Entry Message.""" from enum import IntEnum from pyof.foundation.base import GenericMessage from pyof.foundation.basic_types import ( FixedTypeList, Pad, UBInt8, UBInt16, UBInt32) from pyof.v0x04.common.header import Header, Type from pyof.v0x04.controller2switch.common import Bucket __all__ = ('Gr...
class GroupMod(GenericMessage): """Group setup and teardown (controller -> datapath).""" header = Header(message_type=Type.OFPT_GROUP_MOD) command = UBInt16(enum_ref=GroupModCommand) group_type = UBInt8() #: Pad to 64 bits. pad = Pad(1) group_id = UBInt32() buckets = ListOfBuckets() ...
"""Create a ListOfBuckets with the optional parameters below. Args: items (Bucket): Instance or a list of instances. """ super().__init__(pyof_class=Bucket, items=items)
identifier_body
merge_sort.rs
fn merge(a: Vec<i32>, b: Vec<i32>) -> Vec<i32> { let mut merged: Vec<i32> = Vec::with_capacity(a.len() + b.len()); let mut ai: usize = 0; let mut bi: usize = 0; while ai < a.len() && bi < b.len() { if a[ai] <= b[bi] { merged.push(a[ai]); ai += 1; } else
} for i in ai..a.len() { merged.push(a[i]); } for i in bi..b.len() { merged.push(b[i]); } merged } fn merge_sort(v: Vec<i32>) -> Vec<i32> { if v.len() <= 1 { v } else { let mid = v.len() / 2; let parts = v.split_at(mid); let a = merge...
{ merged.push(b[bi]); bi += 1; }
conditional_block
merge_sort.rs
fn merge(a: Vec<i32>, b: Vec<i32>) -> Vec<i32>
merged } fn merge_sort(v: Vec<i32>) -> Vec<i32> { if v.len() <= 1 { v } else { let mid = v.len() / 2; let parts = v.split_at(mid); let a = merge_sort(parts.0.to_vec()); let b = merge_sort(parts.1.to_vec()); merge(a, b) } } fn main() { let a = ve...
{ let mut merged: Vec<i32> = Vec::with_capacity(a.len() + b.len()); let mut ai: usize = 0; let mut bi: usize = 0; while ai < a.len() && bi < b.len() { if a[ai] <= b[bi] { merged.push(a[ai]); ai += 1; } else { merged.push(b[bi]); bi ...
identifier_body
merge_sort.rs
fn merge(a: Vec<i32>, b: Vec<i32>) -> Vec<i32> { let mut merged: Vec<i32> = Vec::with_capacity(a.len() + b.len()); let mut ai: usize = 0; let mut bi: usize = 0; while ai < a.len() && bi < b.len() { if a[ai] <= b[bi] { merged.push(a[ai]); ai += 1; } else { ...
merge_sort(vec![1, 5, 65, 23, 57, 1232, -1, -5, -2, 242, 100, 4, 423, 2, 564, 9, 0, 10, 43, 64, 32, 1, 999]), vec![-5, -2, -1, 0, 1, 1, 2, 4, 5, 9, 10, 23, 32, 43, 57, 64, 65, 100, 242, 423, 564, 999, 1232] ); }
random_line_split
merge_sort.rs
fn merge(a: Vec<i32>, b: Vec<i32>) -> Vec<i32> { let mut merged: Vec<i32> = Vec::with_capacity(a.len() + b.len()); let mut ai: usize = 0; let mut bi: usize = 0; while ai < a.len() && bi < b.len() { if a[ai] <= b[bi] { merged.push(a[ai]); ai += 1; } else { ...
(v: Vec<i32>) -> Vec<i32> { if v.len() <= 1 { v } else { let mid = v.len() / 2; let parts = v.split_at(mid); let a = merge_sort(parts.0.to_vec()); let b = merge_sort(parts.1.to_vec()); merge(a, b) } } fn main() { let a = vec![1, 5, 7, 4, 3, 2, 1, 9, 0...
merge_sort
identifier_name
intrinsic-alignment.rs
// Copyright 2012-2014 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-MI...
() { unsafe { assert_eq!(::rusti::pref_align_of::<u64>(), 8u); assert_eq!(::rusti::min_align_of::<u64>(), 8u); } } }
main
identifier_name
intrinsic-alignment.rs
// Copyright 2012-2014 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-MI...
assert_eq!(::rusti::min_align_of::<u64>(), 8u); } } } #[cfg(target_os = "android")] mod m { #[main] #[cfg(target_arch = "arm")] pub fn main() { unsafe { assert_eq!(::rusti::pref_align_of::<u64>(), 8u); assert_eq!(::rusti::min_align_of::<u64>(), 8u); ...
pub fn main() { unsafe { assert_eq!(::rusti::pref_align_of::<u64>(), 8u);
random_line_split
intrinsic-alignment.rs
// Copyright 2012-2014 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-MI...
#[main] #[cfg(target_arch = "x86_64")] pub fn main() { unsafe { assert_eq!(::rusti::pref_align_of::<u64>(), 8u); assert_eq!(::rusti::min_align_of::<u64>(), 8u); } } } #[cfg(target_os = "android")] mod m { #[main] #[cfg(target_arch = "arm")] pub fn m...
{ unsafe { assert_eq!(::rusti::pref_align_of::<u64>(), 8u); assert_eq!(::rusti::min_align_of::<u64>(), 8u); } }
identifier_body
index.js
'use strict'; // determine native module name let nativeModuleName = null; if (process.platform === 'win32') { nativeModuleName = `${process.platform}-${process.arch}`; } // find module let native = null; try { const _native = require(`./${nativeModuleName}`); native = _native; } catch (e) {} // assign mock ob...
function fetchFileIconAsPng(filePath, callback) { try { native.fetchFileIconAsPng(filePath, callback); } catch (e) { console.log(e); } } function saveFocus() { native.saveFocus(); } function restoreFocus() { native.restoreFocus(); } module.exports = { fetchFileIconAsPng, saveFocus, restoreFocus }...
{ native = { fetchFileIconAsPng: (path, cb) => { cb([]); }, saveFocus: () => {}, restoreFocus: () => {} }; }
conditional_block
index.js
'use strict'; // determine native module name let nativeModuleName = null; if (process.platform === 'win32') { nativeModuleName = `${process.platform}-${process.arch}`; } // find module let native = null; try {
const _native = require(`./${nativeModuleName}`); native = _native; } catch (e) {} // assign mock object if (native === null) { native = { fetchFileIconAsPng: (path, cb) => { cb([]); }, saveFocus: () => {}, restoreFocus: () => {} }; } function fetchFileIconAsPng(filePath, callback) { t...
random_line_split
index.js
'use strict'; // determine native module name let nativeModuleName = null; if (process.platform === 'win32') { nativeModuleName = `${process.platform}-${process.arch}`; } // find module let native = null; try { const _native = require(`./${nativeModuleName}`); native = _native; } catch (e) {} // assign mock ob...
function saveFocus() { native.saveFocus(); } function restoreFocus() { native.restoreFocus(); } module.exports = { fetchFileIconAsPng, saveFocus, restoreFocus };
{ try { native.fetchFileIconAsPng(filePath, callback); } catch (e) { console.log(e); } }
identifier_body
index.js
'use strict'; // determine native module name let nativeModuleName = null; if (process.platform === 'win32') { nativeModuleName = `${process.platform}-${process.arch}`; } // find module let native = null; try { const _native = require(`./${nativeModuleName}`); native = _native; } catch (e) {} // assign mock ob...
() { native.saveFocus(); } function restoreFocus() { native.restoreFocus(); } module.exports = { fetchFileIconAsPng, saveFocus, restoreFocus };
saveFocus
identifier_name
rmm.rs
//! The RMM map files have the following layout //! //! [HEADER] //! String (first byte indicates how long the string is) //! int map size x //! int map size y //! String (first byte indicates how long the string is) //! int map number //! int number of events //! //! [Event list (Number of events)] = Event clickable l...
let b_7: u32 = cursor.read_u8()? as u32; assert_eq!(b_0 & 0x2, 0); let obj_file_num = (b_0 / 4) + (b_1 % 32) * 64; let tle_file_idx = ((b_2 % 128) * 8) + (b_1 / 32); let tle_file_num = (b_3 * 2) + (b_2 / 128); let warp = b_4; let collision = b_6; let obj_file_idx = if collision % 24 ==...
let b_4: u32 = cursor.read_u8()? as u32; let b_5: u32 = cursor.read_u8()? as u32; let b_6: u32 = cursor.read_u8()? as u32;
random_line_split
rmm.rs
//! The RMM map files have the following layout //! //! [HEADER] //! String (first byte indicates how long the string is) //! int map size x //! int map size y //! String (first byte indicates how long the string is) //! int map number //! int number of events //! //! [Event list (Number of events)] = Event clickable l...
// map size (x, y) in number of tiles map.set_size_x(cursor.read_u32::<LE>()?); map.set_size_y(cursor.read_u32::<LE>()?); // Map name? map.set_id_count(cursor.read_u8()?); for idx in 0..(map.id_count()) { map.add_id_list_val(cursor.read_u8()?); } map.name = cp949::cp949_to_utf...
{ // println!("{:?}", file_type); return Err(Error::MissingMapIdentifier); }
conditional_block
rmm.rs
//! The RMM map files have the following layout //! //! [HEADER] //! String (first byte indicates how long the string is) //! int map size x //! int map size y //! String (first byte indicates how long the string is) //! int map number //! int number of events //! //! [Event list (Number of events)] = Event clickable l...
(b_7 << 1) + 1 }; let tile = MapTile { obj_rmd_entry: Entry::new(obj_file_num, obj_file_idx), tle_rmd_entry: Entry::new(tle_file_num, tle_file_idx), warp, collision, }; Ok(tile) } // NOTE: This was a test to see if pulling out the bit fields could be made a li...
{ let b_0: u32 = cursor.read_u8()? as u32; let b_1: u32 = cursor.read_u8()? as u32; let b_2: u32 = cursor.read_u8()? as u32; let b_3: u32 = cursor.read_u8()? as u32; let b_4: u32 = cursor.read_u8()? as u32; let b_5: u32 = cursor.read_u8()? as u32; let b_6: u32 = cursor.read_u8()? as u32; ...
identifier_body
rmm.rs
//! The RMM map files have the following layout //! //! [HEADER] //! String (first byte indicates how long the string is) //! int map size x //! int map size y //! String (first byte indicates how long the string is) //! int map number //! int number of events //! //! [Event list (Number of events)] = Event clickable l...
(data: &[u8]) -> Result<Map, Error> { let mut cursor = Cursor::new(data); let mut map = Map::new(); // filetype string: needs to equal "Redmoon MapData 1.0" let string_length = cursor.read_u8()?; let mut string = Vec::<u8>::new(); for _ in 0..string_length { let chr = cursor.read_u8()?;...
parse_rmm
identifier_name
insults.rs
! version = 2.0 // Handling abusive users. + int random comeback{weight=100} - You sound reasonable... time to up the medication. - I see you've set aside this special time to humiliate yourself in public. - Ahhh... I see the screw-up fairy has visited us again. - I don't know what your problem is, but I'll bet it's ...
- I can see your point, but I still think you're full of it. - What am I? Flypaper for freaks!? - Any connection between your reality and mine is purely coincidental. - I'm already visualizing the duct tape over your mouth. - Your teeth are brighter than you are. - We're all refreshed and challenged by your unique poin...
- I'm really easy to get along with once you people learn to worship me. - It sounds like English, but I can't understand a word you're saying.
random_line_split
insults.rs
! version = 2.0 // Handling abusive users. + int random comeback{weight=100} - You sound reasonable... time to up the medication. - I see you've set aside this special time to humiliate yourself in public. - Ahhh... I see the screw-up fairy has visited us again. - I don't know what your problem is, but I'll bet it's ...
- =-O How mean! :-({topic=apology} - Omg what a jerk!!{topic=apology} > topic apology + * - <noreply>{weight=10} - We're fighting. - Say you're sorry. - Say you're sorry. Now. + sorry - Okay.. I'll forgive you. :-){topic=random} - Good, you should be.{topic=random} - Okay. :-){topic=random} + (* sorry|sor...
{weight=100}
conditional_block
Badge.stories.tsx
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you...
disable: true, }, }, }; BadgeTextGallery.story = { parameters: { actions: { disable: true, }, controls: { disable: true, }, knobs: { disable: true, }, }, };
}, knobs: {
random_line_split
http_method_parser.py
# This file is part of Copernicus # http://www.copernicus-computing.org/ # # Copyright (C) 2011, Sander Pronk, Iman Pouya, Erik Lindahl, and others. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as published # by the Free Soft...
#tests the file against a reference file # this test can be run if one sees problems with the file transfer in multipart POST # send a file, and specify the path in the referenceFilename variable # will test that the received file that was parsed has same content and size as reference file def r...
regexp = 'boundary=(.*)' if 'Content-Type' in headers: contentType = headers['Content-Type'] else: contentType = headers['content-type'] match = re.search(regexp,contentType) if match == None: raise Exception('Could not find a multipart message boun...
identifier_body
http_method_parser.py
# This file is part of Copernicus # http://www.copernicus-computing.org/ # # Copyright (C) 2011, Sander Pronk, Iman Pouya, Erik Lindahl, and others. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as published # by the Free Soft...
terminateBoundary = line file.seek(0) skipBytes = 2 realFile = tempfile.TemporaryFile(mode="w+b") realFile.write(file.read(read...
if(line[-2:] == '\r\n'): line = line[:-2] elif(line[-1:] == '\n'): line = line[:-1]
random_line_split
http_method_parser.py
# This file is part of Copernicus # http://www.copernicus-computing.org/ # # Copyright (C) 2011, Sander Pronk, Iman Pouya, Erik Lindahl, and others. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as published # by the Free Soft...
#tests the file against a reference file # this test can be run if one sees problems with the file transfer in multipart POST # send a file, and specify the path in the referenceFilename variable # will test that the received file that was parsed has same content and size as reference file def r...
return match.group(1)
conditional_block
http_method_parser.py
# This file is part of Copernicus # http://www.copernicus-computing.org/ # # Copyright (C) 2011, Sander Pronk, Iman Pouya, Erik Lindahl, and others. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as published # by the Free Soft...
(headers,message): contentLength = long(headers['content-length']) if headers['content-type'] == 'application/x-www-form-urlencoded' or headers['content-type'] == 'application/x-www-form-urlencoded; charset=UTF-8': #TODO generalize msg = message.read(contentLength) parsedDict = ...
handleSinglePart
identifier_name
tableau_refresh_workbook.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
(self, context: dict) -> str: """ Executes the Tableau Extract Refresh and pushes the job id to xcom. :param context: The task context during execution. :type context: dict :return: the id of the job that executes the extract refresh :rtype: str """ with ...
execute
identifier_name
tableau_refresh_workbook.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
def execute(self, context: dict) -> str: """ Executes the Tableau Extract Refresh and pushes the job id to xcom. :param context: The task context during execution. :type context: dict :return: the id of the job that executes the extract refresh :rtype: str ...
super().__init__(**kwargs) self.workbook_name = workbook_name self.site_id = site_id self.blocking = blocking self.tableau_conn_id = tableau_conn_id
identifier_body
tableau_refresh_workbook.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
return job_id def _get_workbook_by_name(self, tableau_hook: TableauHook) -> WorkbookItem: for workbook in tableau_hook.get_all(resource_name='workbooks'): if workbook.name == self.workbook_name: self.log.info('Found matching workbook with id %s', workbook.id) ...
from airflow.providers.tableau.sensors.tableau_job_status import TableauJobStatusSensor TableauJobStatusSensor( job_id=job_id, site_id=self.site_id, tableau_conn_id=self.tableau_conn_id, task_id='wait_until_succeeded', ...
conditional_block
tableau_refresh_workbook.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
tableau_conn_id: str = 'tableau_default', **kwargs, ) -> None: super().__init__(**kwargs) self.workbook_name = workbook_name self.site_id = site_id self.blocking = blocking self.tableau_conn_id = tableau_conn_id def execute(self, context: dict) -> str: ...
site_id: Optional[str] = None, blocking: bool = True,
random_line_split
DB.py
, time, json class Penguin(DBObject): HASONE = ['avatar', 'currency', 'ninja'] HASMANY = ['assets', 'bans', 'careItems', 'coins', 'friends', 'ignores', 'requests', 'inventories', 'mails', 'memberships', 'musicTracks', 'puffles', 'stamps', 'stampCovers', 'igloos'] class Coin(DBObject): pass ...
class Ignore(DBObject): pass class Request(DBObject): pass class Inventory(DBObject): pass class Mail(DBObject): def get_sent_on(self): return int(time.mktime(self.sent_on.timetuple())) class Membership(DBObject): pass class MusicTrack(DBObject): shared = False def __l...
friend_id = -1
identifier_body
DB.py
, time, json class Penguin(DBObject): HASONE = ['avatar', 'currency', 'ninja'] HASMANY = ['assets', 'bans', 'careItems', 'coins', 'friends', 'ignores', 'requests', 'inventories', 'mails', 'memberships', 'musicTracks', 'puffles', 'stamps', 'stampCovers', 'igloos'] class Coin(DBObject): pass ...
else: returnValue(True) @inlineCallbacks def db_p
self.dbpenguin.nickname = p_nickname for error in done.errors: self.log('error', "[TE200] MySQL update nickname failed. Error :", error) returnValue(False)
conditional_block
DB.py
, time, json class Penguin(DBObject): HASONE = ['avatar', 'currency', 'ninja'] HASMANY = ['assets', 'bans', 'careItems', 'coins', 'friends', 'ignores', 'requests', 'inventories', 'mails', 'memberships', 'musicTracks', 'puffles', 'stamps', 'stampCovers', 'igloos'] class Coin(DBObject): pass ...
if not withNotes: return '|'.join(map(str, [self.id, self.name, int(self.shared), self.likes])) return '%'.join(map(str, [self.id, self.name, int(self.shared), self.notes, self.hash, self.likes])) def __int__(self): return self.id class Puffle(DBObject): state = x = y = 0...
return self.length def __str__(self, withNotes = False):
random_line_split
DB.py
, time, json class Penguin(DBObject): HASONE = ['avatar', 'currency', 'ninja'] HASMANY = ['assets', 'bans', 'careItems', 'coins', 'friends', 'ignores', 'requests', 'inventories', 'mails', 'memberships', 'musicTracks', 'puffles', 'stamps', 'stampCovers', 'igloos'] class Coin(DBObject): pass ...
(self): return int(self.stamp) class StampCover(DBObject): pass class EPFCom(DBObject): TABLENAME = 'epfcoms' def getTime(self): return int(time.mktime(self.time.timetuple())) def __str__(self): return '|'.join(map(str, [self.message, self.getTime(), self.mascot])) cl...
__int__
identifier_name
redirect-rename.rs
// Copyright 2016 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 ...
} // @has foo/struct.FooBar.html pub use hidden::Foo as FooBar; // @has foo/baz/index.html // @has foo/baz/struct.Thing.html pub use hidden::bar as baz;
pub mod bar { // @has foo/hidden/bar/struct.Thing.html // @has - '//p/a' '../../foo/baz/struct.Thing.html' pub struct Thing {} }
random_line_split
redirect-rename.rs
// Copyright 2016 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 ...
{} } } // @has foo/struct.FooBar.html pub use hidden::Foo as FooBar; // @has foo/baz/index.html // @has foo/baz/struct.Thing.html pub use hidden::bar as baz;
Thing
identifier_name
main.rs
use std::fs; use std::io::prelude::*; use std::net::TcpListener; use std::net::TcpStream; use std::thread; use std::time::Duration; use web_server::ThreadPool; fn main() { let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); let pool = ThreadPool::new(4); for stream in listener.incoming().take(2...
let (status_line, filename) = if buffer.starts_with(get) { ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") } else if buffer.starts_with(sleep) { thread::sleep(Duration::from_secs(5)); ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") } else { ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") ...
random_line_split
main.rs
use std::fs; use std::io::prelude::*; use std::net::TcpListener; use std::net::TcpStream; use std::thread; use std::time::Duration; use web_server::ThreadPool; fn main()
fn handle_connection(mut stream: TcpStream) { let mut buffer = [0; 1024]; stream.read(&mut buffer).unwrap(); let get = b"GET / HTTP/1.1\r\n"; let sleep = b"GET /sleep HTTP/1.1\r\n"; let (status_line, filename) = if buffer.starts_with(get) { ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") } ...
{ let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); let pool = ThreadPool::new(4); for stream in listener.incoming().take(2) { let stream = stream.unwrap(); pool.execute(|| { handle_connection(stream); }); } println!("Shutting down.") }
identifier_body
main.rs
use std::fs; use std::io::prelude::*; use std::net::TcpListener; use std::net::TcpStream; use std::thread; use std::time::Duration; use web_server::ThreadPool; fn
() { let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); let pool = ThreadPool::new(4); for stream in listener.incoming().take(2) { let stream = stream.unwrap(); pool.execute(|| { handle_connection(stream); }); } println!("Shutting down.") } fn handle...
main
identifier_name
main.rs
use std::fs; use std::io::prelude::*; use std::net::TcpListener; use std::net::TcpStream; use std::thread; use std::time::Duration; use web_server::ThreadPool; fn main() { let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); let pool = ThreadPool::new(4); for stream in listener.incoming().take(2...
else { ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html") }; let contents = fs::read_to_string(filename).unwrap(); let response = format!("{}{}", status_line, contents); stream.write(response.as_bytes()).unwrap(); stream.flush().unwrap(); }
{ thread::sleep(Duration::from_secs(5)); ("HTTP/1.1 200 OK\r\n\r\n", "hello.html") }
conditional_block
Form.js
import React, {Component} from 'react' import {findDOMNode} from 'react-dom' import styles from '../sass/Form' import {Button, Form, Input, DatePicker, Select} from 'antd' class FormComponent extends Component { constructor() { super() this.handleSubmit = this.handleSubmit.bind(this) } handleSubmit(e)...
() { const {form, schools, cats} = this.props return ( <Form onSubmit={this.handleSubmit} className={styles.form} inline> <Form.Item label="学校"> {form.getFieldDecorator('school',{initialValue: schools[0]?schools[0].id:''})( <Select className={style...
render
identifier_name
Form.js
import React, {Component} from 'react' import {findDOMNode} from 'react-dom' import styles from '../sass/Form' import {Button, Form, Input, DatePicker, Select} from 'antd' class FormComponent extends Component { constructor() { super() this.handleSubmit = this.handleSubmit.bind(this) } handleSubmit(e)...
}) } render() { const {form, schools, cats} = this.props return ( <Form onSubmit={this.handleSubmit} className={styles.form} inline> <Form.Item label="学校"> {form.getFieldDecorator('school',{initialValue: schools[0]?schools[0].id:''})( <Se...
{ actions.getItems(values) }
conditional_block
Form.js
import React, {Component} from 'react' import {findDOMNode} from 'react-dom' import styles from '../sass/Form' import {Button, Form, Input, DatePicker, Select} from 'antd' class FormComponent extends Component { constructor() { super() this.handleSubmit = this.handleSubmit.bind(this) } handleSubmit(e)...
<Select className={styles.select}> <Select.Option value="">全部</Select.Option> {cats.map(cat => <Select.Option key={cat.id} value={cat.id}>{cat.catName}</Select.Option> )} </Select> )} </Form.Item> <Form.Item> ...
{ const {form, schools, cats} = this.props return ( <Form onSubmit={this.handleSubmit} className={styles.form} inline> <Form.Item label="学校"> {form.getFieldDecorator('school',{initialValue: schools[0]?schools[0].id:''})( <Select className={styles.s...
identifier_body
Form.js
import React, {Component} from 'react' import {findDOMNode} from 'react-dom' import styles from '../sass/Form' import {Button, Form, Input, DatePicker, Select} from 'antd' class FormComponent extends Component { constructor() { super() this.handleSubmit = this.handleSubmit.bind(this)
handleSubmit(e) { e.preventDefault() const {form, actions} = this.props form.validateFields((err, values) => { if (!err) { actions.getItems(values) } }) } render() { const {form, schools, cats} = this.props return ( <Form onSubmit={this.handleSubmit} c...
}
random_line_split
graft.js
'use strict'; var Transform = require('readable-stream').Transform; var inherits = require('inherits'); var deepMatch = require('./lib/deepMatch'); var wrap = require('./lib/wrapMessage'); var jschan = require('jschan'); function noop() {} function Graft()
this.on('pipe', function(source) { source.on('ready', that.emit.bind(that, 'ready')); this.on('end', function() { source.end(); }); }); this._patterns = []; } inherits(Graft, Transform); Graft.prototype._transform = function flowing(obj, enc, done) { if (!obj._session && !obj._channel) ...
{ if (!(this instanceof Graft)) { return new Graft(); } Transform.call(this, { objectMode: true, highWaterMark: 16 }); var that = this; function readFirst() { /*jshint validthis:true */ this.removeListener('readable', readFirst); that._transform(wrap(this.read(), this), null, noop); } t...
identifier_body
graft.js
'use strict'; var Transform = require('readable-stream').Transform; var inherits = require('inherits'); var deepMatch = require('./lib/deepMatch'); var wrap = require('./lib/wrapMessage'); var jschan = require('jschan'); function noop() {} function Graft() { if (!(this instanceof Graft)) { return new...
this.end(); }; Graft.prototype.ReadChannel = function() { return this._nextChannel.ReadChannel(); }; Graft.prototype.WriteChannel = function() { return this._nextChannel.WriteChannel(); }; module.exports = Graft;
{ this.resume(); }
conditional_block
graft.js
'use strict'; var Transform = require('readable-stream').Transform; var inherits = require('inherits'); var deepMatch = require('./lib/deepMatch'); var wrap = require('./lib/wrapMessage'); var jschan = require('jschan'); function noop() {} function
() { if (!(this instanceof Graft)) { return new Graft(); } Transform.call(this, { objectMode: true, highWaterMark: 16 }); var that = this; function readFirst() { /*jshint validthis:true */ this.removeListener('readable', readFirst); that._transform(wrap(this.read(), this), null, noop); } ...
Graft
identifier_name
graft.js
'use strict'; var Transform = require('readable-stream').Transform; var inherits = require('inherits'); var deepMatch = require('./lib/deepMatch'); var wrap = require('./lib/wrapMessage'); var jschan = require('jschan'); function noop() {} function Graft() { if (!(this instanceof Graft)) { return new ...
this.on('pipe', function(source) { source.on('ready', that.emit.bind(that, 'ready')); this.on('end', function() { source.end(); }); }); this._patterns = []; } inherits(Graft, Transform); Graft.prototype._transform = function flowing(obj, enc, done) { if (!obj._session && !obj._channel) { ...
}); this._nextChannel = this._session.WriteChannel();
random_line_split
main.rs
#![deny(warnings)] #[cfg(feature = "bin")] extern crate difference; #[cfg(feature = "bin")] extern crate getopts; #[cfg(feature = "bin")] use getopts::Options; #[cfg(feature = "bin")] use std::env; #[cfg(not(feature = "bin"))] fn main() { panic!("Needs to be compiled with --features=bin"); } #[cfg(feature = "bi...
else { print!("{}", opts.usage(&format!("Usage: {} [options]", program))); return; }; }
{ let ch = difference::Changeset::new(&matches.free[0], &matches.free[1], split); println!("{}", ch); }
conditional_block
main.rs
#![deny(warnings)] #[cfg(feature = "bin")] extern crate difference; #[cfg(feature = "bin")] extern crate getopts; #[cfg(feature = "bin")] use getopts::Options; #[cfg(feature = "bin")] use std::env; #[cfg(not(feature = "bin"))] fn
() { panic!("Needs to be compiled with --features=bin"); } #[cfg(feature = "bin")] fn main() { let args: Vec<String> = env::args().collect(); let program = args[0].clone(); let mut opts = Options::new(); opts.optopt("s", "split", "", "char|word|line"); let matches = match opts.parse(&args[1..]...
main
identifier_name
main.rs
#![deny(warnings)] #[cfg(feature = "bin")] extern crate difference; #[cfg(feature = "bin")] extern crate getopts; #[cfg(feature = "bin")] use getopts::Options; #[cfg(feature = "bin")] use std::env; #[cfg(not(feature = "bin"))] fn main() { panic!("Needs to be compiled with --features=bin"); } #[cfg(feature = "bi...
opts.optopt("s", "split", "", "char|word|line"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => panic!(f.to_string()), }; let split = match matches.opt_str("s") { Some(ref x) if x == "char" => "", Some(ref x) if x == "word" => " ", Some(ref x)...
let mut opts = Options::new();
random_line_split
main.rs
#![deny(warnings)] #[cfg(feature = "bin")] extern crate difference; #[cfg(feature = "bin")] extern crate getopts; #[cfg(feature = "bin")] use getopts::Options; #[cfg(feature = "bin")] use std::env; #[cfg(not(feature = "bin"))] fn main()
#[cfg(feature = "bin")] fn main() { let args: Vec<String> = env::args().collect(); let program = args[0].clone(); let mut opts = Options::new(); opts.optopt("s", "split", "", "char|word|line"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => panic!(f.to_string()...
{ panic!("Needs to be compiled with --features=bin"); }
identifier_body
solenoid.py
#!/usr/bin/env python """ Deprecated since the solenoid was not strong enough. Was using: https://www.sparkfun.com/products/11015 5v, 4.5mm throw """ # Import required libraries import time import RPi.GPIO as GPIO # Use BCM GPIO references # instead of physical pin numbers GPIO.setmode(GPIO.BCM) GPIO.setwarnings(Fal...
pen = SolenoidMotor() start_time = time.time() for i in range(8): pen.tap() time.sleep(.09) print time.time() - start_time pen.reset()
conditional_block
solenoid.py
#!/usr/bin/env python """ Deprecated since the solenoid was not strong enough. Was using: https://www.sparkfun.com/products/11015 5v, 4.5mm throw """ # Import required libraries import time import RPi.GPIO as GPIO # Use BCM GPIO references # instead of physical pin numbers GPIO.setmode(GPIO.BCM) GPIO.setwarnings(Fal...
def reset(self): GPIO.output(self.pin, False) if __name__ == "__main__": pen = SolenoidMotor() start_time = time.time() for i in range(8): pen.tap() time.sleep(.09) print time.time() - start_time pen.reset()
GPIO.output(self.pin, True) time.sleep(self.wait_time) GPIO.output(self.pin, False)
identifier_body
solenoid.py
#!/usr/bin/env python """ Deprecated since the solenoid was not strong enough. Was using: https://www.sparkfun.com/products/11015 5v, 4.5mm throw """ # Import required libraries import time import RPi.GPIO as GPIO # Use BCM GPIO references # instead of physical pin numbers GPIO.setmode(GPIO.BCM) GPIO.setwarnings(Fal...
if __name__ == "__main__": pen = SolenoidMotor() start_time = time.time() for i in range(8): pen.tap() time.sleep(.09) print time.time() - start_time pen.reset()
def reset(self): GPIO.output(self.pin, False)
random_line_split
solenoid.py
#!/usr/bin/env python """ Deprecated since the solenoid was not strong enough. Was using: https://www.sparkfun.com/products/11015 5v, 4.5mm throw """ # Import required libraries import time import RPi.GPIO as GPIO # Use BCM GPIO references # instead of physical pin numbers GPIO.setmode(GPIO.BCM) GPIO.setwarnings(Fal...
(self): GPIO.output(self.pin, False) if __name__ == "__main__": pen = SolenoidMotor() start_time = time.time() for i in range(8): pen.tap() time.sleep(.09) print time.time() - start_time pen.reset()
reset
identifier_name
mod.rs
//! Platform abstraction //! //! This module aims to provide a platform abstraction and interface for //! the rest of the kernel code. The idea is that an architecture may not //! assume a specific platform, but platforms may assume a specific //! architecture if they desire //! //! As there can only be one actual plat...
} /// Returns the concrete platform implenetation /// We use this wrapper instead of directly re-exporting `plat_get_platform` /// to ensure that the return type of `plat_get_platform` adheres to the /// `PlatInterface` trait /// /// # Safety /// /// This function should be called no more than once as the underlying ...
{ for byte in s.bytes() { self.putchar(byte); } Ok(()) }
identifier_body
mod.rs
//! Platform abstraction //! //! This module aims to provide a platform abstraction and interface for //! the rest of the kernel code. The idea is that an architecture may not //! assume a specific platform, but platforms may assume a specific //! architecture if they desire //! //! As there can only be one actual plat...
unsafe fn early_init(&mut self) -> Result<(), ()>; /// Perform device discovery. Takes a window that can provide access /// to any hardware structures to walk fn early_device_discovery<'a, W: VSpaceWindow<'a>>(&mut self, window: &'a W) -> Result<(), ()>; } impl fmt::Write for PlatInterfaceType { fn...
/// # Safety /// /// This function should only be called once, and only during the /// early bootup phase of the system
random_line_split
mod.rs
//! Platform abstraction //! //! This module aims to provide a platform abstraction and interface for //! the rest of the kernel code. The idea is that an architecture may not //! assume a specific platform, but platforms may assume a specific //! architecture if they desire //! //! As there can only be one actual plat...
(config: &BootConfig) -> PlatInterfaceType where PlatInterfaceType: PlatInterface { plat_get_platform(config) }
get_platform
identifier_name
step_interpolator.ts
import {Interpolator} from "./interpolator" import {StepMode} from "core/enums" import * as p from "core/properties" import {min, findIndex, findLastIndex} from "core/util/array" export namespace StepInterpolator { export interface Attrs extends Interpolator.Attrs { mode: StepMode } export interface Props e...
(x: number): number { this.sort(false) if (this.clip) { if (x < this._x_sorted[0] || x > this._x_sorted[this._x_sorted.length-1]) return NaN } else { if (x < this._x_sorted[0]) return this._y_sorted[0] if (x > this._x_sorted[this._x_sorted.length-1]) return this._y...
compute
identifier_name
step_interpolator.ts
import {Interpolator} from "./interpolator" import {StepMode} from "core/enums" import * as p from "core/properties" import {min, findIndex, findLastIndex} from "core/util/array" export namespace StepInterpolator { export interface Attrs extends Interpolator.Attrs { mode: StepMode } export interface Props e...
return this._y_sorted[0] if (x > this._x_sorted[this._x_sorted.length-1]) return this._y_sorted[this._y_sorted.length-1] } let ind: number switch (this.mode) { case "after": { ind = findLastIndex(this._x_sorted, num => x >= num) break } case "before":...
return NaN } else { if (x < this._x_sorted[0])
random_line_split
step_interpolator.ts
import {Interpolator} from "./interpolator" import {StepMode} from "core/enums" import * as p from "core/properties" import {min, findIndex, findLastIndex} from "core/util/array" export namespace StepInterpolator { export interface Attrs extends Interpolator.Attrs { mode: StepMode } export interface Props e...
static initClass(): void { this.prototype.type = "StepInterpolator" this.define({ mode: [ p.StepMode, "after"], }) } compute(x: number): number { this.sort(false) if (this.clip) { if (x < this._x_sorted[0] || x > this._x_sorted[this._x_sorted.length-1]) return NaN ...
{ super(attrs) }
identifier_body
font_context.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use font::UsedFontStyle; use platform::font::FontHandle; use font_context::FontContextHandleMethods; use platform:...
{ ctx: FT_Library, } impl Drop for FreeTypeLibraryHandle { fn drop(&self) { assert!(self.ctx.is_not_null()); unsafe { FT_Done_FreeType(self.ctx); } } } pub struct FontContextHandle { ctx: @FreeTypeLibraryHandle, } impl FontContextHandle { pub fn new() -> FontC...
FreeTypeLibraryHandle
identifier_name
font_context.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use font::UsedFontStyle; use platform::font::FontHandle; use font_context::FontContextHandleMethods; use platform:...
}
{ debug!("Creating font handle for %s", name); do path_from_identifier(name, &style).chain |file_name| { debug!("Opening font face %s", file_name); FontHandle::new_from_file(self, file_name, &style) } }
identifier_body
font_context.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use font::UsedFontStyle; use platform::font::FontHandle; use font_context::FontContextHandleMethods; use platform:...
FontContextHandle { ctx: @FreeTypeLibraryHandle { ctx: ctx }, } } } } impl FontContextHandleMethods for FontContextHandle { fn clone(&self) -> FontContextHandle { FontContextHandle { ctx: self.ctx } } fn create_font_from_identifier(&self, name...
{ fail!(); }
conditional_block
font_context.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use font::UsedFontStyle; use platform::font::FontHandle; use font_context::FontContextHandleMethods; use platform:...
ctx: @FreeTypeLibraryHandle, } impl FontContextHandle { pub fn new() -> FontContextHandle { unsafe { let ctx: FT_Library = ptr::null(); let result = FT_Init_FreeType(ptr::to_unsafe_ptr(&ctx)); if !result.succeeded() { fail!(); } FontContextHandle { ...
pub struct FontContextHandle {
random_line_split
build.rs
use std::path::Path; use std::path::PathBuf; use std::env; use std::process::Command; fn
() { let out_dir = env::var("OUT_DIR").unwrap(); let target = env::var("TARGET").unwrap(); // http://doc.crates.io/build-script.html#inputs-to-the-build-script // "the build script’s current directory is the source directory of the build script’s package." let current_dir = env::current_dir().unwra...
main
identifier_name
build.rs
use std::path::Path; use std::path::PathBuf; use std::env; use std::process::Command; fn main()
}; println!(" QT_VER: {}", default_qt_ver); println!(" QT_COMP: {}", default_qt_comp); let qt_dir_default = home_dir.join("Qt") .join(env::var("QT_VER").unwrap_or(default_qt_ver)) .join(env::var("QT_COMP").unwrap_...
{ let out_dir = env::var("OUT_DIR").unwrap(); let target = env::var("TARGET").unwrap(); // http://doc.crates.io/build-script.html#inputs-to-the-build-script // "the build script’s current directory is the source directory of the build script’s package." let current_dir = env::current_dir().unwrap()...
identifier_body