Unnamed: 0
int64
0
10k
repository_name
stringlengths
7
54
func_path_in_repository
stringlengths
5
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
100
30.3k
language
stringclasses
1 value
func_code_string
stringlengths
100
30.3k
func_code_tokens
stringlengths
138
33.2k
func_documentation_string
stringlengths
1
15k
func_documentation_tokens
stringlengths
5
5.14k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
3,600
zhanglab/psamm
psamm/fluxanalysis.py
consistency_check
def consistency_check(model, subset, epsilon, tfba, solver): """Check that reaction subset of model is consistent using FBA. Yields all reactions that are *not* flux consistent. A reaction is consistent if there is at least one flux solution to the model that both respects the model constraints and als...
python
def consistency_check(model, subset, epsilon, tfba, solver): """Check that reaction subset of model is consistent using FBA. Yields all reactions that are *not* flux consistent. A reaction is consistent if there is at least one flux solution to the model that both respects the model constraints and als...
['def', 'consistency_check', '(', 'model', ',', 'subset', ',', 'epsilon', ',', 'tfba', ',', 'solver', ')', ':', 'fba', '=', '_get_fba_problem', '(', 'model', ',', 'tfba', ',', 'solver', ')', 'subset', '=', 'set', '(', 'subset', ')', 'while', 'len', '(', 'subset', ')', '>', '0', ':', 'reaction', '=', 'next', '(', 'iter'...
Check that reaction subset of model is consistent using FBA. Yields all reactions that are *not* flux consistent. A reaction is consistent if there is at least one flux solution to the model that both respects the model constraints and also allows the reaction in question to have non-zero flux. Th...
['Check', 'that', 'reaction', 'subset', 'of', 'model', 'is', 'consistent', 'using', 'FBA', '.']
train
https://github.com/zhanglab/psamm/blob/dc427848c4f9d109ca590f0afa024c63b685b3f4/psamm/fluxanalysis.py#L420-L470
3,601
apple/turicreate
deps/src/boost_1_68_0/libs/metaparse/tools/benchmark/generate.py
Template.range
def range(self): """Returns the range for N""" match = self._match(in_comment( 'n[ \t]+in[ \t]*\\[([0-9]+)\\.\\.([0-9]+)\\),[ \t]+' 'step[ \t]+([0-9]+)' )) return range( int(match.group(1)), int(match.group(2)), int(match.group(...
python
def range(self): """Returns the range for N""" match = self._match(in_comment( 'n[ \t]+in[ \t]*\\[([0-9]+)\\.\\.([0-9]+)\\),[ \t]+' 'step[ \t]+([0-9]+)' )) return range( int(match.group(1)), int(match.group(2)), int(match.group(...
['def', 'range', '(', 'self', ')', ':', 'match', '=', 'self', '.', '_match', '(', 'in_comment', '(', "'n[ \\t]+in[ \\t]*\\\\[([0-9]+)\\\\.\\\\.([0-9]+)\\\\),[ \\t]+'", "'step[ \\t]+([0-9]+)'", ')', ')', 'return', 'range', '(', 'int', '(', 'match', '.', 'group', '(', '1', ')', ')', ',', 'int', '(', 'match', '.', 'group'...
Returns the range for N
['Returns', 'the', 'range', 'for', 'N']
train
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/libs/metaparse/tools/benchmark/generate.py#L143-L153
3,602
ten10solutions/Geist
geist/backends/_x11_common.py
GeistXBase.create_process
def create_process(self, command, shell=True, stdout=None, stderr=None, env=None): """ Execute a process using subprocess.Popen, setting the backend's DISPLAY """ env = env if env is not None else dict(os.environ) env['DISPLAY'] = self.display retur...
python
def create_process(self, command, shell=True, stdout=None, stderr=None, env=None): """ Execute a process using subprocess.Popen, setting the backend's DISPLAY """ env = env if env is not None else dict(os.environ) env['DISPLAY'] = self.display retur...
['def', 'create_process', '(', 'self', ',', 'command', ',', 'shell', '=', 'True', ',', 'stdout', '=', 'None', ',', 'stderr', '=', 'None', ',', 'env', '=', 'None', ')', ':', 'env', '=', 'env', 'if', 'env', 'is', 'not', 'None', 'else', 'dict', '(', 'os', '.', 'environ', ')', 'env', '[', "'DISPLAY'", ']', '=', 'self', '.'...
Execute a process using subprocess.Popen, setting the backend's DISPLAY
['Execute', 'a', 'process', 'using', 'subprocess', '.', 'Popen', 'setting', 'the', 'backend', 's', 'DISPLAY']
train
https://github.com/ten10solutions/Geist/blob/a1ef16d8b4c3777735008b671a50acfde3ce7bf1/geist/backends/_x11_common.py#L54-L63
3,603
olitheolix/qtmacs
qtmacs/logging_handler.py
QtmacsLoggingHandler.fetch
def fetch(self, start=None, stop=None): """ Fetch log records and return them as a list. |Args| * ``start`` (**int**): non-negative index of the first log record to return. * ``stop`` (**int**): non-negative index of the last log record to return. ...
python
def fetch(self, start=None, stop=None): """ Fetch log records and return them as a list. |Args| * ``start`` (**int**): non-negative index of the first log record to return. * ``stop`` (**int**): non-negative index of the last log record to return. ...
['def', 'fetch', '(', 'self', ',', 'start', '=', 'None', ',', 'stop', '=', 'None', ')', ':', '# Set defaults if no explicit indices were provided.', 'if', 'not', 'start', ':', 'start', '=', '0', 'if', 'not', 'stop', ':', 'stop', '=', 'len', '(', 'self', '.', 'log', ')', '# Sanity check: indices must be valid.', 'if', '...
Fetch log records and return them as a list. |Args| * ``start`` (**int**): non-negative index of the first log record to return. * ``stop`` (**int**): non-negative index of the last log record to return. |Returns| * **list**: list of log records (see ``lo...
['Fetch', 'log', 'records', 'and', 'return', 'them', 'as', 'a', 'list', '.']
train
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/logging_handler.py#L127-L165
3,604
alexras/bread
bread/utils.py
indent_text
def indent_text(string, indent_level=2): """Indent every line of text in a newline-delimited string""" indented_lines = [] indent_spaces = ' ' * indent_level for line in string.split('\n'): indented_lines.append(indent_spaces + line) return '\n'.join(indented_lines)
python
def indent_text(string, indent_level=2): """Indent every line of text in a newline-delimited string""" indented_lines = [] indent_spaces = ' ' * indent_level for line in string.split('\n'): indented_lines.append(indent_spaces + line) return '\n'.join(indented_lines)
['def', 'indent_text', '(', 'string', ',', 'indent_level', '=', '2', ')', ':', 'indented_lines', '=', '[', ']', 'indent_spaces', '=', "' '", '*', 'indent_level', 'for', 'line', 'in', 'string', '.', 'split', '(', "'\\n'", ')', ':', 'indented_lines', '.', 'append', '(', 'indent_spaces', '+', 'line', ')', 'return', "'\\n'...
Indent every line of text in a newline-delimited string
['Indent', 'every', 'line', 'of', 'text', 'in', 'a', 'newline', '-', 'delimited', 'string']
train
https://github.com/alexras/bread/blob/2e131380878c07500167fc12685e7bff1df258a4/bread/utils.py#L1-L10
3,605
muckamuck/stackility
stackility/CloudStackUtility.py
CloudStackUtility._fill_parameters
def _fill_parameters(self): """ Fill in the _parameters dict from the properties file. Args: None Returns: True Todo: Figure out what could go wrong and at least acknowledge the the fact that Murphy was an optimist. """ ...
python
def _fill_parameters(self): """ Fill in the _parameters dict from the properties file. Args: None Returns: True Todo: Figure out what could go wrong and at least acknowledge the the fact that Murphy was an optimist. """ ...
['def', '_fill_parameters', '(', 'self', ')', ':', 'self', '.', '_parameters', '=', 'self', '.', '_config', '.', 'get', '(', "'parameters'", ',', '{', '}', ')', 'self', '.', '_fill_defaults', '(', ')', 'for', 'k', 'in', 'self', '.', '_parameters', '.', 'keys', '(', ')', ':', 'try', ':', 'if', 'self', '.', '_parameters'...
Fill in the _parameters dict from the properties file. Args: None Returns: True Todo: Figure out what could go wrong and at least acknowledge the the fact that Murphy was an optimist.
['Fill', 'in', 'the', '_parameters', 'dict', 'from', 'the', 'properties', 'file', '.']
train
https://github.com/muckamuck/stackility/blob/b1696f02661134d31b99b4dea7c0d21d09482d33/stackility/CloudStackUtility.py#L453-L498
3,606
fabioz/PyDev.Debugger
_pydevd_bundle/pydevd_console.py
ConsoleMessage.add_console_message
def add_console_message(self, message_type, message): """add messages in the console_messages list """ for m in message.split("\n"): if m.strip(): self.console_messages.append((message_type, m))
python
def add_console_message(self, message_type, message): """add messages in the console_messages list """ for m in message.split("\n"): if m.strip(): self.console_messages.append((message_type, m))
['def', 'add_console_message', '(', 'self', ',', 'message_type', ',', 'message', ')', ':', 'for', 'm', 'in', 'message', '.', 'split', '(', '"\\n"', ')', ':', 'if', 'm', '.', 'strip', '(', ')', ':', 'self', '.', 'console_messages', '.', 'append', '(', '(', 'message_type', ',', 'm', ')', ')']
add messages in the console_messages list
['add', 'messages', 'in', 'the', 'console_messages', 'list']
train
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydevd_bundle/pydevd_console.py#L31-L36
3,607
ska-sa/katcp-python
katcp/kattypes.py
Parameter.unpack
def unpack(self, value): """Unpack the parameter using its kattype. Parameters ---------- packed_value : str The unescaped KATCP string to unpack. Returns ------- value : object The unpacked value. """ # Wrap errors in Fa...
python
def unpack(self, value): """Unpack the parameter using its kattype. Parameters ---------- packed_value : str The unescaped KATCP string to unpack. Returns ------- value : object The unpacked value. """ # Wrap errors in Fa...
['def', 'unpack', '(', 'self', ',', 'value', ')', ':', '# Wrap errors in FailReplies with information identifying the parameter', 'try', ':', 'return', 'self', '.', '_kattype', '.', 'unpack', '(', 'value', ',', 'self', '.', 'major', ')', 'except', 'ValueError', ',', 'message', ':', 'raise', 'FailReply', '(', '"Error in...
Unpack the parameter using its kattype. Parameters ---------- packed_value : str The unescaped KATCP string to unpack. Returns ------- value : object The unpacked value.
['Unpack', 'the', 'parameter', 'using', 'its', 'kattype', '.']
train
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/kattypes.py#L586-L605
3,608
bcbio/bcbio-nextgen
bcbio/bam/trim.py
_cutadapt_se_cmd
def _cutadapt_se_cmd(fastq_files, out_files, base_cmd, data): """ this has to use the -o option, not redirect to stdout in order for gzipping to be supported """ min_length = dd.get_min_read_length(data) cmd = base_cmd + " --minimum-length={min_length} ".format(**locals()) fq1 = objectstore....
python
def _cutadapt_se_cmd(fastq_files, out_files, base_cmd, data): """ this has to use the -o option, not redirect to stdout in order for gzipping to be supported """ min_length = dd.get_min_read_length(data) cmd = base_cmd + " --minimum-length={min_length} ".format(**locals()) fq1 = objectstore....
['def', '_cutadapt_se_cmd', '(', 'fastq_files', ',', 'out_files', ',', 'base_cmd', ',', 'data', ')', ':', 'min_length', '=', 'dd', '.', 'get_min_read_length', '(', 'data', ')', 'cmd', '=', 'base_cmd', '+', '" --minimum-length={min_length} "', '.', 'format', '(', '*', '*', 'locals', '(', ')', ')', 'fq1', '=', 'objectsto...
this has to use the -o option, not redirect to stdout in order for gzipping to be supported
['this', 'has', 'to', 'use', 'the', '-', 'o', 'option', 'not', 'redirect', 'to', 'stdout', 'in', 'order', 'for', 'gzipping', 'to', 'be', 'supported']
train
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/trim.py#L246-L257
3,609
ewels/MultiQC
multiqc/modules/fastqc/fastqc.py
MultiqcModule.sequence_quality_plot
def sequence_quality_plot (self): """ Create the HTML for the phred quality score plot """ data = dict() for s_name in self.fastqc_data: try: data[s_name] = {self.avg_bp_from_range(d['base']): d['mean'] for d in self.fastqc_data[s_name]['per_base_sequence_quality']} ...
python
def sequence_quality_plot (self): """ Create the HTML for the phred quality score plot """ data = dict() for s_name in self.fastqc_data: try: data[s_name] = {self.avg_bp_from_range(d['base']): d['mean'] for d in self.fastqc_data[s_name]['per_base_sequence_quality']} ...
['def', 'sequence_quality_plot', '(', 'self', ')', ':', 'data', '=', 'dict', '(', ')', 'for', 's_name', 'in', 'self', '.', 'fastqc_data', ':', 'try', ':', 'data', '[', 's_name', ']', '=', '{', 'self', '.', 'avg_bp_from_range', '(', 'd', '[', "'base'", ']', ')', ':', 'd', '[', "'mean'", ']', 'for', 'd', 'in', 'self', '....
Create the HTML for the phred quality score plot
['Create', 'the', 'HTML', 'for', 'the', 'phred', 'quality', 'score', 'plot']
train
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/fastqc/fastqc.py#L324-L369
3,610
honzajavorek/redis-collections
redis_collections/base.py
RedisCollection._normalize_index
def _normalize_index(self, index, pipe=None): """Convert negative indexes into their positive equivalents.""" pipe = self.redis if pipe is None else pipe len_self = self.__len__(pipe) positive_index = index if index >= 0 else len_self + index return len_self, positive_index
python
def _normalize_index(self, index, pipe=None): """Convert negative indexes into their positive equivalents.""" pipe = self.redis if pipe is None else pipe len_self = self.__len__(pipe) positive_index = index if index >= 0 else len_self + index return len_self, positive_index
['def', '_normalize_index', '(', 'self', ',', 'index', ',', 'pipe', '=', 'None', ')', ':', 'pipe', '=', 'self', '.', 'redis', 'if', 'pipe', 'is', 'None', 'else', 'pipe', 'len_self', '=', 'self', '.', '__len__', '(', 'pipe', ')', 'positive_index', '=', 'index', 'if', 'index', '>=', '0', 'else', 'len_self', '+', 'index',...
Convert negative indexes into their positive equivalents.
['Convert', 'negative', 'indexes', 'into', 'their', 'positive', 'equivalents', '.']
train
https://github.com/honzajavorek/redis-collections/blob/07ca8efe88fb128f7dc7319dfa6a26cd39b3776b/redis_collections/base.py#L152-L158
3,611
leancloud/python-sdk
leancloud/user.py
User.sign_up
def sign_up(self, username=None, password=None): """ 创建一个新用户。新创建的 User 对象,应该使用此方法来将数据保存至服务器,而不是使用 save 方法。 用户对象上必须包含 username 和 password 两个字段 """ if username: self.set('username', username) if password: self.set('password', password) usern...
python
def sign_up(self, username=None, password=None): """ 创建一个新用户。新创建的 User 对象,应该使用此方法来将数据保存至服务器,而不是使用 save 方法。 用户对象上必须包含 username 和 password 两个字段 """ if username: self.set('username', username) if password: self.set('password', password) usern...
['def', 'sign_up', '(', 'self', ',', 'username', '=', 'None', ',', 'password', '=', 'None', ')', ':', 'if', 'username', ':', 'self', '.', 'set', '(', "'username'", ',', 'username', ')', 'if', 'password', ':', 'self', '.', 'set', '(', "'password'", ',', 'password', ')', 'username', '=', 'self', '.', 'get', '(', "'userna...
创建一个新用户。新创建的 User 对象,应该使用此方法来将数据保存至服务器,而不是使用 save 方法。 用户对象上必须包含 username 和 password 两个字段
['创建一个新用户。新创建的', 'User', '对象,应该使用此方法来将数据保存至服务器,而不是使用', 'save', '方法。', '用户对象上必须包含', 'username', '和', 'password', '两个字段']
train
https://github.com/leancloud/python-sdk/blob/fea3240257ce65e6a32c7312a5cee1f94a51a587/leancloud/user.py#L114-L131
3,612
hellock/icrawler
icrawler/utils/proxy_pool.py
ProxyPool.load
def load(self, filename): """Load proxies from file""" with open(filename, 'r') as fin: proxies = json.load(fin) for protocol in proxies: for proxy in proxies[protocol]: self.proxies[protocol][proxy['addr']] = Proxy( proxy['addr'], prox...
python
def load(self, filename): """Load proxies from file""" with open(filename, 'r') as fin: proxies = json.load(fin) for protocol in proxies: for proxy in proxies[protocol]: self.proxies[protocol][proxy['addr']] = Proxy( proxy['addr'], prox...
['def', 'load', '(', 'self', ',', 'filename', ')', ':', 'with', 'open', '(', 'filename', ',', "'r'", ')', 'as', 'fin', ':', 'proxies', '=', 'json', '.', 'load', '(', 'fin', ')', 'for', 'protocol', 'in', 'proxies', ':', 'for', 'proxy', 'in', 'proxies', '[', 'protocol', ']', ':', 'self', '.', 'proxies', '[', 'protocol', ...
Load proxies from file
['Load', 'proxies', 'from', 'file']
train
https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/proxy_pool.py#L166-L175
3,613
inasafe/inasafe
safe/impact_function/impact_function.py
ImpactFunction.style
def style(self): """Function to apply some styles to the layers.""" LOGGER.info('ANALYSIS : Styling') classes = generate_classified_legend( self.analysis_impacted, self.exposure, self.hazard, self.use_rounding, self.debug_mode) ...
python
def style(self): """Function to apply some styles to the layers.""" LOGGER.info('ANALYSIS : Styling') classes = generate_classified_legend( self.analysis_impacted, self.exposure, self.hazard, self.use_rounding, self.debug_mode) ...
['def', 'style', '(', 'self', ')', ':', 'LOGGER', '.', 'info', '(', "'ANALYSIS : Styling'", ')', 'classes', '=', 'generate_classified_legend', '(', 'self', '.', 'analysis_impacted', ',', 'self', '.', 'exposure', ',', 'self', '.', 'hazard', ',', 'self', '.', 'use_rounding', ',', 'self', '.', 'debug_mode', ')', "# Let's ...
Function to apply some styles to the layers.
['Function', 'to', 'apply', 'some', 'styles', 'to', 'the', 'layers', '.']
train
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/impact_function/impact_function.py#L2478-L2510
3,614
saltstack/salt
salt/returners/couchbase_return.py
get_jids
def get_jids(): ''' Return a list of all job ids ''' cb_ = _get_connection() _verify_views() ret = {} for result in cb_.query(DESIGN_NAME, 'jids', include_docs=True): ret[result.key] = _format_jid_instance(result.key, result.doc.value['load']) return ret
python
def get_jids(): ''' Return a list of all job ids ''' cb_ = _get_connection() _verify_views() ret = {} for result in cb_.query(DESIGN_NAME, 'jids', include_docs=True): ret[result.key] = _format_jid_instance(result.key, result.doc.value['load']) return ret
['def', 'get_jids', '(', ')', ':', 'cb_', '=', '_get_connection', '(', ')', '_verify_views', '(', ')', 'ret', '=', '{', '}', 'for', 'result', 'in', 'cb_', '.', 'query', '(', 'DESIGN_NAME', ',', "'jids'", ',', 'include_docs', '=', 'True', ')', ':', 'ret', '[', 'result', '.', 'key', ']', '=', '_format_jid_instance', '(',...
Return a list of all job ids
['Return', 'a', 'list', 'of', 'all', 'job', 'ids']
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/couchbase_return.py#L297-L309
3,615
geographika/mappyfile
mappyfile/validator.py
Validator.validate
def validate(self, value, add_comments=False, schema_name="map"): """ verbose - also return the jsonschema error details """ validator = self.get_schema_validator(schema_name) error_messages = [] if isinstance(value, list): for d in value: er...
python
def validate(self, value, add_comments=False, schema_name="map"): """ verbose - also return the jsonschema error details """ validator = self.get_schema_validator(schema_name) error_messages = [] if isinstance(value, list): for d in value: er...
['def', 'validate', '(', 'self', ',', 'value', ',', 'add_comments', '=', 'False', ',', 'schema_name', '=', '"map"', ')', ':', 'validator', '=', 'self', '.', 'get_schema_validator', '(', 'schema_name', ')', 'error_messages', '=', '[', ']', 'if', 'isinstance', '(', 'value', ',', 'list', ')', ':', 'for', 'd', 'in', 'value...
verbose - also return the jsonschema error details
['verbose', '-', 'also', 'return', 'the', 'jsonschema', 'error', 'details']
train
https://github.com/geographika/mappyfile/blob/aecbc5e66ec06896bc4c5db41313503468829d00/mappyfile/validator.py#L169-L183
3,616
goshuirc/irc
girc/imapping.py
IDict.copy
def copy(self): """Return a copy of ourself.""" new_dict = IDict(std=self._std) new_dict.update(self.store) return new_dict
python
def copy(self): """Return a copy of ourself.""" new_dict = IDict(std=self._std) new_dict.update(self.store) return new_dict
['def', 'copy', '(', 'self', ')', ':', 'new_dict', '=', 'IDict', '(', 'std', '=', 'self', '.', '_std', ')', 'new_dict', '.', 'update', '(', 'self', '.', 'store', ')', 'return', 'new_dict']
Return a copy of ourself.
['Return', 'a', 'copy', 'of', 'ourself', '.']
train
https://github.com/goshuirc/irc/blob/d6a5e3e04d337566c009b087f108cd76f9e122cc/girc/imapping.py#L103-L107
3,617
tonioo/sievelib
sievelib/managesieve.py
Client.setactive
def setactive(self, scriptname): """Define the active script See MANAGESIEVE specifications, section 2.8 If scriptname is empty, the current active script is disabled, ie. there will be no active script anymore. :param scriptname: script's name :rtype: boolean ...
python
def setactive(self, scriptname): """Define the active script See MANAGESIEVE specifications, section 2.8 If scriptname is empty, the current active script is disabled, ie. there will be no active script anymore. :param scriptname: script's name :rtype: boolean ...
['def', 'setactive', '(', 'self', ',', 'scriptname', ')', ':', 'code', ',', 'data', '=', 'self', '.', '__send_command', '(', '"SETACTIVE"', ',', '[', 'scriptname', '.', 'encode', '(', '"utf-8"', ')', ']', ')', 'if', 'code', '==', '"OK"', ':', 'return', 'True', 'return', 'False']
Define the active script See MANAGESIEVE specifications, section 2.8 If scriptname is empty, the current active script is disabled, ie. there will be no active script anymore. :param scriptname: script's name :rtype: boolean
['Define', 'the', 'active', 'script']
train
https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/managesieve.py#L676-L691
3,618
ray-project/ray
python/ray/tune/schedulers/median_stopping_rule.py
MedianStoppingRule.on_trial_result
def on_trial_result(self, trial_runner, trial, result): """Callback for early stopping. This stopping rule stops a running trial if the trial's best objective value by step `t` is strictly worse than the median of the running averages of all completed trials' objectives reported up to s...
python
def on_trial_result(self, trial_runner, trial, result): """Callback for early stopping. This stopping rule stops a running trial if the trial's best objective value by step `t` is strictly worse than the median of the running averages of all completed trials' objectives reported up to s...
['def', 'on_trial_result', '(', 'self', ',', 'trial_runner', ',', 'trial', ',', 'result', ')', ':', 'if', 'trial', 'in', 'self', '.', '_stopped_trials', ':', 'assert', 'not', 'self', '.', '_hard_stop', 'return', 'TrialScheduler', '.', 'CONTINUE', '# fall back to FIFO', 'time', '=', 'result', '[', 'self', '.', '_time_at...
Callback for early stopping. This stopping rule stops a running trial if the trial's best objective value by step `t` is strictly worse than the median of the running averages of all completed trials' objectives reported up to step `t`.
['Callback', 'for', 'early', 'stopping', '.']
train
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/schedulers/median_stopping_rule.py#L56-L85
3,619
bxlab/bx-python
lib/bx_extras/stats.py
lgammln
def lgammln(xx): """ Returns the gamma function of xx. Gamma(z) = Integral(0,infinity) of t^(z-1)exp(-t) dt. (Adapted from: Numerical Recipies in C.) Usage: lgammln(xx) """ coeff = [76.18009173, -86.50532033, 24.01409822, -1.231739516, 0.120858003e-2, -0.536382e-5] x = xx - 1.0 tmp ...
python
def lgammln(xx): """ Returns the gamma function of xx. Gamma(z) = Integral(0,infinity) of t^(z-1)exp(-t) dt. (Adapted from: Numerical Recipies in C.) Usage: lgammln(xx) """ coeff = [76.18009173, -86.50532033, 24.01409822, -1.231739516, 0.120858003e-2, -0.536382e-5] x = xx - 1.0 tmp ...
['def', 'lgammln', '(', 'xx', ')', ':', 'coeff', '=', '[', '76.18009173', ',', '-', '86.50532033', ',', '24.01409822', ',', '-', '1.231739516', ',', '0.120858003e-2', ',', '-', '0.536382e-5', ']', 'x', '=', 'xx', '-', '1.0', 'tmp', '=', 'x', '+', '5.5', 'tmp', '=', 'tmp', '-', '(', 'x', '+', '0.5', ')', '*', 'math', '....
Returns the gamma function of xx. Gamma(z) = Integral(0,infinity) of t^(z-1)exp(-t) dt. (Adapted from: Numerical Recipies in C.) Usage: lgammln(xx)
['Returns', 'the', 'gamma', 'function', 'of', 'xx', '.', 'Gamma', '(', 'z', ')', '=', 'Integral', '(', '0', 'infinity', ')', 'of', 't^', '(', 'z', '-', '1', ')', 'exp', '(', '-', 't', ')', 'dt', '.', '(', 'Adapted', 'from', ':', 'Numerical', 'Recipies', 'in', 'C', '.', ')']
train
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L1470-L1488
3,620
BerkeleyAutomation/perception
perception/image.py
Image.mask_by_linear_ind
def mask_by_linear_ind(self, linear_inds): """Create a new image by zeroing out data at locations not in the given indices. Parameters ---------- linear_inds : :obj:`numpy.ndarray` of int A list of linear coordinates. Returns ------- :obj:`Im...
python
def mask_by_linear_ind(self, linear_inds): """Create a new image by zeroing out data at locations not in the given indices. Parameters ---------- linear_inds : :obj:`numpy.ndarray` of int A list of linear coordinates. Returns ------- :obj:`Im...
['def', 'mask_by_linear_ind', '(', 'self', ',', 'linear_inds', ')', ':', 'inds', '=', 'self', '.', 'linear_to_ij', '(', 'linear_inds', ')', 'return', 'self', '.', 'mask_by_ind', '(', 'inds', ')']
Create a new image by zeroing out data at locations not in the given indices. Parameters ---------- linear_inds : :obj:`numpy.ndarray` of int A list of linear coordinates. Returns ------- :obj:`Image` A new Image of the same type, with da...
['Create', 'a', 'new', 'image', 'by', 'zeroing', 'out', 'data', 'at', 'locations', 'not', 'in', 'the', 'given', 'indices', '.']
train
https://github.com/BerkeleyAutomation/perception/blob/03d9b37dd6b66896cdfe173905c9413c8c3c5df6/perception/image.py#L452-L468
3,621
aewallin/allantools
allantools/noise_kasdin.py
Noise.adev_from_qd
def adev_from_qd(self, tau0=1.0, tau=1.0): """ prefactor for Allan deviation for noise type defined by (qd, b, tau0) Colored noise generated with (qd, b, tau0) parameters will show an Allan variance of: AVAR = prefactor * h_a * tau^c where a = b + 2...
python
def adev_from_qd(self, tau0=1.0, tau=1.0): """ prefactor for Allan deviation for noise type defined by (qd, b, tau0) Colored noise generated with (qd, b, tau0) parameters will show an Allan variance of: AVAR = prefactor * h_a * tau^c where a = b + 2...
['def', 'adev_from_qd', '(', 'self', ',', 'tau0', '=', '1.0', ',', 'tau', '=', '1.0', ')', ':', 'g_b', '=', 'self', '.', 'phase_psd_from_qd', '(', 'tau0', ')', 'f_h', '=', '0.5', '/', 'tau0', 'if', 'self', '.', 'b', '==', '0', ':', 'coeff', '=', '3.0', '*', 'f_h', '/', '(', '4.0', '*', 'pow', '(', 'np', '.', 'pi', ',',...
prefactor for Allan deviation for noise type defined by (qd, b, tau0) Colored noise generated with (qd, b, tau0) parameters will show an Allan variance of: AVAR = prefactor * h_a * tau^c where a = b + 2 is the slope of the frequency PSD. and h_a...
['prefactor', 'for', 'Allan', 'deviation', 'for', 'noise', 'type', 'defined', 'by', '(', 'qd', 'b', 'tau0', ')']
train
https://github.com/aewallin/allantools/blob/b5c695a5af4379fcea4d4ce93a066cb902e7ee0a/allantools/noise_kasdin.py#L209-L251
3,622
ars096/pypci
pypci/pypci.py
write
def write(bar, offset, data): """Write data to PCI board. Parameters ---------- bar : BaseAddressRegister BAR to write. offset : int Address offset in BAR to write. data : bytes Data to write. Returns ------- None Examples ...
python
def write(bar, offset, data): """Write data to PCI board. Parameters ---------- bar : BaseAddressRegister BAR to write. offset : int Address offset in BAR to write. data : bytes Data to write. Returns ------- None Examples ...
['def', 'write', '(', 'bar', ',', 'offset', ',', 'data', ')', ':', 'if', 'type', '(', 'data', ')', 'not', 'in', '[', 'bytes', ',', 'bytearray', ']', ':', 'msg', '=', "'data should be bytes or bytearray type'", 'raise', 'TypeError', '(', 'msg', ')', 'size', '=', 'len', '(', 'data', ')', 'verify_access_range', '(', 'bar'...
Write data to PCI board. Parameters ---------- bar : BaseAddressRegister BAR to write. offset : int Address offset in BAR to write. data : bytes Data to write. Returns ------- None Examples -------- >>> b = pypci.lspci(vend...
['Write', 'data', 'to', 'PCI', 'board', '.', 'Parameters', '----------', 'bar', ':', 'BaseAddressRegister', 'BAR', 'to', 'write', '.', 'offset', ':', 'int', 'Address', 'offset', 'in', 'BAR', 'to', 'write', '.', 'data', ':', 'bytes', 'Data', 'to', 'write', '.', 'Returns', '-------', 'None', 'Examples', '--------', '>>>'...
train
https://github.com/ars096/pypci/blob/9469fa012e1f88fc6efc3aa6c17cd9732bbf73f6/pypci/pypci.py#L247-L282
3,623
watson-developer-cloud/python-sdk
ibm_watson/assistant_v1.py
AssistantV1.update_intent
def update_intent(self, workspace_id, intent, new_intent=None, new_description=None, new_examples=None, **kwargs): """ Update intent. Update an existing intent wit...
python
def update_intent(self, workspace_id, intent, new_intent=None, new_description=None, new_examples=None, **kwargs): """ Update intent. Update an existing intent wit...
['def', 'update_intent', '(', 'self', ',', 'workspace_id', ',', 'intent', ',', 'new_intent', '=', 'None', ',', 'new_description', '=', 'None', ',', 'new_examples', '=', 'None', ',', '*', '*', 'kwargs', ')', ':', 'if', 'workspace_id', 'is', 'None', ':', 'raise', 'ValueError', '(', "'workspace_id must be provided'", ')',...
Update intent. Update an existing intent with new or modified data. You must provide component objects defining the content of the updated intent. This operation is limited to 2000 requests per 30 minutes. For more information, see **Rate limiting**. :param str workspace_id: Un...
['Update', 'intent', '.']
train
https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/assistant_v1.py#L751-L815
3,624
kayak/pypika
pypika/queries.py
QueryBuilder._group_sql
def _group_sql(self, quote_char=None, groupby_alias=True, **kwargs): """ Produces the GROUP BY part of the query. This is a list of fields. The clauses are stored in the query under self._groupbys as a list fields. If an groupby field is used in the select clause, determined by...
python
def _group_sql(self, quote_char=None, groupby_alias=True, **kwargs): """ Produces the GROUP BY part of the query. This is a list of fields. The clauses are stored in the query under self._groupbys as a list fields. If an groupby field is used in the select clause, determined by...
['def', '_group_sql', '(', 'self', ',', 'quote_char', '=', 'None', ',', 'groupby_alias', '=', 'True', ',', '*', '*', 'kwargs', ')', ':', 'clauses', '=', '[', ']', 'selected_aliases', '=', '{', 's', '.', 'alias', 'for', 's', 'in', 'self', '.', '_selects', '}', 'for', 'field', 'in', 'self', '.', '_groupbys', ':', 'if', '...
Produces the GROUP BY part of the query. This is a list of fields. The clauses are stored in the query under self._groupbys as a list fields. If an groupby field is used in the select clause, determined by a matching alias, and the groupby_alias is set True then the GROUP BY clause wil...
['Produces', 'the', 'GROUP', 'BY', 'part', 'of', 'the', 'query', '.', 'This', 'is', 'a', 'list', 'of', 'fields', '.', 'The', 'clauses', 'are', 'stored', 'in', 'the', 'query', 'under', 'self', '.', '_groupbys', 'as', 'a', 'list', 'fields', '.']
train
https://github.com/kayak/pypika/blob/bfed26e963b982ecdb9697b61b67d76b493f2115/pypika/queries.py#L914-L938
3,625
kmedian/ctmc
ctmc/simulate.py
simulate
def simulate(s0, transmat, steps=1): """Simulate the next state Parameters ---------- s0 : ndarray Vector with state variables at t=0 transmat : ndarray The estimated transition/stochastic matrix. steps : int (Default: 1) The number of steps to simulate model outputs a...
python
def simulate(s0, transmat, steps=1): """Simulate the next state Parameters ---------- s0 : ndarray Vector with state variables at t=0 transmat : ndarray The estimated transition/stochastic matrix. steps : int (Default: 1) The number of steps to simulate model outputs a...
['def', 'simulate', '(', 's0', ',', 'transmat', ',', 'steps', '=', '1', ')', ':', '# Single-Step simulation', 'if', 'steps', '==', '1', ':', 'return', 'np', '.', 'dot', '(', 's0', ',', 'transmat', ')', '# Multi-Step simulation', 'out', '=', 'np', '.', 'zeros', '(', 'shape', '=', '(', 'steps', '+', '1', ',', 'len', '(',...
Simulate the next state Parameters ---------- s0 : ndarray Vector with state variables at t=0 transmat : ndarray The estimated transition/stochastic matrix. steps : int (Default: 1) The number of steps to simulate model outputs ahead. If steps>1 the a Mult-Step Sim...
['Simulate', 'the', 'next', 'state']
train
https://github.com/kmedian/ctmc/blob/e30747f797ce777fd2aaa1b7ee5a77e91d7db5e4/ctmc/simulate.py#L5-L40
3,626
inspirehep/inspire-dojson
inspire_dojson/hepnames/rules.py
name2marc
def name2marc(self, key, value): """Populates the ``100`` field. Also populates the ``400``, ``880``, and ``667`` fields through side effects. """ result = self.get('100', {}) result['a'] = value.get('value') result['b'] = value.get('numeration') result['c'] = value.get('title') re...
python
def name2marc(self, key, value): """Populates the ``100`` field. Also populates the ``400``, ``880``, and ``667`` fields through side effects. """ result = self.get('100', {}) result['a'] = value.get('value') result['b'] = value.get('numeration') result['c'] = value.get('title') re...
['def', 'name2marc', '(', 'self', ',', 'key', ',', 'value', ')', ':', 'result', '=', 'self', '.', 'get', '(', "'100'", ',', '{', '}', ')', 'result', '[', "'a'", ']', '=', 'value', '.', 'get', '(', "'value'", ')', 'result', '[', "'b'", ']', '=', 'value', '.', 'get', '(', "'numeration'", ')', 'result', '[', "'c'", ']', '...
Populates the ``100`` field. Also populates the ``400``, ``880``, and ``667`` fields through side effects.
['Populates', 'the', '100', 'field', '.']
train
https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hepnames/rules.py#L213-L237
3,627
mitsei/dlkit
dlkit/json_/grading/objects.py
GradebookNode.get_gradebook
def get_gradebook(self): """Gets the ``Gradebook`` at this node. return: (osid.grading.Gradebook) - the gradebook represented by this node *compliance: mandatory -- This method must be implemented.* """ if self._lookup_session is None: mgr = get_prov...
python
def get_gradebook(self): """Gets the ``Gradebook`` at this node. return: (osid.grading.Gradebook) - the gradebook represented by this node *compliance: mandatory -- This method must be implemented.* """ if self._lookup_session is None: mgr = get_prov...
['def', 'get_gradebook', '(', 'self', ')', ':', 'if', 'self', '.', '_lookup_session', 'is', 'None', ':', 'mgr', '=', 'get_provider_manager', '(', "'GRADING'", ',', 'runtime', '=', 'self', '.', '_runtime', ',', 'proxy', '=', 'self', '.', '_proxy', ')', 'self', '.', '_lookup_session', '=', 'mgr', '.', 'get_gradebook_look...
Gets the ``Gradebook`` at this node. return: (osid.grading.Gradebook) - the gradebook represented by this node *compliance: mandatory -- This method must be implemented.*
['Gets', 'the', 'Gradebook', 'at', 'this', 'node', '.']
train
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/grading/objects.py#L2041-L2052
3,628
saltstack/salt
salt/modules/solr.py
signal
def signal(signal=None): ''' Signals Apache Solr to start, stop, or restart. Obviously this is only going to work if the minion resides on the solr host. Additionally Solr doesn't ship with an init script so one must be created. signal : str (None) The command to pass to the apache solr ini...
python
def signal(signal=None): ''' Signals Apache Solr to start, stop, or restart. Obviously this is only going to work if the minion resides on the solr host. Additionally Solr doesn't ship with an init script so one must be created. signal : str (None) The command to pass to the apache solr ini...
['def', 'signal', '(', 'signal', '=', 'None', ')', ':', 'valid_signals', '=', '(', "'start'", ',', "'stop'", ',', "'restart'", ')', '# Give a friendly error message for invalid signals', '# TODO: Fix this logic to be reusable and used by apache.signal', 'if', 'signal', 'not', 'in', 'valid_signals', ':', 'msg', '=', 'va...
Signals Apache Solr to start, stop, or restart. Obviously this is only going to work if the minion resides on the solr host. Additionally Solr doesn't ship with an init script so one must be created. signal : str (None) The command to pass to the apache solr init valid values are 'start', '...
['Signals', 'Apache', 'Solr', 'to', 'start', 'stop', 'or', 'restart', '.', 'Obviously', 'this', 'is', 'only', 'going', 'to', 'work', 'if', 'the', 'minion', 'resides', 'on', 'the', 'solr', 'host', '.', 'Additionally', 'Solr', 'doesn', 't', 'ship', 'with', 'an', 'init', 'script', 'so', 'one', 'must', 'be', 'created', '.'...
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solr.py#L996-L1022
3,629
bcbio/bcbio-nextgen
bcbio/ngsalign/bowtie2.py
align_transcriptome
def align_transcriptome(fastq_file, pair_file, ref_file, data): """ bowtie2 with settings for aligning to the transcriptome for eXpress/RSEM/etc """ work_bam = dd.get_work_bam(data) base, ext = os.path.splitext(work_bam) out_file = base + ".transcriptome" + ext if utils.file_exists(out_file)...
python
def align_transcriptome(fastq_file, pair_file, ref_file, data): """ bowtie2 with settings for aligning to the transcriptome for eXpress/RSEM/etc """ work_bam = dd.get_work_bam(data) base, ext = os.path.splitext(work_bam) out_file = base + ".transcriptome" + ext if utils.file_exists(out_file)...
['def', 'align_transcriptome', '(', 'fastq_file', ',', 'pair_file', ',', 'ref_file', ',', 'data', ')', ':', 'work_bam', '=', 'dd', '.', 'get_work_bam', '(', 'data', ')', 'base', ',', 'ext', '=', 'os', '.', 'path', '.', 'splitext', '(', 'work_bam', ')', 'out_file', '=', 'base', '+', '".transcriptome"', '+', 'ext', 'if',...
bowtie2 with settings for aligning to the transcriptome for eXpress/RSEM/etc
['bowtie2', 'with', 'settings', 'for', 'aligning', 'to', 'the', 'transcriptome', 'for', 'eXpress', '/', 'RSEM', '/', 'etc']
train
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/bowtie2.py#L130-L152
3,630
Fuyukai/asyncwebsockets
asyncwebsockets/server.py
open_websocket_server
async def open_websocket_server(sock, filter=None): # pylint: disable=W0622 """ A context manager which serves this websocket. :param filter: an async callback which accepts the connection request and returns a bool, or an explicit Accept/Reject message. """ ws = await create_websocket_server(...
python
async def open_websocket_server(sock, filter=None): # pylint: disable=W0622 """ A context manager which serves this websocket. :param filter: an async callback which accepts the connection request and returns a bool, or an explicit Accept/Reject message. """ ws = await create_websocket_server(...
['async', 'def', 'open_websocket_server', '(', 'sock', ',', 'filter', '=', 'None', ')', ':', '# pylint: disable=W0622', 'ws', '=', 'await', 'create_websocket_server', '(', 'sock', ',', 'filter', '=', 'filter', ')', 'try', ':', 'yield', 'ws', 'finally', ':', 'await', 'ws', '.', 'close', '(', ')']
A context manager which serves this websocket. :param filter: an async callback which accepts the connection request and returns a bool, or an explicit Accept/Reject message.
['A', 'context', 'manager', 'which', 'serves', 'this', 'websocket', '.']
train
https://github.com/Fuyukai/asyncwebsockets/blob/e33e75fd51ce5ae0feac244e8407d2672c5b4745/asyncwebsockets/server.py#L14-L25
3,631
brainiak/brainiak
brainiak/funcalign/sssrm.py
SSSRM.fit
def fit(self, X, y, Z): """Compute the Semi-Supervised Shared Response Model Parameters ---------- X : list of 2D arrays, element i has shape=[voxels_i, n_align] Each element in the list contains the fMRI data for alignment of one subject. There are n_align samp...
python
def fit(self, X, y, Z): """Compute the Semi-Supervised Shared Response Model Parameters ---------- X : list of 2D arrays, element i has shape=[voxels_i, n_align] Each element in the list contains the fMRI data for alignment of one subject. There are n_align samp...
['def', 'fit', '(', 'self', ',', 'X', ',', 'y', ',', 'Z', ')', ':', 'logger', '.', 'info', '(', "'Starting SS-SRM'", ')', '# Check that the alpha value is in range (0.0,1.0)', 'if', '0.0', '>=', 'self', '.', 'alpha', 'or', 'self', '.', 'alpha', '>=', '1.0', ':', 'raise', 'ValueError', '(', '"Alpha parameter should be i...
Compute the Semi-Supervised Shared Response Model Parameters ---------- X : list of 2D arrays, element i has shape=[voxels_i, n_align] Each element in the list contains the fMRI data for alignment of one subject. There are n_align samples for each subject. y : ...
['Compute', 'the', 'Semi', '-', 'Supervised', 'Shared', 'Response', 'Model']
train
https://github.com/brainiak/brainiak/blob/408f12dec2ff56559a26873a848a09e4c8facfeb/brainiak/funcalign/sssrm.py#L133-L202
3,632
horazont/aioxmpp
aioxmpp/statemachine.py
OrderedStateMachine.wait_for
def wait_for(self, new_state): """ Wait for an exact state `new_state` to be reached by the state machine. If the state is skipped, that is, if a state which is greater than `new_state` is written to :attr:`state`, the coroutine raises :class:`OrderedStateSkipped` except...
python
def wait_for(self, new_state): """ Wait for an exact state `new_state` to be reached by the state machine. If the state is skipped, that is, if a state which is greater than `new_state` is written to :attr:`state`, the coroutine raises :class:`OrderedStateSkipped` except...
['def', 'wait_for', '(', 'self', ',', 'new_state', ')', ':', 'if', 'self', '.', '_state', '==', 'new_state', ':', 'return', 'if', 'self', '.', '_state', '>', 'new_state', ':', 'raise', 'OrderedStateSkipped', '(', 'new_state', ')', 'fut', '=', 'asyncio', '.', 'Future', '(', 'loop', '=', 'self', '.', 'loop', ')', 'self',...
Wait for an exact state `new_state` to be reached by the state machine. If the state is skipped, that is, if a state which is greater than `new_state` is written to :attr:`state`, the coroutine raises :class:`OrderedStateSkipped` exception as it is not possible anymore that it c...
['Wait', 'for', 'an', 'exact', 'state', 'new_state', 'to', 'be', 'reached', 'by', 'the', 'state', 'machine', '.']
train
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/statemachine.py#L152-L170
3,633
cwoebker/pen
pen/core.py
cmd_touch_note
def cmd_touch_note(args): """Create a note""" major = args.get(0) minor = args.get(1) if major in penStore.data: if minor is None: # show items in list for note in penStore.data[major]: puts(note) elif minor in penStore.data[major]: penStore.openN...
python
def cmd_touch_note(args): """Create a note""" major = args.get(0) minor = args.get(1) if major in penStore.data: if minor is None: # show items in list for note in penStore.data[major]: puts(note) elif minor in penStore.data[major]: penStore.openN...
['def', 'cmd_touch_note', '(', 'args', ')', ':', 'major', '=', 'args', '.', 'get', '(', '0', ')', 'minor', '=', 'args', '.', 'get', '(', '1', ')', 'if', 'major', 'in', 'penStore', '.', 'data', ':', 'if', 'minor', 'is', 'None', ':', '# show items in list', 'for', 'note', 'in', 'penStore', '.', 'data', '[', 'major', ']',...
Create a note
['Create', 'a', 'note']
train
https://github.com/cwoebker/pen/blob/996dfcdc018f2fc14a376835a2622fb4a7230a2f/pen/core.py#L58-L72
3,634
jtwhite79/pyemu
pyemu/utils/geostats.py
gslib_2_dataframe
def gslib_2_dataframe(filename,attr_name=None,x_idx=0,y_idx=1): """ function to read a GSLIB point data file into a pandas.DataFrame Parameters ---------- filename : (str) GSLIB file attr_name : (str) the column name in the dataframe for the attribute. If None, GSLIB file c...
python
def gslib_2_dataframe(filename,attr_name=None,x_idx=0,y_idx=1): """ function to read a GSLIB point data file into a pandas.DataFrame Parameters ---------- filename : (str) GSLIB file attr_name : (str) the column name in the dataframe for the attribute. If None, GSLIB file c...
['def', 'gslib_2_dataframe', '(', 'filename', ',', 'attr_name', '=', 'None', ',', 'x_idx', '=', '0', ',', 'y_idx', '=', '1', ')', ':', 'with', 'open', '(', 'filename', ',', "'r'", ')', 'as', 'f', ':', 'title', '=', 'f', '.', 'readline', '(', ')', '.', 'strip', '(', ')', 'num_attrs', '=', 'int', '(', 'f', '.', 'readline...
function to read a GSLIB point data file into a pandas.DataFrame Parameters ---------- filename : (str) GSLIB file attr_name : (str) the column name in the dataframe for the attribute. If None, GSLIB file can have only 3 columns. attr_name must be in the GSLIB file header ...
['function', 'to', 'read', 'a', 'GSLIB', 'point', 'data', 'file', 'into', 'a', 'pandas', '.', 'DataFrame']
train
https://github.com/jtwhite79/pyemu/blob/c504d8e7a4097cec07655a6318d275739bd8148a/pyemu/utils/geostats.py#L1792-L1856
3,635
xav/Grapefruit
grapefruit.py
rgb_to_yiq
def rgb_to_yiq(r, g=None, b=None): """Convert the color from RGB to YIQ. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (y, i, q) tuple in the range: y[0...1], i[0...1],...
python
def rgb_to_yiq(r, g=None, b=None): """Convert the color from RGB to YIQ. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (y, i, q) tuple in the range: y[0...1], i[0...1],...
['def', 'rgb_to_yiq', '(', 'r', ',', 'g', '=', 'None', ',', 'b', '=', 'None', ')', ':', 'if', 'type', '(', 'r', ')', 'in', '[', 'list', ',', 'tuple', ']', ':', 'r', ',', 'g', ',', 'b', '=', 'r', 'y', '=', '(', 'r', '*', '0.29895808', ')', '+', '(', 'g', '*', '0.58660979', ')', '+', '(', 'b', '*', '0.11443213', ')', 'i'...
Convert the color from RGB to YIQ. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (y, i, q) tuple in the range: y[0...1], i[0...1], q[0...1] >>> '(%g, %g, %g)' % rg...
['Convert', 'the', 'color', 'from', 'RGB', 'to', 'YIQ', '.']
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L430-L457
3,636
brean/python-pathfinding
pathfinding/core/util.py
expand_path
def expand_path(path): ''' Given a compressed path, return a new path that has all the segments in it interpolated. ''' expanded = [] if len(path) < 2: return expanded for i in range(len(path)-1): expanded += bresenham(path[i], path[i + 1]) expanded += [path[:-1]] ret...
python
def expand_path(path): ''' Given a compressed path, return a new path that has all the segments in it interpolated. ''' expanded = [] if len(path) < 2: return expanded for i in range(len(path)-1): expanded += bresenham(path[i], path[i + 1]) expanded += [path[:-1]] ret...
['def', 'expand_path', '(', 'path', ')', ':', 'expanded', '=', '[', ']', 'if', 'len', '(', 'path', ')', '<', '2', ':', 'return', 'expanded', 'for', 'i', 'in', 'range', '(', 'len', '(', 'path', ')', '-', '1', ')', ':', 'expanded', '+=', 'bresenham', '(', 'path', '[', 'i', ']', ',', 'path', '[', 'i', '+', '1', ']', ')', ...
Given a compressed path, return a new path that has all the segments in it interpolated.
['Given', 'a', 'compressed', 'path', 'return', 'a', 'new', 'path', 'that', 'has', 'all', 'the', 'segments', 'in', 'it', 'interpolated', '.']
train
https://github.com/brean/python-pathfinding/blob/b857bf85e514a1712b40e29ccb5a473cd7fd5c80/pathfinding/core/util.py#L97-L108
3,637
MartinThoma/hwrt
hwrt/serve.py
work
def work(): """Implement a worker for write-math.com.""" global n cmd = utils.get_project_configuration() if 'worker_api_key' not in cmd: return ("You need to define a 'worker_api_key' in your ~/") chunk_size = 1000 logging.info("Start working with n=%i", n) for _ in range(chunk_s...
python
def work(): """Implement a worker for write-math.com.""" global n cmd = utils.get_project_configuration() if 'worker_api_key' not in cmd: return ("You need to define a 'worker_api_key' in your ~/") chunk_size = 1000 logging.info("Start working with n=%i", n) for _ in range(chunk_s...
['def', 'work', '(', ')', ':', 'global', 'n', 'cmd', '=', 'utils', '.', 'get_project_configuration', '(', ')', 'if', "'worker_api_key'", 'not', 'in', 'cmd', ':', 'return', '(', '"You need to define a \'worker_api_key\' in your ~/"', ')', 'chunk_size', '=', '1000', 'logging', '.', 'info', '(', '"Start working with n=%i"...
Implement a worker for write-math.com.
['Implement', 'a', 'worker', 'for', 'write', '-', 'math', '.', 'com', '.']
train
https://github.com/MartinThoma/hwrt/blob/725c21a3d0f5a30b8492cbc184b3688ceb364e1c/hwrt/serve.py#L260-L332
3,638
MoseleyBioinformaticsLab/mwtab
mwtab/fileio.py
_generate_filenames
def _generate_filenames(sources): """Generate filenames. :param tuple sources: Sequence of strings representing path to file(s). :return: Path to file(s). :rtype: :py:class:`str` """ for source in sources: if os.path.isdir(source): for path, dirlist, filelist in os.walk(sour...
python
def _generate_filenames(sources): """Generate filenames. :param tuple sources: Sequence of strings representing path to file(s). :return: Path to file(s). :rtype: :py:class:`str` """ for source in sources: if os.path.isdir(source): for path, dirlist, filelist in os.walk(sour...
['def', '_generate_filenames', '(', 'sources', ')', ':', 'for', 'source', 'in', 'sources', ':', 'if', 'os', '.', 'path', '.', 'isdir', '(', 'source', ')', ':', 'for', 'path', ',', 'dirlist', ',', 'filelist', 'in', 'os', '.', 'walk', '(', 'source', ')', ':', 'for', 'fname', 'in', 'filelist', ':', 'if', 'GenericFilePath'...
Generate filenames. :param tuple sources: Sequence of strings representing path to file(s). :return: Path to file(s). :rtype: :py:class:`str`
['Generate', 'filenames', '.']
train
https://github.com/MoseleyBioinformaticsLab/mwtab/blob/8c0ae8ab2aa621662f99589ed41e481cf8b7152b/mwtab/fileio.py#L43-L73
3,639
srsudar/eg
eg/config.py
get_expanded_path
def get_expanded_path(path): """Expand ~ and variables in a path. If path is not truthy, return None.""" if path: result = path result = os.path.expanduser(result) result = os.path.expandvars(result) return result else: return None
python
def get_expanded_path(path): """Expand ~ and variables in a path. If path is not truthy, return None.""" if path: result = path result = os.path.expanduser(result) result = os.path.expandvars(result) return result else: return None
['def', 'get_expanded_path', '(', 'path', ')', ':', 'if', 'path', ':', 'result', '=', 'path', 'result', '=', 'os', '.', 'path', '.', 'expanduser', '(', 'result', ')', 'result', '=', 'os', '.', 'path', '.', 'expandvars', '(', 'result', ')', 'return', 'result', 'else', ':', 'return', 'None']
Expand ~ and variables in a path. If path is not truthy, return None.
['Expand', '~', 'and', 'variables', 'in', 'a', 'path', '.', 'If', 'path', 'is', 'not', 'truthy', 'return', 'None', '.']
train
https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L345-L353
3,640
spotify/snakebite
snakebite/minicluster.py
MiniCluster.mkdir
def mkdir(self, src, extra_args=[]): '''Create a directory''' return self._getStdOutCmd([self._hadoop_cmd, 'fs', '-mkdir'] + extra_args + [self._full_hdfs_path(src)], True)
python
def mkdir(self, src, extra_args=[]): '''Create a directory''' return self._getStdOutCmd([self._hadoop_cmd, 'fs', '-mkdir'] + extra_args + [self._full_hdfs_path(src)], True)
['def', 'mkdir', '(', 'self', ',', 'src', ',', 'extra_args', '=', '[', ']', ')', ':', 'return', 'self', '.', '_getStdOutCmd', '(', '[', 'self', '.', '_hadoop_cmd', ',', "'fs'", ',', "'-mkdir'", ']', '+', 'extra_args', '+', '[', 'self', '.', '_full_hdfs_path', '(', 'src', ')', ']', ',', 'True', ')']
Create a directory
['Create', 'a', 'directory']
train
https://github.com/spotify/snakebite/blob/6a456e6100b0c1be66cc1f7f9d7f50494f369da3/snakebite/minicluster.py#L126-L128
3,641
junzis/pyModeS
pyModeS/decoder/adsb.py
nic_v1
def nic_v1(msg, NICs): """Calculate NIC, navigation integrity category, for ADS-B version 1 Args: msg (string): 28 bytes hexadecimal message string NICs (int or string): NIC supplement Returns: int or string: Horizontal Radius of Containment int or string: Vertical Protecti...
python
def nic_v1(msg, NICs): """Calculate NIC, navigation integrity category, for ADS-B version 1 Args: msg (string): 28 bytes hexadecimal message string NICs (int or string): NIC supplement Returns: int or string: Horizontal Radius of Containment int or string: Vertical Protecti...
['def', 'nic_v1', '(', 'msg', ',', 'NICs', ')', ':', 'if', 'typecode', '(', 'msg', ')', '<', '5', 'or', 'typecode', '(', 'msg', ')', '>', '22', ':', 'raise', 'RuntimeError', '(', '"%s: Not a surface position message (5<TC<8), \\\n airborne position message (8<TC<19), \\\n or airborne position with...
Calculate NIC, navigation integrity category, for ADS-B version 1 Args: msg (string): 28 bytes hexadecimal message string NICs (int or string): NIC supplement Returns: int or string: Horizontal Radius of Containment int or string: Vertical Protection Limit
['Calculate', 'NIC', 'navigation', 'integrity', 'category', 'for', 'ADS', '-', 'B', 'version', '1']
train
https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/adsb.py#L278-L308
3,642
OiNutter/lean
lean/__init__.py
Lean.get_template
def get_template(file): ''' Lookup a template class for the given filename or file extension. Return nil when no implementation is found. ''' pattern = str(file).lower() while len(pattern) and not Lean.is_registered(pattern): pattern = os.path.basename(pattern) pattern = re.sub(r'^[...
python
def get_template(file): ''' Lookup a template class for the given filename or file extension. Return nil when no implementation is found. ''' pattern = str(file).lower() while len(pattern) and not Lean.is_registered(pattern): pattern = os.path.basename(pattern) pattern = re.sub(r'^[...
['def', 'get_template', '(', 'file', ')', ':', 'pattern', '=', 'str', '(', 'file', ')', '.', 'lower', '(', ')', 'while', 'len', '(', 'pattern', ')', 'and', 'not', 'Lean', '.', 'is_registered', '(', 'pattern', ')', ':', 'pattern', '=', 'os', '.', 'path', '.', 'basename', '(', 'pattern', ')', 'pattern', '=', 're', '.', '...
Lookup a template class for the given filename or file extension. Return nil when no implementation is found.
['Lookup', 'a', 'template', 'class', 'for', 'the', 'given', 'filename', 'or', 'file', 'extension', '.', 'Return', 'nil', 'when', 'no', 'implementation', 'is', 'found', '.']
train
https://github.com/OiNutter/lean/blob/5d251f923acd44265ed401de14a9ead6752c543f/lean/__init__.py#L61-L103
3,643
user-cont/colin
colin/core/target.py
DockerfileTarget.labels
def labels(self): """ Get list of labels from the target instance. :return: [str] """ if self._labels is None: self._labels = self.instance.labels return self._labels
python
def labels(self): """ Get list of labels from the target instance. :return: [str] """ if self._labels is None: self._labels = self.instance.labels return self._labels
['def', 'labels', '(', 'self', ')', ':', 'if', 'self', '.', '_labels', 'is', 'None', ':', 'self', '.', '_labels', '=', 'self', '.', 'instance', '.', 'labels', 'return', 'self', '.', '_labels']
Get list of labels from the target instance. :return: [str]
['Get', 'list', 'of', 'labels', 'from', 'the', 'target', 'instance', '.']
train
https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/target.py#L131-L139
3,644
maxalbert/tohu
tohu/v6/set_special_methods.py
check_that_operator_can_be_applied_to_produces_items
def check_that_operator_can_be_applied_to_produces_items(op, g1, g2): """ Helper function to check that the operator `op` can be applied to items produced by g1 and g2. """ g1_tmp_copy = g1.spawn() g2_tmp_copy = g2.spawn() sample_item_1 = next(g1_tmp_copy) sample_item_2 = next(g2_tmp_copy) ...
python
def check_that_operator_can_be_applied_to_produces_items(op, g1, g2): """ Helper function to check that the operator `op` can be applied to items produced by g1 and g2. """ g1_tmp_copy = g1.spawn() g2_tmp_copy = g2.spawn() sample_item_1 = next(g1_tmp_copy) sample_item_2 = next(g2_tmp_copy) ...
['def', 'check_that_operator_can_be_applied_to_produces_items', '(', 'op', ',', 'g1', ',', 'g2', ')', ':', 'g1_tmp_copy', '=', 'g1', '.', 'spawn', '(', ')', 'g2_tmp_copy', '=', 'g2', '.', 'spawn', '(', ')', 'sample_item_1', '=', 'next', '(', 'g1_tmp_copy', ')', 'sample_item_2', '=', 'next', '(', 'g2_tmp_copy', ')', 'tr...
Helper function to check that the operator `op` can be applied to items produced by g1 and g2.
['Helper', 'function', 'to', 'check', 'that', 'the', 'operator', 'op', 'can', 'be', 'applied', 'to', 'items', 'produced', 'by', 'g1', 'and', 'g2', '.']
train
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v6/set_special_methods.py#L16-L28
3,645
hackthefed/govtrack2csv
govtrack2csv/__init__.py
extract_subjects
def extract_subjects(bill): """ Return a list subject for legislation. """ logger.debug("Extracting Subjects") subject_map = [] subjects = bill.get('subjects', []) bill_id = bill.get('bill_id', None) bill_type = bill.get('bill_type', None) for sub in subjects: subject_map.ap...
python
def extract_subjects(bill): """ Return a list subject for legislation. """ logger.debug("Extracting Subjects") subject_map = [] subjects = bill.get('subjects', []) bill_id = bill.get('bill_id', None) bill_type = bill.get('bill_type', None) for sub in subjects: subject_map.ap...
['def', 'extract_subjects', '(', 'bill', ')', ':', 'logger', '.', 'debug', '(', '"Extracting Subjects"', ')', 'subject_map', '=', '[', ']', 'subjects', '=', 'bill', '.', 'get', '(', "'subjects'", ',', '[', ']', ')', 'bill_id', '=', 'bill', '.', 'get', '(', "'bill_id'", ',', 'None', ')', 'bill_type', '=', 'bill', '.', '...
Return a list subject for legislation.
['Return', 'a', 'list', 'subject', 'for', 'legislation', '.']
train
https://github.com/hackthefed/govtrack2csv/blob/db991f5fcd3dfda6e6d51fadd286cba983f493e5/govtrack2csv/__init__.py#L285-L300
3,646
qacafe/cdrouter.py
cdrouter/configs.py
ConfigsService.bulk_delete
def bulk_delete(self, ids=None, filter=None, type=None, all=False): # pylint: disable=redefined-builtin """Bulk delete a set of configs. :param ids: (optional) Int list of config IDs. :param filter: (optional) String list of filters. :param type: (optional) `union` or `inter` as string....
python
def bulk_delete(self, ids=None, filter=None, type=None, all=False): # pylint: disable=redefined-builtin """Bulk delete a set of configs. :param ids: (optional) Int list of config IDs. :param filter: (optional) String list of filters. :param type: (optional) `union` or `inter` as string....
['def', 'bulk_delete', '(', 'self', ',', 'ids', '=', 'None', ',', 'filter', '=', 'None', ',', 'type', '=', 'None', ',', 'all', '=', 'False', ')', ':', '# pylint: disable=redefined-builtin', 'return', 'self', '.', 'service', '.', 'bulk_delete', '(', 'self', '.', 'base', ',', 'self', '.', 'RESOURCE', ',', 'ids', '=', 'id...
Bulk delete a set of configs. :param ids: (optional) Int list of config IDs. :param filter: (optional) String list of filters. :param type: (optional) `union` or `inter` as string. :param all: (optional) Apply to all if bool `True`.
['Bulk', 'delete', 'a', 'set', 'of', 'configs', '.']
train
https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/configs.py#L381-L390
3,647
ZELLMECHANIK-DRESDEN/dclab
dclab/isoelastics/__init__.py
Isoelastics.get
def get(self, col1, col2, method, channel_width, flow_rate=None, viscosity=None, add_px_err=False, px_um=None): """Get isoelastics Parameters ---------- col1: str Name of the first feature of all isoelastics (e.g. isoel[0][:,0]) col2: str ...
python
def get(self, col1, col2, method, channel_width, flow_rate=None, viscosity=None, add_px_err=False, px_um=None): """Get isoelastics Parameters ---------- col1: str Name of the first feature of all isoelastics (e.g. isoel[0][:,0]) col2: str ...
['def', 'get', '(', 'self', ',', 'col1', ',', 'col2', ',', 'method', ',', 'channel_width', ',', 'flow_rate', '=', 'None', ',', 'viscosity', '=', 'None', ',', 'add_px_err', '=', 'False', ',', 'px_um', '=', 'None', ')', ':', 'if', 'method', 'not', 'in', 'VALID_METHODS', ':', 'validstr', '=', '","', '.', 'join', '(', 'VAL...
Get isoelastics Parameters ---------- col1: str Name of the first feature of all isoelastics (e.g. isoel[0][:,0]) col2: str Name of the second feature of all isoelastics (e.g. isoel[0][:,1]) method: str The method used ...
['Get', 'isoelastics']
train
https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/isoelastics/__init__.py#L233-L310
3,648
gbiggs/rtctree
rtctree/tree.py
RTCTree.is_zombie
def is_zombie(self, path): '''Is the node pointed to by @ref path a zombie object?''' node = self.get_node(path) if not node: return False return node.is_zombie
python
def is_zombie(self, path): '''Is the node pointed to by @ref path a zombie object?''' node = self.get_node(path) if not node: return False return node.is_zombie
['def', 'is_zombie', '(', 'self', ',', 'path', ')', ':', 'node', '=', 'self', '.', 'get_node', '(', 'path', ')', 'if', 'not', 'node', ':', 'return', 'False', 'return', 'node', '.', 'is_zombie']
Is the node pointed to by @ref path a zombie object?
['Is', 'the', 'node', 'pointed', 'to', 'by']
train
https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/tree.py#L240-L245
3,649
rigetti/quantumflow
quantumflow/gates.py
join_gates
def join_gates(*gates: Gate) -> Gate: """Direct product of two gates. Qubit count is the sum of each gate's bit count.""" vectors = [gate.vec for gate in gates] vec = reduce(outer_product, vectors) return Gate(vec.tensor, vec.qubits)
python
def join_gates(*gates: Gate) -> Gate: """Direct product of two gates. Qubit count is the sum of each gate's bit count.""" vectors = [gate.vec for gate in gates] vec = reduce(outer_product, vectors) return Gate(vec.tensor, vec.qubits)
['def', 'join_gates', '(', '*', 'gates', ':', 'Gate', ')', '->', 'Gate', ':', 'vectors', '=', '[', 'gate', '.', 'vec', 'for', 'gate', 'in', 'gates', ']', 'vec', '=', 'reduce', '(', 'outer_product', ',', 'vectors', ')', 'return', 'Gate', '(', 'vec', '.', 'tensor', ',', 'vec', '.', 'qubits', ')']
Direct product of two gates. Qubit count is the sum of each gate's bit count.
['Direct', 'product', 'of', 'two', 'gates', '.', 'Qubit', 'count', 'is', 'the', 'sum', 'of', 'each', 'gate', 's', 'bit', 'count', '.']
train
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/gates.py#L63-L68
3,650
softlayer/softlayer-python
SoftLayer/CLI/firewall/edit.py
get_formatted_rule
def get_formatted_rule(rule=None): """Helper to format the rule into a user friendly format. :param dict rule: A dict containing one rule of the firewall :returns: a formatted string that get be pushed into the editor """ rule = rule or {} return ('action: %s\n' 'protocol: %s\n' ...
python
def get_formatted_rule(rule=None): """Helper to format the rule into a user friendly format. :param dict rule: A dict containing one rule of the firewall :returns: a formatted string that get be pushed into the editor """ rule = rule or {} return ('action: %s\n' 'protocol: %s\n' ...
['def', 'get_formatted_rule', '(', 'rule', '=', 'None', ')', ':', 'rule', '=', 'rule', 'or', '{', '}', 'return', '(', "'action: %s\\n'", "'protocol: %s\\n'", "'source_ip_address: %s\\n'", "'source_ip_subnet_mask: %s\\n'", "'destination_ip_address: %s\\n'", "'destination_ip_subnet_mask: %s\\n'", "'destination_port_range...
Helper to format the rule into a user friendly format. :param dict rule: A dict containing one rule of the firewall :returns: a formatted string that get be pushed into the editor
['Helper', 'to', 'format', 'the', 'rule', 'into', 'a', 'user', 'friendly', 'format', '.']
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/firewall/edit.py#L108-L132
3,651
watson-developer-cloud/python-sdk
ibm_watson/language_translator_v3.py
LanguageTranslatorV3.translate
def translate(self, text, model_id=None, source=None, target=None, **kwargs): """ Translate. Translates the input text from the source language to the target language. :param list[str] text: Input text in UTF-8 encoding. Multiple entries will result in multipl...
python
def translate(self, text, model_id=None, source=None, target=None, **kwargs): """ Translate. Translates the input text from the source language to the target language. :param list[str] text: Input text in UTF-8 encoding. Multiple entries will result in multipl...
['def', 'translate', '(', 'self', ',', 'text', ',', 'model_id', '=', 'None', ',', 'source', '=', 'None', ',', 'target', '=', 'None', ',', '*', '*', 'kwargs', ')', ':', 'if', 'text', 'is', 'None', ':', 'raise', 'ValueError', '(', "'text must be provided'", ')', 'headers', '=', '{', '}', 'if', "'headers'", 'in', 'kwargs'...
Translate. Translates the input text from the source language to the target language. :param list[str] text: Input text in UTF-8 encoding. Multiple entries will result in multiple translations in the response. :param str model_id: A globally unique string that identifies the underlying...
['Translate', '.']
train
https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/language_translator_v3.py#L110-L154
3,652
minhhoit/yacms
yacms/twitter/managers.py
TweetManager.get_for
def get_for(self, query_type, value): """ Create a query and run it for the given arg if it doesn't exist, and return the tweets for the query. """ from yacms.twitter.models import Query lookup = {"type": query_type, "value": value} query, created = Query.objects....
python
def get_for(self, query_type, value): """ Create a query and run it for the given arg if it doesn't exist, and return the tweets for the query. """ from yacms.twitter.models import Query lookup = {"type": query_type, "value": value} query, created = Query.objects....
['def', 'get_for', '(', 'self', ',', 'query_type', ',', 'value', ')', ':', 'from', 'yacms', '.', 'twitter', '.', 'models', 'import', 'Query', 'lookup', '=', '{', '"type"', ':', 'query_type', ',', '"value"', ':', 'value', '}', 'query', ',', 'created', '=', 'Query', '.', 'objects', '.', 'get_or_create', '(', '*', '*', 'l...
Create a query and run it for the given arg if it doesn't exist, and return the tweets for the query.
['Create', 'a', 'query', 'and', 'run', 'it', 'for', 'the', 'given', 'arg', 'if', 'it', 'doesn', 't', 'exist', 'and', 'return', 'the', 'tweets', 'for', 'the', 'query', '.']
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/twitter/managers.py#L12-L25
3,653
zarr-developers/zarr
zarr/convenience.py
open
def open(store=None, mode='a', **kwargs): """Convenience function to open a group or array using file-mode-like semantics. Parameters ---------- store : MutableMapping or string, optional Store or path to directory in file system or name of zip file. mode : {'r', 'r+', 'a', 'w', 'w-'}, opti...
python
def open(store=None, mode='a', **kwargs): """Convenience function to open a group or array using file-mode-like semantics. Parameters ---------- store : MutableMapping or string, optional Store or path to directory in file system or name of zip file. mode : {'r', 'r+', 'a', 'w', 'w-'}, opti...
['def', 'open', '(', 'store', '=', 'None', ',', 'mode', '=', "'a'", ',', '*', '*', 'kwargs', ')', ':', 'path', '=', 'kwargs', '.', 'get', '(', "'path'", ',', 'None', ')', '# handle polymorphic store arg', 'clobber', '=', 'mode', '==', "'w'", 'store', '=', 'normalize_store_arg', '(', 'store', ',', 'clobber', '=', 'clobb...
Convenience function to open a group or array using file-mode-like semantics. Parameters ---------- store : MutableMapping or string, optional Store or path to directory in file system or name of zip file. mode : {'r', 'r+', 'a', 'w', 'w-'}, optional Persistence mode: 'r' means read onl...
['Convenience', 'function', 'to', 'open', 'a', 'group', 'or', 'array', 'using', 'file', '-', 'mode', '-', 'like', 'semantics', '.']
train
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/convenience.py#L21-L102
3,654
GPflow/GPflow
gpflow/multioutput/conditionals.py
independent_interdomain_conditional
def independent_interdomain_conditional(Kmn, Kmm, Knn, f, *, full_cov=False, full_output_cov=False, q_sqrt=None, white=False): """ The inducing outputs live in the g-space (R^L). Interdomain conditional calculation. :param Kmn: M x L x N x P :param Kmm: L x M...
python
def independent_interdomain_conditional(Kmn, Kmm, Knn, f, *, full_cov=False, full_output_cov=False, q_sqrt=None, white=False): """ The inducing outputs live in the g-space (R^L). Interdomain conditional calculation. :param Kmn: M x L x N x P :param Kmm: L x M...
['def', 'independent_interdomain_conditional', '(', 'Kmn', ',', 'Kmm', ',', 'Knn', ',', 'f', ',', '*', ',', 'full_cov', '=', 'False', ',', 'full_output_cov', '=', 'False', ',', 'q_sqrt', '=', 'None', ',', 'white', '=', 'False', ')', ':', 'logger', '.', 'debug', '(', '"independent_interdomain_conditional"', ')', 'M', ',...
The inducing outputs live in the g-space (R^L). Interdomain conditional calculation. :param Kmn: M x L x N x P :param Kmm: L x M x M :param Knn: N x P or N x N or P x N x N or N x P x N x P :param f: data matrix, M x L :param q_sqrt: L x M x M or M x L :param full_cov: calculate cov...
['The', 'inducing', 'outputs', 'live', 'in', 'the', 'g', '-', 'space', '(', 'R^L', ')', '.', 'Interdomain', 'conditional', 'calculation', '.']
train
https://github.com/GPflow/GPflow/blob/549394f0b1b0696c7b521a065e49bdae6e7acf27/gpflow/multioutput/conditionals.py#L274-L339
3,655
msmbuilder/msmbuilder
msmbuilder/tpt/hub.py
fraction_visited
def fraction_visited(source, sink, waypoint, msm): """ Calculate the fraction of times a walker on `tprob` going from `sources` to `sinks` will travel through the set of states `waypoints` en route. Computes the conditional committors q^{ABC^+} and uses them to find the fraction of paths mentioned ...
python
def fraction_visited(source, sink, waypoint, msm): """ Calculate the fraction of times a walker on `tprob` going from `sources` to `sinks` will travel through the set of states `waypoints` en route. Computes the conditional committors q^{ABC^+} and uses them to find the fraction of paths mentioned ...
['def', 'fraction_visited', '(', 'source', ',', 'sink', ',', 'waypoint', ',', 'msm', ')', ':', 'for_committors', '=', 'committors', '(', '[', 'source', ']', ',', '[', 'sink', ']', ',', 'msm', ')', 'cond_committors', '=', 'conditional_committors', '(', 'source', ',', 'sink', ',', 'waypoint', ',', 'msm', ')', 'if', 'hasa...
Calculate the fraction of times a walker on `tprob` going from `sources` to `sinks` will travel through the set of states `waypoints` en route. Computes the conditional committors q^{ABC^+} and uses them to find the fraction of paths mentioned above. Note that in the notation of Dickson et. al. this c...
['Calculate', 'the', 'fraction', 'of', 'times', 'a', 'walker', 'on', 'tprob', 'going', 'from', 'sources', 'to', 'sinks', 'will', 'travel', 'through', 'the', 'set', 'of', 'states', 'waypoints', 'en', 'route', '.']
train
https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/tpt/hub.py#L27-L83
3,656
striglia/stockfighter
stockfighter/stockfighter.py
Stockfighter.status_for_order
def status_for_order(self, order_id, stock): """Status For An Existing Order https://starfighter.readme.io/docs/status-for-an-existing-order """ url_fragment = 'venues/{venue}/stocks/{stock}/orders/{order_id}'.format( venue=self.venue, stock=stock, or...
python
def status_for_order(self, order_id, stock): """Status For An Existing Order https://starfighter.readme.io/docs/status-for-an-existing-order """ url_fragment = 'venues/{venue}/stocks/{stock}/orders/{order_id}'.format( venue=self.venue, stock=stock, or...
['def', 'status_for_order', '(', 'self', ',', 'order_id', ',', 'stock', ')', ':', 'url_fragment', '=', "'venues/{venue}/stocks/{stock}/orders/{order_id}'", '.', 'format', '(', 'venue', '=', 'self', '.', 'venue', ',', 'stock', '=', 'stock', ',', 'order_id', '=', 'order_id', ',', ')', 'url', '=', 'urljoin', '(', 'self', ...
Status For An Existing Order https://starfighter.readme.io/docs/status-for-an-existing-order
['Status', 'For', 'An', 'Existing', 'Order']
train
https://github.com/striglia/stockfighter/blob/df908f5919d6f861601cd00c906a049d04253d47/stockfighter/stockfighter.py#L94-L105
3,657
bigchaindb/bigchaindb
bigchaindb/backend/connection.py
Connection.connect
def connect(self): """Try to connect to the database. Raises: :exc:`~ConnectionError`: If the connection to the database fails. """ attempt = 0 for i in self.max_tries_counter: attempt += 1 try: self._conn = se...
python
def connect(self): """Try to connect to the database. Raises: :exc:`~ConnectionError`: If the connection to the database fails. """ attempt = 0 for i in self.max_tries_counter: attempt += 1 try: self._conn = se...
['def', 'connect', '(', 'self', ')', ':', 'attempt', '=', '0', 'for', 'i', 'in', 'self', '.', 'max_tries_counter', ':', 'attempt', '+=', '1', 'try', ':', 'self', '.', '_conn', '=', 'self', '.', '_connect', '(', ')', 'except', 'ConnectionError', 'as', 'exc', ':', 'logger', '.', 'warning', '(', "'Attempt %s/%s. Connectio...
Try to connect to the database. Raises: :exc:`~ConnectionError`: If the connection to the database fails.
['Try', 'to', 'connect', 'to', 'the', 'database', '.']
train
https://github.com/bigchaindb/bigchaindb/blob/835fdfcf598918f76139e3b88ee33dd157acaaa7/bigchaindb/backend/connection.py#L148-L169
3,658
youversion/crony
crony/crony.py
CommandCenter.log
def log(self, output, exit_status): """Log given CompletedProcess and return exit status code.""" if exit_status != 0: self.logger.error(f'Error running command! Exit status: {exit_status}, {output}') return exit_status
python
def log(self, output, exit_status): """Log given CompletedProcess and return exit status code.""" if exit_status != 0: self.logger.error(f'Error running command! Exit status: {exit_status}, {output}') return exit_status
['def', 'log', '(', 'self', ',', 'output', ',', 'exit_status', ')', ':', 'if', 'exit_status', '!=', '0', ':', 'self', '.', 'logger', '.', 'error', '(', "f'Error running command! Exit status: {exit_status}, {output}'", ')', 'return', 'exit_status']
Log given CompletedProcess and return exit status code.
['Log', 'given', 'CompletedProcess', 'and', 'return', 'exit', 'status', 'code', '.']
train
https://github.com/youversion/crony/blob/c93d14b809a2e878f1b9d6d53d5a04947896583b/crony/crony.py#L129-L134
3,659
iterative/dvc
dvc/repo/__init__.py
Repo.graph
def graph(self, stages=None, from_directory=None): """Generate a graph by using the given stages on the given directory The nodes of the graph are the stage's path relative to the root. Edges are created when the output of one stage is used as a dependency in other stage. The ...
python
def graph(self, stages=None, from_directory=None): """Generate a graph by using the given stages on the given directory The nodes of the graph are the stage's path relative to the root. Edges are created when the output of one stage is used as a dependency in other stage. The ...
['def', 'graph', '(', 'self', ',', 'stages', '=', 'None', ',', 'from_directory', '=', 'None', ')', ':', 'import', 'networkx', 'as', 'nx', 'from', 'dvc', '.', 'exceptions', 'import', '(', 'OutputDuplicationError', ',', 'StagePathAsOutputError', ',', 'OverlappingOutputPathsError', ',', ')', 'G', '=', 'nx', '.', 'DiGraph'...
Generate a graph by using the given stages on the given directory The nodes of the graph are the stage's path relative to the root. Edges are created when the output of one stage is used as a dependency in other stage. The direction of the edges goes from the stage to its dependency: ...
['Generate', 'a', 'graph', 'by', 'using', 'the', 'given', 'stages', 'on', 'the', 'given', 'directory']
train
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/repo/__init__.py#L300-L404
3,660
zagaran/mongolia
mongolia/mongo_connection.py
authenticate_connection
def authenticate_connection(username, password, db=None): """ Authenticates the current database connection with the passed username and password. If the database connection uses all default parameters, this can be called without connect_to_database. Otherwise, it should be preceded by a connect_t...
python
def authenticate_connection(username, password, db=None): """ Authenticates the current database connection with the passed username and password. If the database connection uses all default parameters, this can be called without connect_to_database. Otherwise, it should be preceded by a connect_t...
['def', 'authenticate_connection', '(', 'username', ',', 'password', ',', 'db', '=', 'None', ')', ':', 'return', 'CONNECTION', '.', 'authenticate', '(', 'username', ',', 'password', ',', 'db', '=', 'db', ')']
Authenticates the current database connection with the passed username and password. If the database connection uses all default parameters, this can be called without connect_to_database. Otherwise, it should be preceded by a connect_to_database call. @param username: the username with which you...
['Authenticates', 'the', 'current', 'database', 'connection', 'with', 'the', 'passed', 'username', 'and', 'password', '.', 'If', 'the', 'database', 'connection', 'uses', 'all', 'default', 'parameters', 'this', 'can', 'be', 'called', 'without', 'connect_to_database', '.', 'Otherwise', 'it', 'should', 'be', 'preceded', '...
train
https://github.com/zagaran/mongolia/blob/82c499345f0a8610c7289545e19f5f633e8a81c0/mongolia/mongo_connection.py#L109-L132
3,661
halfak/python-jsonable
jsonable/functions.py
to_json
def to_json(value): """ Converts a value to a jsonable type. """ if type(value) in JSON_TYPES: return value elif hasattr(value, "to_json"): return value.to_json() elif isinstance(value, list) or isinstance(value, set) or \ isinstance(value, deque) or isinstance(value,...
python
def to_json(value): """ Converts a value to a jsonable type. """ if type(value) in JSON_TYPES: return value elif hasattr(value, "to_json"): return value.to_json() elif isinstance(value, list) or isinstance(value, set) or \ isinstance(value, deque) or isinstance(value,...
['def', 'to_json', '(', 'value', ')', ':', 'if', 'type', '(', 'value', ')', 'in', 'JSON_TYPES', ':', 'return', 'value', 'elif', 'hasattr', '(', 'value', ',', '"to_json"', ')', ':', 'return', 'value', '.', 'to_json', '(', ')', 'elif', 'isinstance', '(', 'value', ',', 'list', ')', 'or', 'isinstance', '(', 'value', ',', '...
Converts a value to a jsonable type.
['Converts', 'a', 'value', 'to', 'a', 'jsonable', 'type', '.']
train
https://github.com/halfak/python-jsonable/blob/70a53aedaca84d078228b3564fdd8f60a586d43f/jsonable/functions.py#L6-L20
3,662
manahl/arctic
arctic/chunkstore/chunkstore.py
ChunkStore.rename
def rename(self, from_symbol, to_symbol, audit=None): """ Rename a symbol Parameters ---------- from_symbol: str the existing symbol that will be renamed to_symbol: str the new symbol name audit: dict audit information ...
python
def rename(self, from_symbol, to_symbol, audit=None): """ Rename a symbol Parameters ---------- from_symbol: str the existing symbol that will be renamed to_symbol: str the new symbol name audit: dict audit information ...
['def', 'rename', '(', 'self', ',', 'from_symbol', ',', 'to_symbol', ',', 'audit', '=', 'None', ')', ':', 'sym', '=', 'self', '.', '_get_symbol_info', '(', 'from_symbol', ')', 'if', 'not', 'sym', ':', 'raise', 'NoDataFoundException', '(', "'No data found for %s'", '%', '(', 'from_symbol', ')', ')', 'if', 'self', '.', '...
Rename a symbol Parameters ---------- from_symbol: str the existing symbol that will be renamed to_symbol: str the new symbol name audit: dict audit information
['Rename', 'a', 'symbol']
train
https://github.com/manahl/arctic/blob/57e110b6e182dbab00e7e214dc26f7d9ec47c120/arctic/chunkstore/chunkstore.py#L193-L226
3,663
blueset/ehForwarderBot
ehforwarderbot/coordinator.py
add_middleware
def add_middleware(middleware: EFBMiddleware): """ Register a middleware with the coordinator. Args: middleware (EFBMiddleware): Middleware to register """ global middlewares if isinstance(middleware, EFBMiddleware): middlewares.append(middleware) else: raise TypeErr...
python
def add_middleware(middleware: EFBMiddleware): """ Register a middleware with the coordinator. Args: middleware (EFBMiddleware): Middleware to register """ global middlewares if isinstance(middleware, EFBMiddleware): middlewares.append(middleware) else: raise TypeErr...
['def', 'add_middleware', '(', 'middleware', ':', 'EFBMiddleware', ')', ':', 'global', 'middlewares', 'if', 'isinstance', '(', 'middleware', ',', 'EFBMiddleware', ')', ':', 'middlewares', '.', 'append', '(', 'middleware', ')', 'else', ':', 'raise', 'TypeError', '(', '"Middleware instance is expected"', ')']
Register a middleware with the coordinator. Args: middleware (EFBMiddleware): Middleware to register
['Register', 'a', 'middleware', 'with', 'the', 'coordinator', '.']
train
https://github.com/blueset/ehForwarderBot/blob/62e8fcfe77b2993aba91623f538f404a90f59f1d/ehforwarderbot/coordinator.py#L70-L81
3,664
google/prettytensor
prettytensor/pretty_tensor_methods.py
split
def split(input_layer, split_dim=0, num_splits=2): """Splits this Tensor along the split_dim into num_splits Equal chunks. Examples: * `[1, 2, 3, 4] -> [1, 2], [3, 4]` * `[[1, 1], [2, 2], [3, 3], [4, 4]] -> [[1, 1], [2, 2]], [[3, 3], [4, 4]]` Args: input_layer: The chainable object, supplied. split...
python
def split(input_layer, split_dim=0, num_splits=2): """Splits this Tensor along the split_dim into num_splits Equal chunks. Examples: * `[1, 2, 3, 4] -> [1, 2], [3, 4]` * `[[1, 1], [2, 2], [3, 3], [4, 4]] -> [[1, 1], [2, 2]], [[3, 3], [4, 4]]` Args: input_layer: The chainable object, supplied. split...
['def', 'split', '(', 'input_layer', ',', 'split_dim', '=', '0', ',', 'num_splits', '=', '2', ')', ':', 'shape', '=', 'input_layer', '.', 'shape', '_check_split_dims', '(', 'num_splits', ',', 'split_dim', ',', 'shape', ')', 'splits', '=', 'tf', '.', 'split', '(', 'value', '=', 'input_layer', ',', 'num_or_size_splits', ...
Splits this Tensor along the split_dim into num_splits Equal chunks. Examples: * `[1, 2, 3, 4] -> [1, 2], [3, 4]` * `[[1, 1], [2, 2], [3, 3], [4, 4]] -> [[1, 1], [2, 2]], [[3, 3], [4, 4]]` Args: input_layer: The chainable object, supplied. split_dim: The dimension to split along. Defaults to batch. ...
['Splits', 'this', 'Tensor', 'along', 'the', 'split_dim', 'into', 'num_splits', 'Equal', 'chunks', '.']
train
https://github.com/google/prettytensor/blob/75daa0b11252590f548da5647addc0ea610c4c45/prettytensor/pretty_tensor_methods.py#L569-L591
3,665
chrisbouchard/braillegraph
braillegraph/__main__.py
run
def run(): """Display the arguments as a braille graph on standard output.""" # We override the program name to reflect that this script must be run with # the python executable. parser = argparse.ArgumentParser( prog='python -m braillegraph', description='Print a braille bar graph of t...
python
def run(): """Display the arguments as a braille graph on standard output.""" # We override the program name to reflect that this script must be run with # the python executable. parser = argparse.ArgumentParser( prog='python -m braillegraph', description='Print a braille bar graph of t...
['def', 'run', '(', ')', ':', '# We override the program name to reflect that this script must be run with', '# the python executable.', 'parser', '=', 'argparse', '.', 'ArgumentParser', '(', 'prog', '=', "'python -m braillegraph'", ',', 'description', '=', "'Print a braille bar graph of the given integers.'", ')', "# ...
Display the arguments as a braille graph on standard output.
['Display', 'the', 'arguments', 'as', 'a', 'braille', 'graph', 'on', 'standard', 'output', '.']
train
https://github.com/chrisbouchard/braillegraph/blob/744ca8394676579cfb11e5c297c9bd794ab5bd78/braillegraph/__main__.py#L45-L88
3,666
adafruit/Adafruit_Python_CharLCD
Adafruit_CharLCD/Adafruit_CharLCD.py
Adafruit_CharLCD.set_right_to_left
def set_right_to_left(self): """Set text direction right to left.""" self.displaymode &= ~LCD_ENTRYLEFT self.write8(LCD_ENTRYMODESET | self.displaymode)
python
def set_right_to_left(self): """Set text direction right to left.""" self.displaymode &= ~LCD_ENTRYLEFT self.write8(LCD_ENTRYMODESET | self.displaymode)
['def', 'set_right_to_left', '(', 'self', ')', ':', 'self', '.', 'displaymode', '&=', '~', 'LCD_ENTRYLEFT', 'self', '.', 'write8', '(', 'LCD_ENTRYMODESET', '|', 'self', '.', 'displaymode', ')']
Set text direction right to left.
['Set', 'text', 'direction', 'right', 'to', 'left', '.']
train
https://github.com/adafruit/Adafruit_Python_CharLCD/blob/c126e6b673074c12a03f4bd36afb2fe40272341e/Adafruit_CharLCD/Adafruit_CharLCD.py#L228-L231
3,667
google/openhtf
openhtf/output/servers/dashboard_server.py
DashboardPubSub.publish_if_new
def publish_if_new(cls): """If the station map has changed, publish the new information.""" message = cls.make_message() if message != cls.last_message: super(DashboardPubSub, cls).publish(message) cls.last_message = message
python
def publish_if_new(cls): """If the station map has changed, publish the new information.""" message = cls.make_message() if message != cls.last_message: super(DashboardPubSub, cls).publish(message) cls.last_message = message
['def', 'publish_if_new', '(', 'cls', ')', ':', 'message', '=', 'cls', '.', 'make_message', '(', ')', 'if', 'message', '!=', 'cls', '.', 'last_message', ':', 'super', '(', 'DashboardPubSub', ',', 'cls', ')', '.', 'publish', '(', 'message', ')', 'cls', '.', 'last_message', '=', 'message']
If the station map has changed, publish the new information.
['If', 'the', 'station', 'map', 'has', 'changed', 'publish', 'the', 'new', 'information', '.']
train
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/output/servers/dashboard_server.py#L92-L97
3,668
daviddrysdale/python-phonenumbers
python/phonenumbers/shortnumberinfo.py
_example_short_number_for_cost
def _example_short_number_for_cost(region_code, cost): """Gets a valid short number for the specified cost category. Arguments: region_code -- the region for which an example short number is needed. cost -- the cost category of number that is needed. Returns a valid short number for the specified ...
python
def _example_short_number_for_cost(region_code, cost): """Gets a valid short number for the specified cost category. Arguments: region_code -- the region for which an example short number is needed. cost -- the cost category of number that is needed. Returns a valid short number for the specified ...
['def', '_example_short_number_for_cost', '(', 'region_code', ',', 'cost', ')', ':', 'metadata', '=', 'PhoneMetadata', '.', 'short_metadata_for_region', '(', 'region_code', ')', 'if', 'metadata', 'is', 'None', ':', 'return', 'U_EMPTY_STRING', 'desc', '=', 'None', 'if', 'cost', '==', 'ShortNumberCost', '.', 'TOLL_FREE',...
Gets a valid short number for the specified cost category. Arguments: region_code -- the region for which an example short number is needed. cost -- the cost category of number that is needed. Returns a valid short number for the specified region and cost category. Returns an empty string when the...
['Gets', 'a', 'valid', 'short', 'number', 'for', 'the', 'specified', 'cost', 'category', '.']
train
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/shortnumberinfo.py#L295-L322
3,669
msfrank/cifparser
cifparser/valuetree.py
ValueTree.append_field
def append_field(self, path, name, value): """ Appends the field to the container at the specified path. :param path: str or Path instance :param name: :type name: str :param value: :type value: str """ path = make_path(path) container = s...
python
def append_field(self, path, name, value): """ Appends the field to the container at the specified path. :param path: str or Path instance :param name: :type name: str :param value: :type value: str """ path = make_path(path) container = s...
['def', 'append_field', '(', 'self', ',', 'path', ',', 'name', ',', 'value', ')', ':', 'path', '=', 'make_path', '(', 'path', ')', 'container', '=', 'self', '.', 'get_container', '(', 'path', ')', 'current', '=', 'container', '.', '_values', '.', 'get', '(', 'name', ',', 'None', ')', 'if', 'current', 'is', 'None', ':',...
Appends the field to the container at the specified path. :param path: str or Path instance :param name: :type name: str :param value: :type value: str
['Appends', 'the', 'field', 'to', 'the', 'container', 'at', 'the', 'specified', 'path', '.']
train
https://github.com/msfrank/cifparser/blob/ecd899ba2e7b990e2cec62b115742d830e7e4384/cifparser/valuetree.py#L177-L197
3,670
gem/oq-engine
openquake/commonlib/logictree.py
BranchSet.filter_source
def filter_source(self, source): # pylint: disable=R0911,R0912 """ Apply filters to ``source`` and return ``True`` if uncertainty should be applied to it. """ for key, value in self.filters.items(): if key == 'applyToTectonicRegionType': if val...
python
def filter_source(self, source): # pylint: disable=R0911,R0912 """ Apply filters to ``source`` and return ``True`` if uncertainty should be applied to it. """ for key, value in self.filters.items(): if key == 'applyToTectonicRegionType': if val...
['def', 'filter_source', '(', 'self', ',', 'source', ')', ':', '# pylint: disable=R0911,R0912', 'for', 'key', ',', 'value', 'in', 'self', '.', 'filters', '.', 'items', '(', ')', ':', 'if', 'key', '==', "'applyToTectonicRegionType'", ':', 'if', 'value', '!=', 'source', '.', 'tectonic_region_type', ':', 'return', 'False'...
Apply filters to ``source`` and return ``True`` if uncertainty should be applied to it.
['Apply', 'filters', 'to', 'source', 'and', 'return', 'True', 'if', 'uncertainty', 'should', 'be', 'applied', 'to', 'it', '.']
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/logictree.py#L343-L379
3,671
django-salesforce/django-salesforce
salesforce/utils.py
get_soap_client
def get_soap_client(db_alias, client_class=None): """ Create the SOAP client for the current user logged in the db_alias The default created client is "beatbox.PythonClient", but an alternative client is possible. (i.e. other subtype of beatbox.XMLClient) """ if not beatbox: raise Inter...
python
def get_soap_client(db_alias, client_class=None): """ Create the SOAP client for the current user logged in the db_alias The default created client is "beatbox.PythonClient", but an alternative client is possible. (i.e. other subtype of beatbox.XMLClient) """ if not beatbox: raise Inter...
['def', 'get_soap_client', '(', 'db_alias', ',', 'client_class', '=', 'None', ')', ':', 'if', 'not', 'beatbox', ':', 'raise', 'InterfaceError', '(', '"To use SOAP API, you\'ll need to install the Beatbox package."', ')', 'if', 'client_class', 'is', 'None', ':', 'client_class', '=', 'beatbox', '.', 'PythonClient', 'soap...
Create the SOAP client for the current user logged in the db_alias The default created client is "beatbox.PythonClient", but an alternative client is possible. (i.e. other subtype of beatbox.XMLClient)
['Create', 'the', 'SOAP', 'client', 'for', 'the', 'current', 'user', 'logged', 'in', 'the', 'db_alias']
train
https://github.com/django-salesforce/django-salesforce/blob/6fd5643dba69d49c5881de50875cf90204a8f808/salesforce/utils.py#L20-L46
3,672
rosenbrockc/acorn
acorn/ipython.py
record_markdown
def record_markdown(text, cellid): """Records the specified markdown text to the acorn database. Args: text (str): the *raw* markdown text entered into the cell in the ipython notebook. """ from acorn.logging.database import record from time import time ekey = "nb-{}".format(c...
python
def record_markdown(text, cellid): """Records the specified markdown text to the acorn database. Args: text (str): the *raw* markdown text entered into the cell in the ipython notebook. """ from acorn.logging.database import record from time import time ekey = "nb-{}".format(c...
['def', 'record_markdown', '(', 'text', ',', 'cellid', ')', ':', 'from', 'acorn', '.', 'logging', '.', 'database', 'import', 'record', 'from', 'time', 'import', 'time', 'ekey', '=', '"nb-{}"', '.', 'format', '(', 'cellid', ')', 'global', '_cellid_map', 'if', 'cellid', 'not', 'in', '_cellid_map', ':', 'from', 'acorn', '...
Records the specified markdown text to the acorn database. Args: text (str): the *raw* markdown text entered into the cell in the ipython notebook.
['Records', 'the', 'specified', 'markdown', 'text', 'to', 'the', 'acorn', 'database', '.']
train
https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/ipython.py#L488-L534
3,673
brocade/pynos
pynos/versions/ver_6/ver_6_0_1/yang/brocade_port_profile.py
brocade_port_profile.port_profile_restrict_flooding_container_restrict_flooding
def port_profile_restrict_flooding_container_restrict_flooding(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") port_profile = ET.SubElement(config, "port-profile", xmlns="urn:brocade.com:mgmt:brocade-port-profile") name_key = ET.SubElement(port_profile, ...
python
def port_profile_restrict_flooding_container_restrict_flooding(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") port_profile = ET.SubElement(config, "port-profile", xmlns="urn:brocade.com:mgmt:brocade-port-profile") name_key = ET.SubElement(port_profile, ...
['def', 'port_profile_restrict_flooding_container_restrict_flooding', '(', 'self', ',', '*', '*', 'kwargs', ')', ':', 'config', '=', 'ET', '.', 'Element', '(', '"config"', ')', 'port_profile', '=', 'ET', '.', 'SubElement', '(', 'config', ',', '"port-profile"', ',', 'xmlns', '=', '"urn:brocade.com:mgmt:brocade-port-prof...
Auto Generated Code
['Auto', 'Generated', 'Code']
train
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_port_profile.py#L660-L671
3,674
yyuu/botornado
botornado/__init__.py
connect_euca
def connect_euca(host=None, aws_access_key_id=None, aws_secret_access_key=None, port=8773, path='/services/Eucalyptus', is_secure=False, **kwargs): """ Connect to a Eucalyptus service. :type host: string :param host: the host name or ip address of the Eucalyptus server...
python
def connect_euca(host=None, aws_access_key_id=None, aws_secret_access_key=None, port=8773, path='/services/Eucalyptus', is_secure=False, **kwargs): """ Connect to a Eucalyptus service. :type host: string :param host: the host name or ip address of the Eucalyptus server...
['def', 'connect_euca', '(', 'host', '=', 'None', ',', 'aws_access_key_id', '=', 'None', ',', 'aws_secret_access_key', '=', 'None', ',', 'port', '=', '8773', ',', 'path', '=', "'/services/Eucalyptus'", ',', 'is_secure', '=', 'False', ',', '*', '*', 'kwargs', ')', ':', 'raise', 'BotoClientError', '(', "'Not Implemented'...
Connect to a Eucalyptus service. :type host: string :param host: the host name or ip address of the Eucalyptus server :type aws_access_key_id: string :param aws_access_key_id: Your AWS Access Key ID :type aws_secret_access_key: string :param aws_secret_access_key: Your AWS Secret Access Key ...
['Connect', 'to', 'a', 'Eucalyptus', 'service', '.']
train
https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/botornado/__init__.py#L259-L277
3,675
pycontribs/pyrax
pyrax/cloudmonitoring.py
CloudMonitorNotificationManager.create
def create(self, notification_type, label=None, name=None, details=None): """ Defines a notification for handling an alarm. """ uri = "/%s" % self.uri_base body = {"label": label or name, "type": utils.get_id(notification_type), "details": details,...
python
def create(self, notification_type, label=None, name=None, details=None): """ Defines a notification for handling an alarm. """ uri = "/%s" % self.uri_base body = {"label": label or name, "type": utils.get_id(notification_type), "details": details,...
['def', 'create', '(', 'self', ',', 'notification_type', ',', 'label', '=', 'None', ',', 'name', '=', 'None', ',', 'details', '=', 'None', ')', ':', 'uri', '=', '"/%s"', '%', 'self', '.', 'uri_base', 'body', '=', '{', '"label"', ':', 'label', 'or', 'name', ',', '"type"', ':', 'utils', '.', 'get_id', '(', 'notification_...
Defines a notification for handling an alarm.
['Defines', 'a', 'notification', 'for', 'handling', 'an', 'alarm', '.']
train
https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/cloudmonitoring.py#L289-L299
3,676
DataDog/integrations-core
sqlserver/datadog_checks/sqlserver/sqlserver.py
SQLServer._conn_string_adodbapi
def _conn_string_adodbapi(self, db_key, instance=None, conn_key=None, db_name=None): ''' Return a connection string to use with adodbapi ''' if instance: _, host, username, password, database, _ = self._get_access_info(instance, db_key, db_name) elif conn_key: _, ...
python
def _conn_string_adodbapi(self, db_key, instance=None, conn_key=None, db_name=None): ''' Return a connection string to use with adodbapi ''' if instance: _, host, username, password, database, _ = self._get_access_info(instance, db_key, db_name) elif conn_key: _, ...
['def', '_conn_string_adodbapi', '(', 'self', ',', 'db_key', ',', 'instance', '=', 'None', ',', 'conn_key', '=', 'None', ',', 'db_name', '=', 'None', ')', ':', 'if', 'instance', ':', '_', ',', 'host', ',', 'username', ',', 'password', ',', 'database', ',', '_', '=', 'self', '.', '_get_access_info', '(', 'instance', ','...
Return a connection string to use with adodbapi
['Return', 'a', 'connection', 'string', 'to', 'use', 'with', 'adodbapi']
train
https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/sqlserver/datadog_checks/sqlserver/sqlserver.py#L391-L408
3,677
mushkevych/scheduler
synergy/scheduler/timetable.py
Timetable.load_tree
def load_tree(self): """ method iterates thru all objects older than synergy_start_timeperiod parameter in job collections and loads them into this timetable""" timeperiod = settings.settings['synergy_start_timeperiod'] yearly_timeperiod = time_helper.cast_to_time_qualifier(QUALIFIER_YEA...
python
def load_tree(self): """ method iterates thru all objects older than synergy_start_timeperiod parameter in job collections and loads them into this timetable""" timeperiod = settings.settings['synergy_start_timeperiod'] yearly_timeperiod = time_helper.cast_to_time_qualifier(QUALIFIER_YEA...
['def', 'load_tree', '(', 'self', ')', ':', 'timeperiod', '=', 'settings', '.', 'settings', '[', "'synergy_start_timeperiod'", ']', 'yearly_timeperiod', '=', 'time_helper', '.', 'cast_to_time_qualifier', '(', 'QUALIFIER_YEARLY', ',', 'timeperiod', ')', 'monthly_timeperiod', '=', 'time_helper', '.', 'cast_to_time_qualif...
method iterates thru all objects older than synergy_start_timeperiod parameter in job collections and loads them into this timetable
['method', 'iterates', 'thru', 'all', 'objects', 'older', 'than', 'synergy_start_timeperiod', 'parameter', 'in', 'job', 'collections', 'and', 'loads', 'them', 'into', 'this', 'timetable']
train
https://github.com/mushkevych/scheduler/blob/6740331360f49083c208085fb5a60ce80ebf418b/synergy/scheduler/timetable.py#L207-L219
3,678
fake-name/WebRequest
WebRequest/WebRequestClass.py
WebGetRobust.getFileNameMime
def getFileNameMime(self, requestedUrl, *args, **kwargs): ''' Give a requested page (note: the arguments for this call are forwarded to getpage()), return the content at the target URL, the filename for the target content, and the mimetype for the content at the target URL, as a 3-tuple (pgctnt, hName, mime). ...
python
def getFileNameMime(self, requestedUrl, *args, **kwargs): ''' Give a requested page (note: the arguments for this call are forwarded to getpage()), return the content at the target URL, the filename for the target content, and the mimetype for the content at the target URL, as a 3-tuple (pgctnt, hName, mime). ...
['def', 'getFileNameMime', '(', 'self', ',', 'requestedUrl', ',', '*', 'args', ',', '*', '*', 'kwargs', ')', ':', 'if', "'returnMultiple'", 'in', 'kwargs', ':', 'raise', 'Exceptions', '.', 'ArgumentError', '(', '"getFileAndName cannot be called with \'returnMultiple\'"', ',', 'requestedUrl', ')', 'if', "'soup'", 'in', ...
Give a requested page (note: the arguments for this call are forwarded to getpage()), return the content at the target URL, the filename for the target content, and the mimetype for the content at the target URL, as a 3-tuple (pgctnt, hName, mime). The filename specified in the content-disposition header is used...
['Give', 'a', 'requested', 'page', '(', 'note', ':', 'the', 'arguments', 'for', 'this', 'call', 'are', 'forwarded', 'to', 'getpage', '()', ')', 'return', 'the', 'content', 'at', 'the', 'target', 'URL', 'the', 'filename', 'for', 'the', 'target', 'content', 'and', 'the', 'mimetype', 'for', 'the', 'content', 'at', 'the', ...
train
https://github.com/fake-name/WebRequest/blob/b6c94631ff88b5f81f26a9f99a2d5c706810b11f/WebRequest/WebRequestClass.py#L292-L334
3,679
kajala/django-jutil
jutil/dates.py
this_month
def this_month(today: datetime=None, tz=None): """ Returns current month begin (inclusive) and end (exclusive). :param today: Some date in the month (defaults current datetime) :param tz: Timezone (defaults pytz UTC) :return: begin (inclusive), end (exclusive) """ if today is None: t...
python
def this_month(today: datetime=None, tz=None): """ Returns current month begin (inclusive) and end (exclusive). :param today: Some date in the month (defaults current datetime) :param tz: Timezone (defaults pytz UTC) :return: begin (inclusive), end (exclusive) """ if today is None: t...
['def', 'this_month', '(', 'today', ':', 'datetime', '=', 'None', ',', 'tz', '=', 'None', ')', ':', 'if', 'today', 'is', 'None', ':', 'today', '=', 'datetime', '.', 'utcnow', '(', ')', 'begin', '=', 'datetime', '(', 'day', '=', '1', ',', 'month', '=', 'today', '.', 'month', ',', 'year', '=', 'today', '.', 'year', ')', ...
Returns current month begin (inclusive) and end (exclusive). :param today: Some date in the month (defaults current datetime) :param tz: Timezone (defaults pytz UTC) :return: begin (inclusive), end (exclusive)
['Returns', 'current', 'month', 'begin', '(', 'inclusive', ')', 'and', 'end', '(', 'exclusive', ')', '.', ':', 'param', 'today', ':', 'Some', 'date', 'in', 'the', 'month', '(', 'defaults', 'current', 'datetime', ')', ':', 'param', 'tz', ':', 'Timezone', '(', 'defaults', 'pytz', 'UTC', ')', ':', 'return', ':', 'begin', ...
train
https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/dates.py#L76-L88
3,680
santoshphilip/eppy
eppy/EPlusInterfaceFunctions/mylib2.py
tabfile2doefile
def tabfile2doefile(tabfile, doefile): """tabfile2doefile""" alist = tabfile2list(tabfile) astr = list2doe(alist) mylib1.write_str2file(doefile, astr)
python
def tabfile2doefile(tabfile, doefile): """tabfile2doefile""" alist = tabfile2list(tabfile) astr = list2doe(alist) mylib1.write_str2file(doefile, astr)
['def', 'tabfile2doefile', '(', 'tabfile', ',', 'doefile', ')', ':', 'alist', '=', 'tabfile2list', '(', 'tabfile', ')', 'astr', '=', 'list2doe', '(', 'alist', ')', 'mylib1', '.', 'write_str2file', '(', 'doefile', ',', 'astr', ')']
tabfile2doefile
['tabfile2doefile']
train
https://github.com/santoshphilip/eppy/blob/55410ff7c11722f35bc4331ff5e00a0b86f787e1/eppy/EPlusInterfaceFunctions/mylib2.py#L90-L94
3,681
tradenity/python-sdk
tradenity/resources/country.py
Country.get_country_by_id
def get_country_by_id(cls, country_id, **kwargs): """Find Country Return single instance of Country by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_country_by_id(country_id, asy...
python
def get_country_by_id(cls, country_id, **kwargs): """Find Country Return single instance of Country by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_country_by_id(country_id, asy...
['def', 'get_country_by_id', '(', 'cls', ',', 'country_id', ',', '*', '*', 'kwargs', ')', ':', 'kwargs', '[', "'_return_http_data_only'", ']', '=', 'True', 'if', 'kwargs', '.', 'get', '(', "'async'", ')', ':', 'return', 'cls', '.', '_get_country_by_id_with_http_info', '(', 'country_id', ',', '*', '*', 'kwargs', ')', 'e...
Find Country Return single instance of Country by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_country_by_id(country_id, async=True) >>> result = thread.get() :param as...
['Find', 'Country']
train
https://github.com/tradenity/python-sdk/blob/d13fbe23f4d6ff22554c6d8d2deaf209371adaf1/tradenity/resources/country.py#L599-L619
3,682
lovvskillz/python-discord-webhook
discord_webhook/webhook.py
DiscordEmbed.set_thumbnail
def set_thumbnail(self, **kwargs): """ set thumbnail of embed :keyword url: source url of thumbnail (only supports http(s) and attachments) :keyword proxy_url: a proxied thumbnail of the image :keyword height: height of thumbnail :keyword width: width of thumbnail ...
python
def set_thumbnail(self, **kwargs): """ set thumbnail of embed :keyword url: source url of thumbnail (only supports http(s) and attachments) :keyword proxy_url: a proxied thumbnail of the image :keyword height: height of thumbnail :keyword width: width of thumbnail ...
['def', 'set_thumbnail', '(', 'self', ',', '*', '*', 'kwargs', ')', ':', 'self', '.', 'thumbnail', '=', '{', "'url'", ':', 'kwargs', '.', 'get', '(', "'url'", ')', ',', "'proxy_url'", ':', 'kwargs', '.', 'get', '(', "'proxy_url'", ')', ',', "'height'", ':', 'kwargs', '.', 'get', '(', "'height'", ')', ',', "'width'", ':...
set thumbnail of embed :keyword url: source url of thumbnail (only supports http(s) and attachments) :keyword proxy_url: a proxied thumbnail of the image :keyword height: height of thumbnail :keyword width: width of thumbnail
['set', 'thumbnail', 'of', 'embed', ':', 'keyword', 'url', ':', 'source', 'url', 'of', 'thumbnail', '(', 'only', 'supports', 'http', '(', 's', ')', 'and', 'attachments', ')', ':', 'keyword', 'proxy_url', ':', 'a', 'proxied', 'thumbnail', 'of', 'the', 'image', ':', 'keyword', 'height', ':', 'height', 'of', 'thumbnail', ...
train
https://github.com/lovvskillz/python-discord-webhook/blob/5278184078c9da9362b6343c478a92e0904a7f83/discord_webhook/webhook.py#L205-L218
3,683
sailthru/sailthru-python-client
sailthru/sailthru_client.py
SailthruClient.multi_send
def multi_send(self, template, emails, _vars=None, evars=None, schedule_time=None, options=None): """ Remotely send an email template to multiple email addresses. http://docs.sailthru.com/api/send @param template: template string @param emails: List with email values or comma sep...
python
def multi_send(self, template, emails, _vars=None, evars=None, schedule_time=None, options=None): """ Remotely send an email template to multiple email addresses. http://docs.sailthru.com/api/send @param template: template string @param emails: List with email values or comma sep...
['def', 'multi_send', '(', 'self', ',', 'template', ',', 'emails', ',', '_vars', '=', 'None', ',', 'evars', '=', 'None', ',', 'schedule_time', '=', 'None', ',', 'options', '=', 'None', ')', ':', '_vars', '=', '_vars', 'or', '{', '}', 'evars', '=', 'evars', 'or', '{', '}', 'options', '=', 'options', 'or', '{', '}', 'dat...
Remotely send an email template to multiple email addresses. http://docs.sailthru.com/api/send @param template: template string @param emails: List with email values or comma separated email string @param _vars: a key/value hash of the replacement vars to use in the send. Each var may be...
['Remotely', 'send', 'an', 'email', 'template', 'to', 'multiple', 'email', 'addresses', '.', 'http', ':', '//', 'docs', '.', 'sailthru', '.', 'com', '/', 'api', '/', 'send']
train
https://github.com/sailthru/sailthru-python-client/blob/22aa39ba0c5bddd7b8743e24ada331128c0f4f54/sailthru/sailthru_client.py#L88-L108
3,684
cqparts/cqparts
src/cqparts_template/catalogue/scripts/build.py
_relative_path_to
def _relative_path_to(path_list, filename): """Get a neat relative path to files relative to the CWD""" return os.path.join( os.path.relpath(os.path.join(*path_list), os.getcwd()), filename )
python
def _relative_path_to(path_list, filename): """Get a neat relative path to files relative to the CWD""" return os.path.join( os.path.relpath(os.path.join(*path_list), os.getcwd()), filename )
['def', '_relative_path_to', '(', 'path_list', ',', 'filename', ')', ':', 'return', 'os', '.', 'path', '.', 'join', '(', 'os', '.', 'path', '.', 'relpath', '(', 'os', '.', 'path', '.', 'join', '(', '*', 'path_list', ')', ',', 'os', '.', 'getcwd', '(', ')', ')', ',', 'filename', ')']
Get a neat relative path to files relative to the CWD
['Get', 'a', 'neat', 'relative', 'path', 'to', 'files', 'relative', 'to', 'the', 'CWD']
train
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_template/catalogue/scripts/build.py#L21-L26
3,685
pyvisa/pyvisa
pyvisa/resources/resource.py
Resource.lock_context
def lock_context(self, timeout='default', requested_key='exclusive'): """A context that locks :param timeout: Absolute time period (in milliseconds) that a resource waits to get unlocked by the locking session before returning an error. (Defaults to self....
python
def lock_context(self, timeout='default', requested_key='exclusive'): """A context that locks :param timeout: Absolute time period (in milliseconds) that a resource waits to get unlocked by the locking session before returning an error. (Defaults to self....
['def', 'lock_context', '(', 'self', ',', 'timeout', '=', "'default'", ',', 'requested_key', '=', "'exclusive'", ')', ':', 'if', 'requested_key', '==', "'exclusive'", ':', 'self', '.', 'lock_excl', '(', 'timeout', ')', 'access_key', '=', 'None', 'else', ':', 'access_key', '=', 'self', '.', 'lock', '(', 'timeout', ',', ...
A context that locks :param timeout: Absolute time period (in milliseconds) that a resource waits to get unlocked by the locking session before returning an error. (Defaults to self.timeout) :param requested_key: When using default of 'exclusive' the lock...
['A', 'context', 'that', 'locks']
train
https://github.com/pyvisa/pyvisa/blob/b8b2d4371e1f00782856aa9176ff1ced6bcb3798/pyvisa/resources/resource.py#L385-L407
3,686
joeyespo/grip
grip/renderers.py
OfflineRenderer.render
def render(self, text, auth=None): """ Renders the specified markdown content and embedded styles. """ if markdown is None: import markdown if UrlizeExtension is None: from .mdx_urlize import UrlizeExtension return markdown.markdown(text, extension...
python
def render(self, text, auth=None): """ Renders the specified markdown content and embedded styles. """ if markdown is None: import markdown if UrlizeExtension is None: from .mdx_urlize import UrlizeExtension return markdown.markdown(text, extension...
['def', 'render', '(', 'self', ',', 'text', ',', 'auth', '=', 'None', ')', ':', 'if', 'markdown', 'is', 'None', ':', 'import', 'markdown', 'if', 'UrlizeExtension', 'is', 'None', ':', 'from', '.', 'mdx_urlize', 'import', 'UrlizeExtension', 'return', 'markdown', '.', 'markdown', '(', 'text', ',', 'extensions', '=', '[', ...
Renders the specified markdown content and embedded styles.
['Renders', 'the', 'specified', 'markdown', 'content', 'and', 'embedded', 'styles', '.']
train
https://github.com/joeyespo/grip/blob/ce933ccc4ca8e0d3718f271c59bd530a4518bf63/grip/renderers.py#L95-L110
3,687
rameshg87/pyremotevbox
pyremotevbox/ZSI/wstools/c14n.py
_utilized
def _utilized(n, node, other_attrs, unsuppressedPrefixes): '''_utilized(n, node, other_attrs, unsuppressedPrefixes) -> boolean Return true if that nodespace is utilized within the node''' if n.startswith('xmlns:'): n = n[6:] elif n.startswith('xmlns'): n = n[5:] if (n=="" and node.pr...
python
def _utilized(n, node, other_attrs, unsuppressedPrefixes): '''_utilized(n, node, other_attrs, unsuppressedPrefixes) -> boolean Return true if that nodespace is utilized within the node''' if n.startswith('xmlns:'): n = n[6:] elif n.startswith('xmlns'): n = n[5:] if (n=="" and node.pr...
['def', '_utilized', '(', 'n', ',', 'node', ',', 'other_attrs', ',', 'unsuppressedPrefixes', ')', ':', 'if', 'n', '.', 'startswith', '(', "'xmlns:'", ')', ':', 'n', '=', 'n', '[', '6', ':', ']', 'elif', 'n', '.', 'startswith', '(', "'xmlns'", ')', ':', 'n', '=', 'n', '[', '5', ':', ']', 'if', '(', 'n', '==', '""', 'and...
_utilized(n, node, other_attrs, unsuppressedPrefixes) -> boolean Return true if that nodespace is utilized within the node
['_utilized', '(', 'n', 'node', 'other_attrs', 'unsuppressedPrefixes', ')', '-', '>', 'boolean', 'Return', 'true', 'if', 'that', 'nodespace', 'is', 'utilized', 'within', 'the', 'node']
train
https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/wstools/c14n.py#L91-L108
3,688
EventTeam/beliefs
src/beliefs/cells/colors.py
RGBColorCell.from_name
def from_name(clz, name): """ Instantiates the object from a known name """ if isinstance(name, list) and "green" in name: name = "teal" assert name in COLOR_NAMES, 'Unknown color name' r, b, g = COLOR_NAMES[name] return clz(r, b, g)
python
def from_name(clz, name): """ Instantiates the object from a known name """ if isinstance(name, list) and "green" in name: name = "teal" assert name in COLOR_NAMES, 'Unknown color name' r, b, g = COLOR_NAMES[name] return clz(r, b, g)
['def', 'from_name', '(', 'clz', ',', 'name', ')', ':', 'if', 'isinstance', '(', 'name', ',', 'list', ')', 'and', '"green"', 'in', 'name', ':', 'name', '=', '"teal"', 'assert', 'name', 'in', 'COLOR_NAMES', ',', "'Unknown color name'", 'r', ',', 'b', ',', 'g', '=', 'COLOR_NAMES', '[', 'name', ']', 'return', 'clz', '(', ...
Instantiates the object from a known name
['Instantiates', 'the', 'object', 'from', 'a', 'known', 'name']
train
https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/colors.py#L27-L35
3,689
ultrabug/py3status
py3status/command.py
CommandServer.run
def run(self): """ Main thread listen to socket and send any commands to the CommandRunner. """ while True: try: data = None # Wait for a connection if self.debug: self.py3_wrapper.log("waiting for a ...
python
def run(self): """ Main thread listen to socket and send any commands to the CommandRunner. """ while True: try: data = None # Wait for a connection if self.debug: self.py3_wrapper.log("waiting for a ...
['def', 'run', '(', 'self', ')', ':', 'while', 'True', ':', 'try', ':', 'data', '=', 'None', '# Wait for a connection', 'if', 'self', '.', 'debug', ':', 'self', '.', 'py3_wrapper', '.', 'log', '(', '"waiting for a connection"', ')', 'connection', ',', 'client_address', '=', 'self', '.', 'sock', '.', 'accept', '(', ')',...
Main thread listen to socket and send any commands to the CommandRunner.
['Main', 'thread', 'listen', 'to', 'socket', 'and', 'send', 'any', 'commands', 'to', 'the', 'CommandRunner', '.']
train
https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/command.py#L264-L294
3,690
RockFeng0/rtsf
rtsf/p_report.py
HtmlReporter.add_report_data
def add_report_data(list_all=[], module_name="TestModule", **kwargs): ''' add report data to a list @param list_all: a list which save the report data @param module_name: test set name or test module name @param kwargs: such as case_name: testcase name ...
python
def add_report_data(list_all=[], module_name="TestModule", **kwargs): ''' add report data to a list @param list_all: a list which save the report data @param module_name: test set name or test module name @param kwargs: such as case_name: testcase name ...
['def', 'add_report_data', '(', 'list_all', '=', '[', ']', ',', 'module_name', '=', '"TestModule"', ',', '*', '*', 'kwargs', ')', ':', 'start_at', '=', 'kwargs', '.', 'get', '(', '"start_at"', ')', 'case_name', '=', 'kwargs', '.', 'get', '(', '"case_name"', ',', '"TestCase"', ')', 'raw_case_name', '=', 'kwargs', '.', '...
add report data to a list @param list_all: a list which save the report data @param module_name: test set name or test module name @param kwargs: such as case_name: testcase name status: test result, Pass or Fail resp_teste...
['add', 'report', 'data', 'to', 'a', 'list']
train
https://github.com/RockFeng0/rtsf/blob/fbc0d57edaeca86418af3942472fcc6d3e9ce591/rtsf/p_report.py#L196-L241
3,691
tariqdaouda/rabaDB
rabaDB/Raba.py
RabaListPupa._attachToObject
def _attachToObject(self, anchorObj, relationName) : "dummy fct for compatibility reasons, a RabaListPupa is attached by default" #MutableSequence.__getattribute__(self, "develop")() self.develop() self._attachToObject(anchorObj, relationName)
python
def _attachToObject(self, anchorObj, relationName) : "dummy fct for compatibility reasons, a RabaListPupa is attached by default" #MutableSequence.__getattribute__(self, "develop")() self.develop() self._attachToObject(anchorObj, relationName)
['def', '_attachToObject', '(', 'self', ',', 'anchorObj', ',', 'relationName', ')', ':', '#MutableSequence.__getattribute__(self, "develop")()', 'self', '.', 'develop', '(', ')', 'self', '.', '_attachToObject', '(', 'anchorObj', ',', 'relationName', ')']
dummy fct for compatibility reasons, a RabaListPupa is attached by default
['dummy', 'fct', 'for', 'compatibility', 'reasons', 'a', 'RabaListPupa', 'is', 'attached', 'by', 'default']
train
https://github.com/tariqdaouda/rabaDB/blob/42e0d6ee65149ae4f1e4c380cc695a9e7d2d1bbc/rabaDB/Raba.py#L739-L743
3,692
ga4gh/ga4gh-server
ga4gh/server/backend.py
Backend.runSearchVariantAnnotationSets
def runSearchVariantAnnotationSets(self, request): """ Runs the specified SearchVariantAnnotationSetsRequest. """ return self.runSearchRequest( request, protocol.SearchVariantAnnotationSetsRequest, protocol.SearchVariantAnnotationSetsResponse, self.var...
python
def runSearchVariantAnnotationSets(self, request): """ Runs the specified SearchVariantAnnotationSetsRequest. """ return self.runSearchRequest( request, protocol.SearchVariantAnnotationSetsRequest, protocol.SearchVariantAnnotationSetsResponse, self.var...
['def', 'runSearchVariantAnnotationSets', '(', 'self', ',', 'request', ')', ':', 'return', 'self', '.', 'runSearchRequest', '(', 'request', ',', 'protocol', '.', 'SearchVariantAnnotationSetsRequest', ',', 'protocol', '.', 'SearchVariantAnnotationSetsResponse', ',', 'self', '.', 'variantAnnotationSetsGenerator', ')']
Runs the specified SearchVariantAnnotationSetsRequest.
['Runs', 'the', 'specified', 'SearchVariantAnnotationSetsRequest', '.']
train
https://github.com/ga4gh/ga4gh-server/blob/1aa18922ef136db8604f6f098cb1732cba6f2a76/ga4gh/server/backend.py#L946-L953
3,693
automl/HpBandSter
hpbandster/examples/example_5_pytorch_worker.py
PyTorchWorker.compute
def compute(self, config, budget, working_directory, *args, **kwargs): """ Simple example for a compute function using a feed forward network. It is trained on the MNIST dataset. The input parameter "config" (dictionary) contains the sampled configurations passed by the bohb optimizer """ # device = torch....
python
def compute(self, config, budget, working_directory, *args, **kwargs): """ Simple example for a compute function using a feed forward network. It is trained on the MNIST dataset. The input parameter "config" (dictionary) contains the sampled configurations passed by the bohb optimizer """ # device = torch....
['def', 'compute', '(', 'self', ',', 'config', ',', 'budget', ',', 'working_directory', ',', '*', 'args', ',', '*', '*', 'kwargs', ')', ':', "# device = torch.device('cpu')", 'model', '=', 'MNISTConvNet', '(', 'num_conv_layers', '=', 'config', '[', "'num_conv_layers'", ']', ',', 'num_filters_1', '=', 'config', '[', "'n...
Simple example for a compute function using a feed forward network. It is trained on the MNIST dataset. The input parameter "config" (dictionary) contains the sampled configurations passed by the bohb optimizer
['Simple', 'example', 'for', 'a', 'compute', 'function', 'using', 'a', 'feed', 'forward', 'network', '.', 'It', 'is', 'trained', 'on', 'the', 'MNIST', 'dataset', '.', 'The', 'input', 'parameter', 'config', '(', 'dictionary', ')', 'contains', 'the', 'sampled', 'configurations', 'passed', 'by', 'the', 'bohb', 'optimizer'...
train
https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/examples/example_5_pytorch_worker.py#L99-L144
3,694
ArabellaTech/django-basic-cms
basic_cms/templatetags/pages_tags.py
show_slug_with_level
def show_slug_with_level(context, page, lang=None, fallback=True): """Display slug with level by language.""" if not lang: lang = context.get('lang', pages_settings.PAGE_DEFAULT_LANGUAGE) page = get_page_from_string_or_id(page, lang) if not page: return '' return {'content': page.s...
python
def show_slug_with_level(context, page, lang=None, fallback=True): """Display slug with level by language.""" if not lang: lang = context.get('lang', pages_settings.PAGE_DEFAULT_LANGUAGE) page = get_page_from_string_or_id(page, lang) if not page: return '' return {'content': page.s...
['def', 'show_slug_with_level', '(', 'context', ',', 'page', ',', 'lang', '=', 'None', ',', 'fallback', '=', 'True', ')', ':', 'if', 'not', 'lang', ':', 'lang', '=', 'context', '.', 'get', '(', "'lang'", ',', 'pages_settings', '.', 'PAGE_DEFAULT_LANGUAGE', ')', 'page', '=', 'get_page_from_string_or_id', '(', 'page', ',...
Display slug with level by language.
['Display', 'slug', 'with', 'level', 'by', 'language', '.']
train
https://github.com/ArabellaTech/django-basic-cms/blob/863f3c6098606f663994930cd8e7723ad0c07caf/basic_cms/templatetags/pages_tags.py#L174-L183
3,695
tkem/cachetools
cachetools/func.py
lfu_cache
def lfu_cache(maxsize=128, typed=False): """Decorator to wrap a function with a memoizing callable that saves up to `maxsize` results based on a Least Frequently Used (LFU) algorithm. """ if maxsize is None: return _cache(_UnboundCache(), typed) else: return _cache(LFUCache(maxs...
python
def lfu_cache(maxsize=128, typed=False): """Decorator to wrap a function with a memoizing callable that saves up to `maxsize` results based on a Least Frequently Used (LFU) algorithm. """ if maxsize is None: return _cache(_UnboundCache(), typed) else: return _cache(LFUCache(maxs...
['def', 'lfu_cache', '(', 'maxsize', '=', '128', ',', 'typed', '=', 'False', ')', ':', 'if', 'maxsize', 'is', 'None', ':', 'return', '_cache', '(', '_UnboundCache', '(', ')', ',', 'typed', ')', 'else', ':', 'return', '_cache', '(', 'LFUCache', '(', 'maxsize', ')', ',', 'typed', ')']
Decorator to wrap a function with a memoizing callable that saves up to `maxsize` results based on a Least Frequently Used (LFU) algorithm.
['Decorator', 'to', 'wrap', 'a', 'function', 'with', 'a', 'memoizing', 'callable', 'that', 'saves', 'up', 'to', 'maxsize', 'results', 'based', 'on', 'a', 'Least', 'Frequently', 'Used', '(', 'LFU', ')', 'algorithm', '.']
train
https://github.com/tkem/cachetools/blob/1b67cddadccb89993e9d2567bac22e57e2b2b373/cachetools/func.py#L96-L105
3,696
patrickayoup/md2remark
md2remark/main.py
parse_cl_args
def parse_cl_args(arg_vector): '''Parses the command line arguments''' parser = argparse.ArgumentParser(description='Compiles markdown files into html files for remark.js') parser.add_argument('source', metavar='source', help='the source to compile. If a directory is provided, all markdown files in that directory...
python
def parse_cl_args(arg_vector): '''Parses the command line arguments''' parser = argparse.ArgumentParser(description='Compiles markdown files into html files for remark.js') parser.add_argument('source', metavar='source', help='the source to compile. If a directory is provided, all markdown files in that directory...
['def', 'parse_cl_args', '(', 'arg_vector', ')', ':', 'parser', '=', 'argparse', '.', 'ArgumentParser', '(', 'description', '=', "'Compiles markdown files into html files for remark.js'", ')', 'parser', '.', 'add_argument', '(', "'source'", ',', 'metavar', '=', "'source'", ',', 'help', '=', "'the source to compile. If ...
Parses the command line arguments
['Parses', 'the', 'command', 'line', 'arguments']
train
https://github.com/patrickayoup/md2remark/blob/04e66462046cd123c5b1810454d949c3a05bc057/md2remark/main.py#L38-L43
3,697
cebel/pyuniprot
src/pyuniprot/manager/database.py
DbManager.db_import_xml
def db_import_xml(self, url=None, force_download=False, taxids=None, silent=False): """Updates the CTD database 1. downloads gzipped XML 2. drops all tables in database 3. creates all tables in database 4. import XML 5. close session :param Optional[list...
python
def db_import_xml(self, url=None, force_download=False, taxids=None, silent=False): """Updates the CTD database 1. downloads gzipped XML 2. drops all tables in database 3. creates all tables in database 4. import XML 5. close session :param Optional[list...
['def', 'db_import_xml', '(', 'self', ',', 'url', '=', 'None', ',', 'force_download', '=', 'False', ',', 'taxids', '=', 'None', ',', 'silent', '=', 'False', ')', ':', 'log', '.', 'info', '(', "'Update UniProt database from {}'", '.', 'format', '(', 'url', ')', ')', 'self', '.', '_drop_tables', '(', ')', 'xml_gzipped_fi...
Updates the CTD database 1. downloads gzipped XML 2. drops all tables in database 3. creates all tables in database 4. import XML 5. close session :param Optional[list[int]] taxids: list of NCBI taxonomy identifier :param str url: iterable of URL strings...
['Updates', 'the', 'CTD', 'database', '1', '.', 'downloads', 'gzipped', 'XML', '2', '.', 'drops', 'all', 'tables', 'in', 'database', '3', '.', 'creates', 'all', 'tables', 'in', 'database', '4', '.', 'import', 'XML', '5', '.', 'close', 'session']
train
https://github.com/cebel/pyuniprot/blob/9462a6042c7c9295415a5eb589b77b27cb7c142b/src/pyuniprot/manager/database.py#L135-L156
3,698
defunkt/pystache
pystache/locator.py
Locator.find_object
def find_object(self, obj, search_dirs, file_name=None): """ Return the path to a template associated with the given object. """ if file_name is None: # TODO: should we define a make_file_name() method? template_name = self.make_template_name(obj) fil...
python
def find_object(self, obj, search_dirs, file_name=None): """ Return the path to a template associated with the given object. """ if file_name is None: # TODO: should we define a make_file_name() method? template_name = self.make_template_name(obj) fil...
['def', 'find_object', '(', 'self', ',', 'obj', ',', 'search_dirs', ',', 'file_name', '=', 'None', ')', ':', 'if', 'file_name', 'is', 'None', ':', '# TODO: should we define a make_file_name() method?', 'template_name', '=', 'self', '.', 'make_template_name', '(', 'obj', ')', 'file_name', '=', 'self', '.', 'make_file_na...
Return the path to a template associated with the given object.
['Return', 'the', 'path', 'to', 'a', 'template', 'associated', 'with', 'the', 'given', 'object', '.']
train
https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/locator.py#L154-L171
3,699
bharadwajyarlagadda/bingmaps
bingmaps/apiservices/trafficincidents.py
TrafficIncidentsApi.get_data
def get_data(self): """Gets data from the given url""" url = self.build_url() self.incidents_data = requests.get(url) if not self.incidents_data.status_code == 200: raise self.incidents_data.raise_for_status()
python
def get_data(self): """Gets data from the given url""" url = self.build_url() self.incidents_data = requests.get(url) if not self.incidents_data.status_code == 200: raise self.incidents_data.raise_for_status()
['def', 'get_data', '(', 'self', ')', ':', 'url', '=', 'self', '.', 'build_url', '(', ')', 'self', '.', 'incidents_data', '=', 'requests', '.', 'get', '(', 'url', ')', 'if', 'not', 'self', '.', 'incidents_data', '.', 'status_code', '==', '200', ':', 'raise', 'self', '.', 'incidents_data', '.', 'raise_for_status', '(', ...
Gets data from the given url
['Gets', 'data', 'from', 'the', 'given', 'url']
train
https://github.com/bharadwajyarlagadda/bingmaps/blob/6bb3cdadfb121aaff96704509cedff2710a62b6d/bingmaps/apiservices/trafficincidents.py#L89-L94