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
nosy.py
"""Watch for changes in a collection of source files. If changes, run the specified test runner (nosetests, by default). """ from argparse import ArgumentParser import ConfigParser import glob import os import stat import subprocess import sys import time class Nosy(object): """Watch for changes in all source fil...
def _checksum(self): """Return a checksum which indicates if any files in the paths list have changed. """ checksum = self._calc_extra_paths_checksum() for root, dirs, files in os.walk(self.base_path): exclusions = self._calc_exclusions(root) checksu...
"""Return the checksum for the monitored files in the specified directory tree. """ checksum = 0 for pattern in self.glob_patterns: for file_path in glob.iglob(os.path.join(root, pattern)): if file_path not in exclusions: stats = os.stat(fi...
identifier_body
nosy.py
"""Watch for changes in a collection of source files. If changes, run the specified test runner (nosetests, by default). """ from argparse import ArgumentParser import ConfigParser import glob import os import stat import subprocess import sys import time class Nosy(object): """Watch for changes in all source fil...
(self, exclusions, root): """Return the checksum for the monitored files in the specified directory tree. """ checksum = 0 for pattern in self.glob_patterns: for file_path in glob.iglob(os.path.join(root, pattern)): if file_path not in exclusions: ...
_calc_dir_checksum
identifier_name
nosy.py
"""Watch for changes in a collection of source files. If changes, run the specified test runner (nosetests, by default). """ from argparse import ArgumentParser import ConfigParser import glob import os import stat import subprocess import sys import time
class Nosy(object): """Watch for changes in all source files. If changes, run the specified test runner (nosetests, by default). """ def __init__(self): """Return an instance with the default configuration, and a command line parser. """ self.config = ConfigParser.SafeCo...
random_line_split
debug.rs
use core::slice; use drivers::io::{Io, Pio}; use system::error::Result; pub fn
(ptr: *const u8, len: usize) -> Result<usize> { let bytes = unsafe { slice::from_raw_parts(ptr, len) }; if unsafe { ::ENV_PTR.is_some() } { ::env().console.lock().write(bytes); } else { let serial_status = Pio::<u8>::new(0x3F8 + 5); let mut serial_data = Pio::<u8>::new(0x3F8); ...
do_sys_debug
identifier_name
debug.rs
use core::slice; use drivers::io::{Io, Pio}; use system::error::Result; pub fn do_sys_debug(ptr: *const u8, len: usize) -> Result<usize> { let bytes = unsafe { slice::from_raw_parts(ptr, len) }; if unsafe { ::ENV_PTR.is_some() } { ::env().console.lock().write(bytes); } else { let serial_...
Ok(len) }
} }
random_line_split
debug.rs
use core::slice; use drivers::io::{Io, Pio}; use system::error::Result; pub fn do_sys_debug(ptr: *const u8, len: usize) -> Result<usize> { let bytes = unsafe { slice::from_raw_parts(ptr, len) }; if unsafe { ::ENV_PTR.is_some() } { ::env().console.lock().write(bytes); } else { let serial_...
} } Ok(len) }
{ while !serial_status.readf(0x20) {} serial_data.write(0x20); while !serial_status.readf(0x20) {} serial_data.write(8); }
conditional_block
debug.rs
use core::slice; use drivers::io::{Io, Pio}; use system::error::Result; pub fn do_sys_debug(ptr: *const u8, len: usize) -> Result<usize>
} } Ok(len) }
{ let bytes = unsafe { slice::from_raw_parts(ptr, len) }; if unsafe { ::ENV_PTR.is_some() } { ::env().console.lock().write(bytes); } else { let serial_status = Pio::<u8>::new(0x3F8 + 5); let mut serial_data = Pio::<u8>::new(0x3F8); for byte in bytes.iter() { whi...
identifier_body
maxSim.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Date : 2017-05-28 10:13:14 # @Author : Sizheree (sizheree.github.io) # @Link : # @Version : $1.0$ import logging import time import numpy as np import matplotlib.pyplot as plt # print(__package__, __file__) logging.basicConfig(level=logging.INFO) log = logging....
self.load() def load(self): from gensim.models import Word2Vec # 存放每一个句子实例的库 self.link_database = [] # 存放模型 self.vecmodel = Word2Vec.load(self.model_file) log.info('开始载入句子库') log.info('开始载入词向量') with open(self.txt_file) as fp: senten_list = fp.readlines() log.debug("senten%s", senten_list) ...
self.model_file = model_file self.lastNsen = 6 with open('../DL/attribute.dat', 'rb') as fp: import pickle self.attr_weigh= pickle.load(fp)
random_line_split
maxSim.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Date : 2017-05-28 10:13:14 # @Author : Sizheree (sizheree.github.io) # @Link : # @Version : $1.0$ import logging import time import numpy as np import matplotlib.pyplot as plt # print(__package__, __file__) logging.basicConfig(level=logging.INFO) log = logging....
self.txt_file = txt_file self.model_file = model_file self.lastNsen = 6 with open('../DL/attribute.dat', 'rb') as fp: import pickle self.attr_weigh= pickle.load(fp) self.load() def load(self): from gensim.models import Word2Vec # 存放每一个句子实例的库 self.link_database = [] # 存放模型 self.vecmodel = Word2...
in'):
identifier_name
maxSim.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Date : 2017-05-28 10:13:14 # @Author : Sizheree (sizheree.github.io) # @Link : # @Version : $1.0$ import logging import time import numpy as np import matplotlib.pyplot as plt # print(__package__, __file__) logging.basicConfig(level=logging.INFO) log = logging....
g.debug(mostNSimlink) log.debug([x.sim for x in self.link_database]) if len(mostNSimlink)==0 or mostNSimlink[0].sim < simCondision: log.info('没有较好匹配的语句,请重新输入其他语句') return None return mostNSimlink[:self.lastNsen] # 输入的语句和单个句子的相似度计算 def juziSim_vec(self, intxt, questionWordset, posWeight=None): # juziIn输入的...
=True) lo
conditional_block
maxSim.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Date : 2017-05-28 10:13:14 # @Author : Sizheree (sizheree.github.io) # @Link : # @Version : $1.0$ import logging import time import numpy as np import matplotlib.pyplot as plt # print(__package__, __file__) logging.basicConfig(level=logging.INFO) log = logging....
_processor(): def __init__(self, txt_file='../OCR/biaoqing.txt', model_file='./fash250.model.bin'): self.txt_file = txt_file self.model_file = model_file self.lastNsen = 6 with open('../DL/attribute.dat', 'rb') as fp: import pickle self.attr_weigh= pickle.load(fp) self.load() def load(self): from g...
"\nsentence_vec%s\n"%self.sentence_vec #对链接的处理库 # 链接就是映射句子到图的语句 class link
identifier_body
layer_utils.py
from __future__ import print_function import inspect import numpy as np import theano from ..layers.advanced_activations import LeakyReLU, PReLU from ..layers.core import Dense, Merge, Dropout, Activation, Reshape, Flatten, RepeatVector, Layer from ..layers.core import ActivityRegularization, TimeDistributedDense, Aut...
else: # The case in which layer_dict represents an "atomic" layer layer_dict.pop('name') if 'parameters' in layer_dict: params = layer_dict.get('parameters') layer_dict.pop('parameters') hasParams = True for k, v in layer_dict.items(): ...
graph_layer = containers.Graph() inputs = layer_dict.get('input_config') for input in inputs: graph_layer.add_input(**input) nodes = layer_dict.get('node_config') for node in nodes: layer = container_from_config(layer_dict['nodes'].get(node['name'])) ...
conditional_block
layer_utils.py
from __future__ import print_function import inspect import numpy as np import theano from ..layers.advanced_activations import LeakyReLU, PReLU from ..layers.core import Dense, Merge, Dropout, Activation, Reshape, Flatten, RepeatVector, Layer from ..layers.core import ActivityRegularization, TimeDistributedDense, Aut...
(model, input_shapes): """ Utility function to print the shape of the output at each layer of a Model Arguments: model: instance of Model / Merge input_shapes: dict (Graph), list of tuples (Merge) or tuple (Sequential) """ if model.__class__.__name__ in ['Sequential', 'Merge']: ...
print_layer_shapes
identifier_name
layer_utils.py
from __future__ import print_function import inspect
import numpy as np import theano from ..layers.advanced_activations import LeakyReLU, PReLU from ..layers.core import Dense, Merge, Dropout, Activation, Reshape, Flatten, RepeatVector, Layer from ..layers.core import ActivityRegularization, TimeDistributedDense, AutoEncoder, MaxoutDense from ..layers.embeddings import...
random_line_split
layer_utils.py
from __future__ import print_function import inspect import numpy as np import theano from ..layers.advanced_activations import LeakyReLU, PReLU from ..layers.core import Dense, Merge, Dropout, Activation, Reshape, Flatten, RepeatVector, Layer from ..layers.core import ActivityRegularization, TimeDistributedDense, Aut...
# in this case input_shapes is a dictionary inputs = [model.inputs[name].input for name in model.input_order] input_dummy = [np.zeros(input_shapes[name], dtype=np.float32) for name in model.input_order] layers = [model.nodes[c['name']] for c in mo...
""" Utility function to print the shape of the output at each layer of a Model Arguments: model: instance of Model / Merge input_shapes: dict (Graph), list of tuples (Merge) or tuple (Sequential) """ if model.__class__.__name__ in ['Sequential', 'Merge']: # in this case input_sh...
identifier_body
prs.py
def merge_pr(api, urn, pr, votes, total, threshold): """ merge a pull request, if possible, and use a nice detailed merge commit message """ pr_num = pr["number"] pr_title = pr['title'] pr_description = pr['body'] path = "/repos/{urn}/pulls/{pr}/merge".format(urn=urn, pr=pr_num) record...
def get_is_mergeable(api, urn, pr_num): return get_pr(api, urn, pr_num)["mergeable"] def get_pr(api, urn, pr_num): """ helper for fetching a pr. necessary because the "mergeable" field does not exist on prs that come back from paginated endpoints, so we must fetch the pr directly """ path = "/...
""" get all pr reviews on a pr https://help.github.com/articles/about-pull-request-reviews/ """ params = { "per_page": settings.DEFAULT_PAGINATION } path = "/repos/{urn}/pulls/{pr}/reviews".format(urn=urn, pr=pr_num) data = api("get", path, params=params) return data
identifier_body
prs.py
def merge_pr(api, urn, pr, votes, total, threshold): """ merge a pull request, if possible, and use a nice detailed merge commit message """ pr_num = pr["number"] pr_title = pr['title'] pr_description = pr['body'] path = "/repos/{urn}/pulls/{pr}/merge".format(urn=urn, pr=pr_num) record...
path = "/repos/{urn}/issues/{pr}/labels".format(urn=urn, pr=pr_num) data = labels resp = api("PUT", path, json=data) def close_pr(api, urn, pr): """ https://developer.github.com/v3/pulls/#update-a-pull-request """ path = "/repos/{urn}/pulls/{pr}".format(urn=urn, pr=pr["number"]) data = { ...
labels = [labels]
conditional_block
prs.py
def merge_pr(api, urn, pr, votes, total, threshold): """ merge a pull request, if possible, and use a nice detailed merge commit message """ pr_num = pr["number"] pr_title = pr['title'] pr_description = pr['body'] path = "/repos/{urn}/pulls/{pr}/merge".format(urn=urn, pr=pr_num) record...
resp = api("PUT", path, json=data) def close_pr(api, urn, pr): """ https://developer.github.com/v3/pulls/#update-a-pull-request """ path = "/repos/{urn}/pulls/{pr}".format(urn=urn, pr=pr["number"]) data = { "state": "closed", } return api("patch", path, json=data) def get_pr_last_upd...
if not isinstance(labels, (tuple, list)): labels = [labels] path = "/repos/{urn}/issues/{pr}/labels".format(urn=urn, pr=pr_num) data = labels
random_line_split
prs.py
def merge_pr(api, urn, pr, votes, total, threshold): """ merge a pull request, if possible, and use a nice detailed merge commit message """ pr_num = pr["number"] pr_title = pr['title'] pr_description = pr['body'] path = "/repos/{urn}/pulls/{pr}/merge".format(urn=urn, pr=pr_num) record...
(api, urn, pr_num): """ helper for fetching a pr. necessary because the "mergeable" field does not exist on prs that come back from paginated endpoints, so we must fetch the pr directly """ path = "/repos/{urn}/pulls/{pr}".format(urn=urn, pr=pr_num) pr = api("get", path) return pr def get_ope...
get_pr
identifier_name
logger.ts
export interface Logger { debug(...data: any[]): void; error(...data: any[]): void; info(...data: any[]): void; log(...data: any[]): void; trace(...data: any[]): void; warn(...data: any[]): void; } export class ConsoleLogger implements Logger { debug(...data: any[]): void { console.debug(...data); ...
console.trace(...data); } warn(...data: any[]): void { console.warn(...data); } } export class BitBucketLogger implements Logger { debug(_: any[]): void {} error(_: any[]): void {} info(_: any[]): void {} log(_: any[]): void {} trace(_: any[]): void {} warn(_: any[]): void {} }
} log(...data: any[]): void { console.log(...data); } trace(...data: any[]): void {
random_line_split
logger.ts
export interface Logger { debug(...data: any[]): void; error(...data: any[]): void; info(...data: any[]): void; log(...data: any[]): void; trace(...data: any[]): void; warn(...data: any[]): void; } export class ConsoleLogger implements Logger { debug(...data: any[]): void { console.debug(...data); ...
(_: any[]): void {} log(_: any[]): void {} trace(_: any[]): void {} warn(_: any[]): void {} }
info
identifier_name
logger.ts
export interface Logger { debug(...data: any[]): void; error(...data: any[]): void; info(...data: any[]): void; log(...data: any[]): void; trace(...data: any[]): void; warn(...data: any[]): void; } export class ConsoleLogger implements Logger { debug(...data: any[]): void { console.debug(...data); ...
warn(_: any[]): void {} }
{}
identifier_body
ascii.rs
// This is a part of rust-encoding. // Copyright (c) 2013-2015, Kang Seonghoon. // See README.md and LICENSE.txt for details. //! 7-bit ASCII encoding. use libtww::std::mem; use libtww::std::convert::Into; use types::*; /** * ASCII, also known as ISO/IEC 646:US. * * It is both a basis and a lowest common denomina...
pub struct ASCIIEncoding; impl Encoding for ASCIIEncoding { fn name(&self) -> &'static str { "ascii" } fn raw_encoder(&self) -> Box<RawEncoder> { ASCIIEncoder::new() } fn raw_decoder(&self) -> Box<RawDecoder> { ASCIIDecoder::new() } } /// An encoder for ASCII. #[derive(...
#[derive(Clone, Copy)]
random_line_split
ascii.rs
// This is a part of rust-encoding. // Copyright (c) 2013-2015, Kang Seonghoon. // See README.md and LICENSE.txt for details. //! 7-bit ASCII encoding. use libtww::std::mem; use libtww::std::convert::Into; use types::*; /** * ASCII, also known as ISO/IEC 646:US. * * It is both a basis and a lowest common denomina...
fn raw_encoder(&self) -> Box<RawEncoder> { ASCIIEncoder::new() } fn raw_decoder(&self) -> Box<RawDecoder> { ASCIIDecoder::new() } } /// An encoder for ASCII. #[derive(Clone, Copy)] pub struct ASCIIEncoder; impl ASCIIEncoder { pub fn new() -> Box<RawEncoder> { Box::new(ASCI...
{ "ascii" }
identifier_body
ascii.rs
// This is a part of rust-encoding. // Copyright (c) 2013-2015, Kang Seonghoon. // See README.md and LICENSE.txt for details. //! 7-bit ASCII encoding. use libtww::std::mem; use libtww::std::convert::Into; use types::*; /** * ASCII, also known as ISO/IEC 646:US. * * It is both a basis and a lowest common denomina...
(&self) -> Box<RawEncoder> { ASCIIEncoder::new() } fn raw_decoder(&self) -> Box<RawDecoder> { ASCIIDecoder::new() } } /// An encoder for ASCII. #[derive(Clone, Copy)] pub struct ASCIIEncoder; impl ASCIIEncoder { pub fn new() -> Box<RawEncoder> { Box::new(ASCIIEncoder) } } ...
raw_encoder
identifier_name
googlemaplocation.py
""" Autopsy Forensic Browser Copyright 2016-2018 Basis Technology Corp. Contact: carrier <at> sleuthkit <dot> org 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...
def analyze(self, dataSource, fileManager, context): try: self.current_case = Case.getCurrentCaseThrows() except NoCurrentCaseException as ex: self._logger.log(Level.WARNING, "No case currently open.", ex) self._logger.log(Level.WARNING, traceback.format_exc()) ...
self._logger = Logger.getLogger(self.__class__.__name__) self.current_case = None self.PROGRAM_NAME = "Google Maps History" self.CAT_DESTINATION = "Destination"
identifier_body
googlemaplocation.py
""" Autopsy Forensic Browser Copyright 2016-2018 Basis Technology Corp. Contact: carrier <at> sleuthkit <dot> org 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...
""" class GoogleMapLocationAnalyzer(general.AndroidComponentAnalyzer): def __init__(self): self._logger = Logger.getLogger(self.__class__.__name__) self.current_case = None self.PROGRAM_NAME = "Google Maps History" self.CAT_DESTINATION = "Destination" def analyze(self, dataSour...
random_line_split
googlemaplocation.py
""" Autopsy Forensic Browser Copyright 2016-2018 Basis Technology Corp. Contact: carrier <at> sleuthkit <dot> org 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...
(self, databasePath, abstractFile): if not databasePath: return try: artifactHelper = GeoArtifactsHelper(self.current_case.getSleuthkitCase(), general.MODULE_NAME, self.PROGRAM_NAME, abstractFile) Class.forName("org.sqlite.JDBC") #...
__findGeoLocationsInDB
identifier_name
googlemaplocation.py
""" Autopsy Forensic Browser Copyright 2016-2018 Basis Technology Corp. Contact: carrier <at> sleuthkit <dot> org 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...
try: artifactHelper = GeoArtifactsHelper(self.current_case.getSleuthkitCase(), general.MODULE_NAME, self.PROGRAM_NAME, abstractFile) Class.forName("org.sqlite.JDBC") # load JDBC driver connection = DriverManager.getConnection("jdbc:sqlite...
return
conditional_block
mod.rs
//! Trait Resolution. See the [rustc-dev-guide] for more information on how this works. //! //! [rustc-dev-guide]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html mod engine; pub mod error_reporting; mod project; mod structural_impls; pub mod util; use rustc_hir as hir; use rustc_middle::ty::error::{Expe...
( cause: ObligationCause<'tcx>, param_env: ty::ParamEnv<'tcx>, predicate: O, ) -> Obligation<'tcx, O> { Obligation { cause, param_env, recursion_depth: 0, predicate } } pub fn with_depth( cause: ObligationCause<'tcx>, recursion_depth: usize, param_env...
new
identifier_name
mod.rs
//! Trait Resolution. See the [rustc-dev-guide] for more information on how this works. //! //! [rustc-dev-guide]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html mod engine; pub mod error_reporting; mod project; mod structural_impls; pub mod util; use rustc_hir as hir; use rustc_middle::ty::error::{Expe...
/// something else, track the total depth to ensure termination. /// If this goes over a certain threshold, we abort compilation -- /// in such cases, we can not say whether or not the predicate /// holds for certain. Stupid halting problem; such a drag. pub recursion_depth: usize, } pub type Predi...
/// If we started proving this as a result of trying to prove
random_line_split
mod.rs
//! Trait Resolution. See the [rustc-dev-guide] for more information on how this works. //! //! [rustc-dev-guide]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html mod engine; pub mod error_reporting; mod project; mod structural_impls; pub mod util; use rustc_hir as hir; use rustc_middle::ty::error::{Expe...
pub fn with<P>(&self, value: P) -> Obligation<'tcx, P> { Obligation { cause: self.cause.clone(), param_env: self.param_env, recursion_depth: self.recursion_depth, predicate: value, } } } impl<'tcx> FulfillmentError<'tcx> { pub fn new( ...
{ Obligation::new(ObligationCause::misc(span, body_id), param_env, trait_ref) }
identifier_body
button.view.js
import React, { Component, PropTypes } from 'react' import cx from 'classnames' import { Icon } from '../icon' import { capitalize } from 'utils/string' import './button.view.styl' export class Button extends Component { static propTypes = { className: PropTypes.string, children: PropTypes.oneOfType([ ...
) } handleClick = (e) => { const { loading, disabled, onClick } = this.props if (loading || disabled) { e.preventDefault() return null } if (onClick) { onClick(e) } } render () { const { icon, htmlType, // loading, ...
{ const { className, type, size, block, loading, disabled, ghost } = this.props return cx( 'button', `button${capitalize(type)}`, `size${capitalize(size)}`, { isBlock: block }, { isGhost: ghost }, { isLoading: loading }, { ...
identifier_body
button.view.js
import React, { Component, PropTypes } from 'react' import cx from 'classnames' import { Icon } from '../icon' import { capitalize } from 'utils/string' import './button.view.styl' export class Button extends Component { static propTypes = { className: PropTypes.string, children: PropTypes.oneOfType([ ...
if (onClick) { onClick(e) } } render () { const { icon, htmlType, // loading, children } = this.props const iconName = icon // @OLD: loading ? 'loading' : icon const iconNode = iconName ? <Icon name={iconName} /> : null return ( <button cl...
{ e.preventDefault() return null }
conditional_block
button.view.js
import React, { Component, PropTypes } from 'react' import cx from 'classnames' import { Icon } from '../icon' import { capitalize } from 'utils/string' import './button.view.styl' export class Button extends Component { static propTypes = { className: PropTypes.string, children: PropTypes.oneOfType([ ...
const iconName = icon // @OLD: loading ? 'loading' : icon const iconNode = iconName ? <Icon name={iconName} /> : null return ( <button className={this.getRootClassNames()} onClick={this.handleClick} type={htmlType || 'button'} > {iconNode}{children} </butt...
} = this.props
random_line_split
button.view.js
import React, { Component, PropTypes } from 'react' import cx from 'classnames' import { Icon } from '../icon' import { capitalize } from 'utils/string' import './button.view.styl' export class Button extends Component { static propTypes = { className: PropTypes.string, children: PropTypes.oneOfType([ ...
() { const { icon, htmlType, // loading, children } = this.props const iconName = icon // @OLD: loading ? 'loading' : icon const iconNode = iconName ? <Icon name={iconName} /> : null return ( <button className={this.getRootClassNames()} onClick={this....
render
identifier_name
__init__.py
# -*- coding: utf-8 -*- """ Pygments ~~~~~~~~ Pygments is a syntax highlighting package written in Python. It is a generic syntax highlighter for general use in all kinds of software such as forum systems, wikis or other applications that need to prettify source code. Highlights are: * a ...
def format(tokens, formatter, outfile=None): """ Format a tokenlist ``tokens`` with the formatter ``formatter``. If ``outfile`` is given and a valid file object (an object with a ``write`` method), the result will be written to it, otherwise it is returned as a string. """ try: i...
""" Lex ``code`` with ``lexer`` and return an iterable of tokens. """ try: return lexer.get_tokens(code) except TypeError, err: if isinstance(err.args[0], str) and \ 'unbound method get_tokens' in err.args[0]: raise TypeError('lex() argument must be a lexer instanc...
identifier_body
__init__.py
# -*- coding: utf-8 -*- """ Pygments ~~~~~~~~ Pygments is a syntax highlighting package written in Python. It is a generic syntax highlighter for general use in all kinds of software such as forum systems, wikis or other applications that need to prettify source code. Highlights are: * a ...
If ``outfile`` is given and a valid file object (an object with a ``write`` method), the result will be written to it, otherwise it is returned as a string. """ try: if not outfile: #print formatter, 'using', formatter.encoding realoutfile = formatter.encoding and By...
def format(tokens, formatter, outfile=None): """ Format a tokenlist ``tokens`` with the formatter ``formatter``.
random_line_split
__init__.py
# -*- coding: utf-8 -*- """ Pygments ~~~~~~~~ Pygments is a syntax highlighting package written in Python. It is a generic syntax highlighter for general use in all kinds of software such as forum systems, wikis or other applications that need to prettify source code. Highlights are: * a ...
(code, lexer): """ Lex ``code`` with ``lexer`` and return an iterable of tokens. """ try: return lexer.get_tokens(code) except TypeError, err: if isinstance(err.args[0], str) and \ 'unbound method get_tokens' in err.args[0]: raise TypeError('lex() argument must...
lex
identifier_name
__init__.py
# -*- coding: utf-8 -*- """ Pygments ~~~~~~~~ Pygments is a syntax highlighting package written in Python. It is a generic syntax highlighter for general use in all kinds of software such as forum systems, wikis or other applications that need to prettify source code. Highlights are: * a ...
from pygments.cmdline import main sys.exit(main(sys.argv))
conditional_block
healthToMongo.py
#!/usr/bin/env python # 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/. # Copyright (c) 2014 Mozilla Corporation # # Contributors: # Anthony Verez averez@mozilla.com imp...
(data, mongo): # Empty everything before mongo.healthescluster.remove({}) mongo.healthescluster.insert(data) def getEsNodesStats(): r = requests.get(options.esservers[0] + '/_nodes/stats/os,jvm,fs') jsonobj = r.json() results = [] for nodeid in jsonobj['nodes']: # Skip non masters ...
writeEsClusterStats
identifier_name
healthToMongo.py
#!/usr/bin/env python # 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/. # Copyright (c) 2014 Mozilla Corporation # # Contributors: # Anthony Verez averez@mozilla.com imp...
mongo.healthfrontend.insert(host['_source']) def writeEsClusterStats(data, mongo): # Empty everything before mongo.healthescluster.remove({}) mongo.healthescluster.insert(data) def getEsNodesStats(): r = requests.get(options.esservers[0] + '/_nodes/stats/os,jvm,fs') jsonobj = r.json() ...
del host['_source']['details'][key]
conditional_block
healthToMongo.py
#!/usr/bin/env python # 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/. # Copyright (c) 2014 Mozilla Corporation # # Contributors: # Anthony Verez averez@mozilla.com imp...
import os sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../lib')) from utilities.toUTC import toUTC from elasticsearch_client import ElasticsearchClient from query_models import SearchQuery, TermMatch logger = logging.getLogger(sys.argv[0]) def loggerTimeStamp(self, record, datefmt=None)...
from logging.handlers import SysLogHandler from pymongo import MongoClient
random_line_split
healthToMongo.py
#!/usr/bin/env python # 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/. # Copyright (c) 2014 Mozilla Corporation # # Contributors: # Anthony Verez averez@mozilla.com imp...
if __name__ == '__main__': parser = OptionParser() parser.add_option( "-c", dest='configfile', default=sys.argv[0].replace('.py', '.conf'), help="configuration file to use") (options, args) = parser.parse_args() initConfig() initLogger() main()
options.output = getConfig('output', 'stdout', options.configfile) # syslog hostname options.sysloghostname = getConfig('sysloghostname', 'localhost', options.configfile) # syslog port options.syslogport = getConfig('syslogport', 514, options.configfile) # elastic search server settings ...
identifier_body
helpers.js
2) { const dt1 = new Date(t1); const dt2 = new Date(t2); const timeSpanMS = dt2.getTime() - dt1.getTime(); const span = { "timeSpanMIN": Math.floor(timeSpanMS / (1000 * 60 )), "timeSpanHR": Math.floor(timeSpanMS / (1000 * 60 * 60)), "timeSpanDAY": Mat...
{ // Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; // And swap it with the current element. temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array...
conditional_block
helpers.js
Input.requestEnvelope.context.System.device && handlerInput.requestEnvelope.context.System.device.supportedInterfaces && handlerInput.requestEnvelope.context.System.device.supportedInterfaces.Display; return hasDisplay; }, 'timeDelta': function(t1, t2) { const dt1 = ne...
return examples; }, 'getRecordCount': function(callback) { const params = { TableName: DYNAMODB_TABLE }; let docClient = new AWS.DynamoDB.DocumentClient(); docClient.scan(params, (err, data) => { if (err) { console.error("Unab...
random_line_split
errors.rs
use primitives::*; error_chain!{ errors { /// Error when trying trying to call `Expr::get()`, but the index is invalid. InvalidExprAccess(index: usize) { description("Trying to access an invalid expression index.") display("Trying to access the invalid ex...
display("Invalid arguments: {:?}. '{}' message: {}", args, op, msg) } Downcast(from: FundamentalType, to: FundamentalType) { description("Down casting tensor.") display("Down casting tensor from {} to {}.", from, to) } } // ...
description("Invalid arguments.")
random_line_split
sawyer_coffee_button_v1_policy.py
import numpy as np from metaworld.policies.action import Action from metaworld.policies.policy import Policy, assert_fully_parsed, move class SawyerCoffeeButtonV1Policy(Policy): @staticmethod @assert_fully_parsed def
(obs): return { 'hand_pos': obs[:3], 'mug_pos': obs[3:6], 'unused_info': obs[6:], } def get_action(self, obs): o_d = self._parse_obs(obs) action = Action({ 'delta_pos': np.arange(3), 'grab_effort': 3 }) ac...
_parse_obs
identifier_name
sawyer_coffee_button_v1_policy.py
import numpy as np from metaworld.policies.action import Action from metaworld.policies.policy import Policy, assert_fully_parsed, move class SawyerCoffeeButtonV1Policy(Policy): @staticmethod @assert_fully_parsed def _parse_obs(obs): return { 'hand_pos': obs[:3], 'mug_pos...
return pos_curr + np.array([.0, .1, .0])
conditional_block
sawyer_coffee_button_v1_policy.py
import numpy as np from metaworld.policies.action import Action from metaworld.policies.policy import Policy, assert_fully_parsed, move class SawyerCoffeeButtonV1Policy(Policy): @staticmethod @assert_fully_parsed def _parse_obs(obs): return { 'hand_pos': obs[:3], 'mug_pos...
pos_curr = o_d['hand_pos'] pos_mug = o_d['mug_pos'] + np.array([.0, .0, .01]) if abs(pos_curr[0] - pos_mug[0]) > 0.02: return np.array([pos_mug[0], pos_curr[1], .28]) else: return pos_curr + np.array([.0, .1, .0])
return action.array @staticmethod def _desired_pos(o_d):
random_line_split
sawyer_coffee_button_v1_policy.py
import numpy as np from metaworld.policies.action import Action from metaworld.policies.policy import Policy, assert_fully_parsed, move class SawyerCoffeeButtonV1Policy(Policy): @staticmethod @assert_fully_parsed def _parse_obs(obs): return { 'hand_pos': obs[:3], 'mug_pos...
pos_curr = o_d['hand_pos'] pos_mug = o_d['mug_pos'] + np.array([.0, .0, .01]) if abs(pos_curr[0] - pos_mug[0]) > 0.02: return np.array([pos_mug[0], pos_curr[1], .28]) else: return pos_curr + np.array([.0, .1, .0])
identifier_body
text_util.py
import re from nltk.corpus import stopwords from nltk.corpus import words from nltk.stem.snowball import SnowballStemmer from apiv2.models import QuestionText, Question from apiv2.search.fsearch import formula_extractor as fe cachedStopWords = stopwords.words("english") english_vocab = set(w.lower() for w in words.wo...
def remove_stopwords(text): return ' '.join([word for word in text.split() if len(word) > 2 and word not in cachedStopWords]) def english_only(text): return ' '.join([word for word in text.split() if word in english_vocab]) def stem_text(text): return ' '.join([stemmer.stem(word)...
return ' '.join([word.lower() for word in text.split()])
identifier_body
text_util.py
import re from nltk.corpus import stopwords from nltk.corpus import words from nltk.stem.snowball import SnowballStemmer from apiv2.models import QuestionText, Question from apiv2.search.fsearch import formula_extractor as fe cachedStopWords = stopwords.words("english") english_vocab = set(w.lower() for w in words.wo...
results = preprocess(text, **kwargs).split() return ' '.join(set(results)) def remove_non_alphabet(text): text = re.sub(r'[^a-zA-Z]', " ", text) return text def clean_latex(text): text = re.sub(fe.DOUBLE_DOLLAR_NOTATION, " ", text) text = re.sub(fe.PAREN_NOTATION, " ", text) text = re.su...
return preprocessed_text def preprocess_unique(text, **kwargs):
random_line_split
text_util.py
import re from nltk.corpus import stopwords from nltk.corpus import words from nltk.stem.snowball import SnowballStemmer from apiv2.models import QuestionText, Question from apiv2.search.fsearch import formula_extractor as fe cachedStopWords = stopwords.words("english") english_vocab = set(w.lower() for w in words.wo...
(text): return ' '.join([word.lower() for word in text.split()]) def remove_stopwords(text): return ' '.join([word for word in text.split() if len(word) > 2 and word not in cachedStopWords]) def english_only(text): return ' '.join([word for word in text.split() if word in english_vo...
to_lower
identifier_name
text_util.py
import re from nltk.corpus import stopwords from nltk.corpus import words from nltk.stem.snowball import SnowballStemmer from apiv2.models import QuestionText, Question from apiv2.search.fsearch import formula_extractor as fe cachedStopWords = stopwords.words("english") english_vocab = set(w.lower() for w in words.wo...
return preprocessed_text def preprocess_unique(text, **kwargs): results = preprocess(text, **kwargs).split() return ' '.join(set(results)) def remove_non_alphabet(text): text = re.sub(r'[^a-zA-Z]', " ", text) return text def clean_latex(text): text = re.sub(fe.DOUBLE_DOLLAR_NOTATION, " "...
preprocessed_text = stem_text(preprocessed_text)
conditional_block
series_lt.py
# ***************************************************************************** # Copyright (c) 2020, Intel Corporation All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # Redistributions of sou...
(): s1 = pd.Series([5, 4, 3, 2, 1]) s2 = pd.Series([0, 2, 3, 6, 8]) return s1.lt(s2) # Expect series of False, False, False, True, True print(series_lt())
series_lt
identifier_name
series_lt.py
# ***************************************************************************** # Copyright (c) 2020, Intel Corporation All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # Redistributions of sou...
@njit def series_lt(): s1 = pd.Series([5, 4, 3, 2, 1]) s2 = pd.Series([0, 2, 3, 6, 8]) return s1.lt(s2) # Expect series of False, False, False, True, True print(series_lt())
import pandas as pd from numba import njit
random_line_split
series_lt.py
# ***************************************************************************** # Copyright (c) 2020, Intel Corporation All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # Redistributions of sou...
print(series_lt())
s1 = pd.Series([5, 4, 3, 2, 1]) s2 = pd.Series([0, 2, 3, 6, 8]) return s1.lt(s2) # Expect series of False, False, False, True, True
identifier_body
datasource.py
""" DataSource is a wrapper for the OGR Data Source object, which provides an interface for reading vector geometry data from many different file formats (including ESRI shapefiles). When instantiating a DataSource object, use the filename of a GDAL-supported data source. For example, a SHP file or a TIGER/Line...
elif isinstance(index, int): if index < 0 or index >= self.layer_count: raise OGRIndexError('index out of range') l = capi.get_layer(self._ptr, index) else: raise TypeError('Invalid index type: %s' % type(index)) return Layer(l, self) ...
l = capi.get_layer_by_name(self.ptr, index) if not l: raise OGRIndexError('invalid OGR Layer name given: "%s"' % index)
conditional_block
datasource.py
""" DataSource is a wrapper for the OGR Data Source object, which provides an interface for reading vector geometry data from many different file formats (including ESRI shapefiles). When instantiating a DataSource object, use the filename of a GDAL-supported data source. For example, a SHP file or a TIGER/Line...
(self): "Returns OGR GetName and Driver for the Data Source." return '%s (%s)' % (self.name, str(self.driver)) @property def layer_count(self): "Returns the number of layers in the data source." return capi.get_layer_count(self._ptr) @property def name(self): "R...
__str__
identifier_name
datasource.py
""" DataSource is a wrapper for the OGR Data Source object, which provides an interface for reading vector geometry data from many different file formats (including ESRI shapefiles). When instantiating a DataSource object, use the filename of a GDAL-supported data source. For example, a SHP file or a TIGER/Line...
ds = capi.open_ds(ds_input, self._write, byref(ds_driver)) except OGRException: # Making the error message more clear rather than something # like "Invalid pointer returned from OGROpen". raise OGRException('Could not open the datasource at "%s...
"Wraps an OGR Data Source object." #### Python 'magic' routines #### def __init__(self, ds_input, ds_driver=False, write=False): # The write flag. if write: self._write = 1 else: self._write = 0 # Registering all the drivers, this needs to be done ...
identifier_body
datasource.py
""" DataSource is a wrapper for the OGR Data Source object, which provides an interface for reading vector geometry data from many different file formats (including ESRI shapefiles). When instantiating a DataSource object, use the filename of a GDAL-supported data source. For example, a SHP file or a TIGER/Line...
# # The OGR_DS_* routines are relevant here. class DataSource(GDALBase): "Wraps an OGR Data Source object." #### Python 'magic' routines #### def __init__(self, ds_input, ds_driver=False, write=False): # The write flag. if write: self._write = 1 else: self._w...
random_line_split
test_atmosphere.py
40626', freq='6h', tz=tz) ephem_data = solarposition.get_solarposition(times, latitude, longitude) # need to add physical tests instead of just functional tests def test_pres2alt(): atmosphere.pres2alt(100000) def test_alt2press(): atmosphere.pres2alt(1000) @pytest.mark.parametrize("model", ['simple...
(): with pytest.raises(TypeError): atmosphere.first_solar_spectral_correction(1, 1) def test_kasten96_lt(): """Test Linke turbidity factor calculated from AOD, Pwat and AM""" amp = np.array([1, 3, 5]) pwat = np.array([0, 2.5, 5]) aod_bb = np.array([0, 0.1, 1]) lt_expected = np.array( ...
test_first_solar_spectral_correction_ambiguous
identifier_name
test_atmosphere.py
40626', freq='6h', tz=tz) ephem_data = solarposition.get_solarposition(times, latitude, longitude) # need to add physical tests instead of just functional tests def test_pres2alt(): atmosphere.pres2alt(100000) def test_alt2press(): atmosphere.pres2alt(1000) @pytest.mark.parametrize("model", ['simple...
@pytest.mark.parametrize("module_type,expect", [ ('cdte', np.array( [[ 0.9905102 , 0.9764032 , 0.93975028], [ 1.02928735, 1.01881074, 0.98578821], [ 1.04750335, 1.03814456, 1.00623986]])), ('monosi', np.array( [[ 0.9776977 , 1.02043409, 1.03574032], [ 0.9863...
temp_air = np.array([0, 20, 40]) relative_humidity = np.array([0, 30, 100]) temps_humids = np.array( list(itertools.product(temp_air, relative_humidity))) pws = atmosphere.gueymard94_pw(temps_humids[:, 0], temps_humids[:, 1]) expected = np.array( [ 0.1 , 0.33702061, 1.1234020...
identifier_body
test_atmosphere.py
140626', freq='6h', tz=tz) ephem_data = solarposition.get_solarposition(times, latitude, longitude) # need to add physical tests instead of just functional tests def test_pres2alt(): atmosphere.pres2alt(100000) def test_alt2press(): atmosphere.pres2alt(1000) @pytest.mark.parametrize("model", ['simpl...
def test_kasten96_lt(): """Test Linke turbidity factor calculated from AOD, Pwat and AM""" amp = np.array([1, 3, 5]) pwat = np.array([0, 2.5, 5]) aod_bb = np.array([0, 0.1, 1]) lt_expected = np.array( [[[1.3802, 2.4102, 11.6802], [1.16303976, 2.37303976, 13.26303976], [1....
random_line_split
FileMonitorFlags.py
# encoding: utf-8 # module gio._gio # from /usr/lib/python2.7/dist-packages/gtk-2.0/gio/_gio.so # by generator 1.135 # no doc
import gobject as __gobject import gobject._gobject as __gobject__gobject class FileMonitorFlags(__gobject.GFlags): # no doc def __init__(self, *args, **kwargs): # real signature unknown pass __weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """...
# imports import gio as __gio import glib as __glib
random_line_split
FileMonitorFlags.py
# encoding: utf-8 # module gio._gio # from /usr/lib/python2.7/dist-packages/gtk-2.0/gio/_gio.so # by generator 1.135 # no doc # imports import gio as __gio import glib as __glib import gobject as __gobject import gobject._gobject as __gobject__gobject class FileMonitorFlags(__gobject.GFlags): # no doc def
(self, *args, **kwargs): # real signature unknown pass __weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """list of weak references to the object (if defined)""" __dict__ = None # (!) real value is '' __flags_values__ = { 0: 0, 1...
__init__
identifier_name
FileMonitorFlags.py
# encoding: utf-8 # module gio._gio # from /usr/lib/python2.7/dist-packages/gtk-2.0/gio/_gio.so # by generator 1.135 # no doc # imports import gio as __gio import glib as __glib import gobject as __gobject import gobject._gobject as __gobject__gobject class FileMonitorFlags(__gobject.GFlags): # no doc
def __init__(self, *args, **kwargs): # real signature unknown pass __weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """list of weak references to the object (if defined)""" __dict__ = None # (!) real value is '' __flags_values__ = { 0: ...
identifier_body
choices.py
from django.utils.translation import ugettext_lazy as _ DIAL_CHOICES = ( ('none', _('None')), ('din 41091.1', _('Dial with minute and hour markers (DIN 41091, Sect. 1)')), ('din 41091.3', _('Dial with hour markers (DIN 41091, Sect. 3)')), ('din 41091.4', _('Dial with hour numerals (DIN 41091, Part 4)')...
('stepping', _('Stepping minute hand')), ('sweeping', _('Sweeping minute hand')), ) SECOND_HAND_MOVEMENT_CHOICES = ( ('stepping', _('Stepping second hand')), ('sweeping', _('Sweeping second hand')), ('swinging', _('Oscillating second hand')), )
MINUTE_HAND_MOVEMENT_CHOICES = (
random_line_split
exercise2_60.py
# -*- coding: utf-8 -*- """ https://mitpress.mit.edu/sicp/full-text/book/book-Z-H-16.html#%_thm_2.60 """ from Chapter2.themes.lisp_list_structured_data import car, cdr, cons, lisp_list, nil, print_lisp_list from Chapter2.themes.sequences_as_conventional_interfaces import accumulate def element_of_set(x, set): """...
return element_of_set(x, cdr(set)) def adjoin_set(x, set): """Adds x to set""" return cons(x, set) def union_set(set1, set2): """Computes union of set1 and set2""" return accumulate(adjoin_set, set2, set1) def intersection_set(set1, set2): """Computes intersection of set1 and set2""" ...
return True
conditional_block
exercise2_60.py
# -*- coding: utf-8 -*- """ https://mitpress.mit.edu/sicp/full-text/book/book-Z-H-16.html#%_thm_2.60 """ from Chapter2.themes.lisp_list_structured_data import car, cdr, cons, lisp_list, nil, print_lisp_list from Chapter2.themes.sequences_as_conventional_interfaces import accumulate def element_of_set(x, set): """...
s2 = lisp_list(1, 1, 3) s3 = lisp_list(1, 2, 3) print(element_of_set(3, s1)) print_lisp_list(adjoin_set(4, s1)) print_lisp_list(intersection_set(s1, s2)) print_lisp_list(union_set(s1, s2)) from timeit import Timer t1_element_of = Timer(stmt='element_of_set(3, %(s1)s)' % locals(), ...
s1 = lisp_list(2, 3, 2, 1, 3, 2, 2)
random_line_split
exercise2_60.py
# -*- coding: utf-8 -*- """ https://mitpress.mit.edu/sicp/full-text/book/book-Z-H-16.html#%_thm_2.60 """ from Chapter2.themes.lisp_list_structured_data import car, cdr, cons, lisp_list, nil, print_lisp_list from Chapter2.themes.sequences_as_conventional_interfaces import accumulate def element_of_set(x, set): """...
setup='from Chapter2.exercise2_60 import intersection_set') t2_intersection = Timer(stmt='intersection_set(%(s1)s, %(s3)s)' % locals(), setup='from Chapter2.sets_as_unordered_lists import intersection_set') t1_union = Timer(stmt='union_set(%(s1)s, %(s2)s)...
s1 = lisp_list(2, 3, 2, 1, 3, 2, 2) s2 = lisp_list(1, 1, 3) s3 = lisp_list(1, 2, 3) print(element_of_set(3, s1)) print_lisp_list(adjoin_set(4, s1)) print_lisp_list(intersection_set(s1, s2)) print_lisp_list(union_set(s1, s2)) from timeit import Timer t1_element_of = Timer(stmt='element_...
identifier_body
exercise2_60.py
# -*- coding: utf-8 -*- """ https://mitpress.mit.edu/sicp/full-text/book/book-Z-H-16.html#%_thm_2.60 """ from Chapter2.themes.lisp_list_structured_data import car, cdr, cons, lisp_list, nil, print_lisp_list from Chapter2.themes.sequences_as_conventional_interfaces import accumulate def element_of_set(x, set): """...
(): s1 = lisp_list(2, 3, 2, 1, 3, 2, 2) s2 = lisp_list(1, 1, 3) s3 = lisp_list(1, 2, 3) print(element_of_set(3, s1)) print_lisp_list(adjoin_set(4, s1)) print_lisp_list(intersection_set(s1, s2)) print_lisp_list(union_set(s1, s2)) from timeit import Timer t1_element_of = Timer(stmt='...
run_the_magic
identifier_name
adaptive_input.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from typing import List import torch from torch import nn from fairseq.modules.quant_noise import quant_noise class AdaptiveInput(nn.Modu...
self.cutoff = cutoff self.embedding_dim = output_dim self.padding_idx = padding_idx self.embeddings = nn.ModuleList() for i in range(len(self.cutoff)): prev = self.cutoff[i - 1] if i > 0 else 0 size = self.cutoff[i] - prev dim = int(initial_...
assert ( vocab_size == cutoff[-1] ), "cannot specify cutoff larger than vocab size"
conditional_block
adaptive_input.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from typing import List import torch from torch import nn from fairseq.modules.quant_noise import quant_noise class AdaptiveInput(nn.Modu...
quant_noise( nn.Linear(dim, output_dim, bias=False), q_noise, qn_block_size ), ) self.embeddings.append(seq) self.padding_idx = None self.padding_idx = padding_idx def init_weights(m): if isinstance(m, ...
super().__init__() if vocab_size > cutoff[-1]: cutoff = cutoff + [vocab_size] else: assert ( vocab_size == cutoff[-1] ), "cannot specify cutoff larger than vocab size" self.cutoff = cutoff self.embedding_dim = output_dim self....
identifier_body
adaptive_input.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from typing import List import torch from torch import nn from fairseq.modules.quant_noise import quant_noise class AdaptiveInput(nn.Modu...
size = self.cutoff[i] - prev dim = int(initial_dim // (factor**i)) seq = nn.Sequential( nn.Embedding(size, dim, self.padding_idx), quant_noise( nn.Linear(dim, output_dim, bias=False), q_noise, qn_block_size ), ...
self.padding_idx = padding_idx self.embeddings = nn.ModuleList() for i in range(len(self.cutoff)): prev = self.cutoff[i - 1] if i > 0 else 0
random_line_split
adaptive_input.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from typing import List import torch from torch import nn from fairseq.modules.quant_noise import quant_noise class
(nn.Module): def __init__( self, vocab_size: int, padding_idx: int, initial_dim: int, factor: float, output_dim: int, cutoff: List[int], q_noise: float = 0, qn_block_size: int = 8, ): super().__init__() if vocab_size > cuto...
AdaptiveInput
identifier_name
p06_2.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Sep 18 16:28:59 2017 @author: hase 2. Credit Card Number Check Suppose you have been hired by MeisterCard to write a function which checks if a given credit card number is valid. Your function check(card_number) should take a string card_number as in...
def card(): ''' Get user input with card number''' card_num = input('Card number, #### #### #### ####? ') if len(card_num) == 19: sanitized = card_num.split(' ') s = len(sanitized) if s == 4: i = range(s) for i in sanitized: if sanitized[i]...
' Feedback to user after an invaid input''' print('Invalid number, please try again!')
identifier_body
p06_2.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*-
""" Created on Mon Sep 18 16:28:59 2017 @author: hase 2. Credit Card Number Check Suppose you have been hired by MeisterCard to write a function which checks if a given credit card number is valid. Your function check(card_number) should take a string card_number as input. - First, if the string does not follow th...
random_line_split
p06_2.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Sep 18 16:28:59 2017 @author: hase 2. Credit Card Number Check Suppose you have been hired by MeisterCard to write a function which checks if a given credit card number is valid. Your function check(card_number) should take a string card_number as in...
: ''' Get user input with card number''' card_num = input('Card number, #### #### #### ####? ') if len(card_num) == 19: sanitized = card_num.split(' ') s = len(sanitized) if s == 4: i = range(s) for i in sanitized: if sanitized[i].isdigit(): ...
rd()
identifier_name
p06_2.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Sep 18 16:28:59 2017 @author: hase 2. Credit Card Number Check Suppose you have been hired by MeisterCard to write a function which checks if a given credit card number is valid. Your function check(card_number) should take a string card_number as in...
else: invalid() else: invalid() else: invalid() return card_num card()
sanitized[i].isdigit(): print('Valid number!')
conditional_block
DatasetValuesJson.js
define(['q'], function(q){ return function ValueStore(dataset, $http, $rootScope){ var self = this; self.values = dataset.values; function getItemIndex(r, c){ return dataset.column.keys.length * r + c; } function keyToIndex(row, column){ va...
getByKey: getByKey, getSome: getSome, getDict: getDict }; }; });
} return dict; } return {
random_line_split
DatasetValuesJson.js
define(['q'], function(q){ return function ValueStore(dataset, $http, $rootScope){ var self = this; self.values = dataset.values; function getItemIndex(r, c)
function keyToIndex(row, column){ var r = dataset.rowLabels2Indexes[row]; var c = dataset.columnLabels2Indexes[column]; return getItemIndex(r, c); } function getByIndex(index){ return self.values[index].value; ...
{ return dataset.column.keys.length * r + c; }
identifier_body
DatasetValuesJson.js
define(['q'], function(q){ return function ValueStore(dataset, $http, $rootScope){ var self = this; self.values = dataset.values; function getItemIndex(r, c){ return dataset.column.keys.length * r + c; } function keyToIndex(row, column){ va...
if(!dict[rowName][columnName]){ dict[rowName][columnName] = { value: getByKey([rowName, columnName]) }; } } return dict; } return { getByKey: getByKey, getSome: getSome, getDict: getDict }; }; });
{ dict[rowName] = {}; }
conditional_block
DatasetValuesJson.js
define(['q'], function(q){ return function ValueStore(dataset, $http, $rootScope){ var self = this; self.values = dataset.values; function getItemIndex(r, c){ return dataset.column.keys.length * r + c; } function
(row, column){ var r = dataset.rowLabels2Indexes[row]; var c = dataset.columnLabels2Indexes[column]; return getItemIndex(r, c); } function getByIndex(index){ return self.values[index].value; } function getByKey(label...
keyToIndex
identifier_name
test_envois.py
#-*- coding: utf-8 -*- """ envois.test ~~~~~~~~~~~~ nosetests for the envois pkg
:license: BSD, see LICENSE for more details. """ import os import json import unittest from envois import invoice jsn = {"seller": {"name": "Lambda Labs, Inc.", "address": {"street": "857 Clay St. Suite 206", "city": "San Francisco", "state": "CA", "zip": "94108", "phone": "(555) 555-5555", "email": "some@email....
:copyright: (c) 2012 by Mek
random_line_split
test_envois.py
#-*- coding: utf-8 -*- """ envois.test ~~~~~~~~~~~~ nosetests for the envois pkg :copyright: (c) 2012 by Mek :license: BSD, see LICENSE for more details. """ import os import json import unittest from envois import invoice jsn = {"seller": {"name": "Lambda Labs, Inc.", "address": {"street": "857...
def test_invoice(self): invoice.make_invoice(jsn)
identifier_body
test_envois.py
#-*- coding: utf-8 -*- """ envois.test ~~~~~~~~~~~~ nosetests for the envois pkg :copyright: (c) 2012 by Mek :license: BSD, see LICENSE for more details. """ import os import json import unittest from envois import invoice jsn = {"seller": {"name": "Lambda Labs, Inc.", "address": {"street": "857...
(unittest.TestCase): def test_invoice(self): invoice.make_invoice(jsn)
Envois_Test
identifier_name
app.ts
import {Component, ViewChild} from '@angular/core'; import {Platform, ionicBootstrap, MenuController, Nav} from 'ionic-angular'; import {StatusBar} from 'ionic-native'; import { HomePage, DevicePage, } from './pages/index'; @Component({ templateUrl: 'build/app.html' }) export class MyApp { @ViewChild...
(page) { // close the menu when clicking a link from the menu this.menu.close(); // navigate to the new page if it is not the current page if (page.component) this.nav.setRoot(page.component); } } ionicBootstrap(MyApp);
openPage
identifier_name
app.ts
import {Component, ViewChild} from '@angular/core'; import {Platform, ionicBootstrap, MenuController, Nav} from 'ionic-angular'; import {StatusBar} from 'ionic-native'; import { HomePage, DevicePage, } from './pages/index'; @Component({ templateUrl: 'build/app.html' }) export class MyApp { @ViewChild...
openPage(page) { // close the menu when clicking a link from the menu this.menu.close(); // navigate to the new page if it is not the current page if (page.component) this.nav.setRoot(page.component); } } ionicBootstrap(MyApp);
{ this.platform.ready().then(() => { // Okay, so the platform is ready and our plugins are available. // Here you can do any higher level native things you might need. StatusBar.styleDefault(); }); }
identifier_body
app.ts
import {Component, ViewChild} from '@angular/core'; import {Platform, ionicBootstrap, MenuController, Nav} from 'ionic-angular'; import {StatusBar} from 'ionic-native'; import { HomePage, DevicePage, } from './pages/index'; @Component({ templateUrl: 'build/app.html' }) export class MyApp { @ViewChild...
// Okay, so the platform is ready and our plugins are available. // Here you can do any higher level native things you might need. StatusBar.styleDefault(); }); } openPage(page) { // close the menu when clicking a link from the menu this.menu.close();...
initializeApp() { this.platform.ready().then(() => {
random_line_split
super_simplex.rs
if i & 4 == 0 { i2 = 0; j2 = -1; } else { i2 = 0; j2 = 1; } } else { if i & 2 != 0 { i1 = 2; j1 = 1; } else { i1 = 0; j1 = ...
{ i1 = 1; j1 = 0; }
conditional_block
super_simplex.rs
j2 = 1; } } else { if i & 2 != 0 { i1 = 2; j1 = 1; } else { i1 = 0; j1 = 1; } if i & 4 != 0 { i2 = 1; j2 = 2; } else { ...
{ let mut lookup_2d: [([i8; 2], [f64; 2]); 8 * 4] = [([0; 2], [0.0; 2]); 8 * 4]; let mut lookup_3d: [[i8; 3]; 16 * 4] = [[0; 3]; 16 * 4]; let skew_constant = -0.211324865405187; for i in 0..8 { let (i1, j1, i2, j2); if i & 1 == 0 { if i & 2 == 0 { i1 = -1; ...
identifier_body
super_simplex.rs
() { let mut lookup_2d: [([i8; 2], [f64; 2]); 8 * 4] = [([0; 2], [0.0; 2]); 8 * 4]; let mut lookup_3d: [[i8; 3]; 16 * 4] = [[0; 3]; 16 * 4]; let skew_constant = -0.211324865405187; for i in 0..8 { let (i1, j1, i2, j2); if i & 1 == 0 { if i & 2 == 0 { i1 = -1;...
main
identifier_name
super_simplex.rs
if i & 4 != 0 { i2 = 1; j2 = 2; } else { i2 = 1; j2 = 0; } } lookup_2d[i * 4] = ([0, 0], [0.0, 0.0]); let skew_factor = -1.0 - 2.0 * skew_constant; lookup_2d[i * 4 + 1] = ([1, 1], [skew_fa...
} else { i1 = 0; j1 = 1; }
random_line_split
Blog.js
// Created by iWeb 3.0.4 local-build-20140617 setTransparentGifURL('../Media/transparent.gif');function applyEffects() {var registry=IWCreateEffectRegistry();registry.registerEffects({stroke_0:new IWStrokeParts([{rect:new IWRect(-2,2,4,332),url:'Blog_files/stroke.png'},{rect:new IWRect(-2,-2,4,4),url:'Blog_files/strok...
() {loadMozillaCSS('Blog_files/BlogMoz.css') adjustLineHeightIfTooBig('id1');adjustFontSizeIfTooBig('id1');adjustLineHeightIfTooBig('id2');adjustFontSizeIfTooBig('id2');detectBrowser();adjustLineHeightIfTooBig('id3');adjustFontSizeIfTooBig('id3');adjustLineHeightIfTooBig('id5');adjustFontSizeIfTooBig('id5');Widget.onlo...
onPageLoad
identifier_name
Blog.js
// Created by iWeb 3.0.4 local-build-20140617 setTransparentGifURL('../Media/transparent.gif');function applyEffects() {var registry=IWCreateEffectRegistry();registry.registerEffects({stroke_0:new IWStrokeParts([{rect:new IWRect(-2,2,4,332),url:'Blog_files/stroke.png'},{rect:new IWRect(-2,-2,4,4),url:'Blog_files/strok...
function photocastSubscribe() {photocastHelper("file://localhost/Users/student/GlassBottle/Blog/rss.xml");} function onPageLoad() {loadMozillaCSS('Blog_files/BlogMoz.css') adjustLineHeightIfTooBig('id1');adjustFontSizeIfTooBig('id1');adjustLineHeightIfTooBig('id2');adjustFontSizeIfTooBig('id2');detectBrowser();adjustL...
{return false;}
identifier_body
Blog.js
// Created by iWeb 3.0.4 local-build-20140617 setTransparentGifURL('../Media/transparent.gif');function applyEffects()
function hostedOnDM() {return false;} function photocastSubscribe() {photocastHelper("file://localhost/Users/student/GlassBottle/Blog/rss.xml");} function onPageLoad() {loadMozillaCSS('Blog_files/BlogMoz.css') adjustLineHeightIfTooBig('id1');adjustFontSizeIfTooBig('id1');adjustLineHeightIfTooBig('id2');adjustFontSizeIf...
{var registry=IWCreateEffectRegistry();registry.registerEffects({stroke_0:new IWStrokeParts([{rect:new IWRect(-2,2,4,332),url:'Blog_files/stroke.png'},{rect:new IWRect(-2,-2,4,4),url:'Blog_files/stroke_1.png'},{rect:new IWRect(2,-2,356,4),url:'Blog_files/stroke_2.png'},{rect:new IWRect(358,-2,4,4),url:'Blog_files/strok...
random_line_split
mainThreadTask.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
(handle: number): TPromise<void> { this._taskService.registerTaskProvider(handle, { provideTasks: () => { return this._proxy.$provideTasks(handle); } }); return TPromise.as<void>(undefined); } public $unregisterTaskProvider(handle: number): TPromise<any> { this._taskService.unregisterTaskProvider(h...
$registerTaskProvider
identifier_name
mainThreadTask.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
public $registerTaskProvider(handle: number): TPromise<void> { this._taskService.registerTaskProvider(handle, { provideTasks: () => { return this._proxy.$provideTasks(handle); } }); return TPromise.as<void>(undefined); } public $unregisterTaskProvider(handle: number): TPromise<any> { this._taskSer...
constructor( @IThreadService threadService: IThreadService, @ITaskService private _taskService: ITaskService) { super(); this._proxy = threadService.get(ExtHostContext.ExtHostTask); }
random_line_split