code
stringlengths
51
2.34k
sequence
stringlengths
186
3.94k
docstring
stringlengths
11
171
def post(self, url, data=None, **kwargs): return requests.post(url, data=data, headers=self.add_headers(**kwargs))
module function_definition identifier parameters identifier identifier default_parameter identifier none dictionary_splat_pattern identifier block return_statement call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier call attribute identifier i...
Encapsulte requests.post to use this class instance header
def execute(self, conn, block_name, origin_site_name, transaction=False): if not conn: dbsExceptionHandler("dbsException-failed-connect2host", "Oracle/Block/UpdateStatus. \ Expects db connection from upper layer.", self.logger.exception) binds = {"block_name": block_name, "origin_site_name":...
module function_definition identifier parameters identifier identifier identifier identifier default_parameter identifier false block if_statement not_operator identifier block expression_statement call identifier argument_list string string_start string_content string_end string string_start string_content escape_sequ...
Update origin_site_name for a given block_name
def maybe_encode_keys(self, keys): ret = {} for k, v in six.iteritems(keys): if is_dynamo_value(v): return keys elif not is_null(v): ret[k] = self.encode(v) return ret
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary for_statement pattern_list identifier identifier call attribute identifier identifier argument_list identifier block if_statement call identifier argument_list identifier block return_state...
Same as encode_keys but a no-op if already in Dynamo format
def addFormat(name, fn, opts): fmtyielders[name] = fn fmtopts[name] = opts
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment subscript identifier identifier identifier expression_statement assignment subscript identifier identifier identifier
Add an additional ingest file format
def _style(self, retval): "Applies custom option tree to values return by the callback." if self.id not in Store.custom_options(): return retval spec = StoreOptions.tree_to_dict(Store.custom_options()[self.id]) return retval.opts(spec)
module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end if_statement comparison_operator attribute identifier identifier call attribute identifier identifier argument_list block return_statement identifier expression_statement assig...
Applies custom option tree to values return by the callback.
def parse_private_key(data, password): if is_pem(data): if b'ENCRYPTED' in data: if password is None: raise TypeError('No password provided for encrypted key.') try: return serialization.load_pem_private_key( data, password, backend=default_bac...
module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier block if_statement comparison_operator string string_start string_content string_end identifier block if_statement comparison_operator identifier none block raise_statement call identifier ...
Identifies, decrypts and returns a cryptography private key object.
def prepare_env(app, env, docname): if not hasattr(env, 'needs_all_needs'): env.needs_all_needs = {} if not hasattr(env, 'needs_functions'): env.needs_functions = {} needs_functions = app.needs_functions if needs_functions is None: needs_functions = [] if not ...
module function_definition identifier parameters identifier identifier identifier block if_statement not_operator call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment attribute identifier identifier dictionary if_statement not_operator call identif...
Prepares the sphinx environment to store sphinx-needs internal data.
def install_cache(expire_after=12 * 3600, cache_post=False): allowable_methods = ['GET'] if cache_post: allowable_methods.append('POST') requests_cache.install_cache( expire_after=expire_after, allowable_methods=allowable_methods)
module function_definition identifier parameters default_parameter identifier binary_operator integer integer default_parameter identifier false block expression_statement assignment identifier list string string_start string_content string_end if_statement identifier block expression_statement call attribute identifie...
Patches the requests library with requests_cache.
def list_commands(self, ctx): self.connect(ctx) if not hasattr(ctx, "widget"): return super(Engineer, self).list_commands(ctx) return ctx.widget.engineer_list_commands() + super(Engineer, self).list_commands(ctx)
module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list identifier if_statement not_operator call identifier argument_list identifier string string_start string_content string_end block return_statement call attribute call iden...
list all commands exposed to engineer
def _expand_subsystems(self, scope_infos): def subsys_deps(subsystem_client_cls): for dep in subsystem_client_cls.subsystem_dependencies_iter(): if dep.scope != GLOBAL_SCOPE: yield self._scope_to_info[dep.options_scope] for x in subsys_deps(dep.subsystem_cls): yield x ...
module function_definition identifier parameters identifier identifier block function_definition identifier parameters identifier block for_statement identifier call attribute identifier identifier argument_list block if_statement comparison_operator attribute identifier identifier identifier block expression_statement...
Add all subsystems tied to a scope, right after that scope.
def dmlc_opts(opts): args = ['--num-workers', str(opts.num_workers), '--num-servers', str(opts.num_servers), '--cluster', opts.launcher, '--host-file', opts.hostfile, '--sync-dst-dir', opts.sync_dst_dir] dopts = vars(opts) for key in ['env_server', 'env_worker...
module function_definition identifier parameters identifier block expression_statement assignment identifier list string string_start string_content string_end call identifier argument_list attribute identifier identifier string string_start string_content string_end call identifier argument_list attribute identifier i...
convert from mxnet's opts to dmlc's opts
def _createSlink(self, slinks): for slink in slinks: superLink = SuperLink(slinkNumber=slink['slinkNumber'], numPipes=slink['numPipes']) superLink.stormPipeNetworkFile = self for node in slink['nodes']: superNode = SuperNode(n...
module function_definition identifier parameters identifier identifier block for_statement identifier identifier block expression_statement assignment identifier call identifier argument_list keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier subsc...
Create GSSHAPY SuperLink, Pipe, and SuperNode Objects Method
def record_diff(old, new): return '\n'.join(difflib.ndiff( ['%s: %s' % (k, v) for op in old for k, v in op.items()], ['%s: %s' % (k, v) for op in new for k, v in op.items()], ))
module function_definition identifier parameters identifier identifier block return_statement call attribute string string_start string_content escape_sequence string_end identifier argument_list call attribute identifier identifier argument_list list_comprehension binary_operator string string_start string_content str...
Generate a human-readable diff of two performance records.
def prepend(self, _, child, name=None): self._insert(child, prepend=True, name=name) return self
module function_definition identifier parameters identifier identifier identifier default_parameter identifier none block expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier true keyword_argument identifier identifier return_statement identifier
Adds childs to this tag, starting from the first position.
def report(zap_helper, output, output_format): if output_format == 'html': zap_helper.html_report(output) elif output_format == 'md': zap_helper.md_report(output) else: zap_helper.xml_report(output) console.info('Report saved to "{0}"'.format(output))
module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list identifier elif_clause comparison_operator identifier string str...
Generate XML, MD or HTML report.
def make_tmp_dir(suffix="", prefix="tmp", dir=None): if dir is None: return tempfile.mkdtemp(suffix, prefix, dir) else: while True: rand_term = random.randint(1, 9999) tmp_dir = os.path.join(dir, "%s%d%s" % (prefix, rand_term, suffix)) if tf.gfile.Exists(tmp_dir): continue tf...
module function_definition identifier parameters default_parameter identifier string string_start string_end default_parameter identifier string string_start string_content string_end default_parameter identifier none block if_statement comparison_operator identifier none block return_statement call attribute identifie...
Make a temporary directory.
def instance_of(klass, arg): if not isinstance(arg, klass): raise com.IbisTypeError( 'Given argument with type {} is not an instance of {}'.format( type(arg), klass ) ) return arg
module function_definition identifier parameters identifier identifier block if_statement not_operator call identifier argument_list identifier identifier block raise_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list call i...
Require that a value has a particular Python type.
def _get_vnet(self, adapter_number): vnet = "ethernet{}.vnet".format(adapter_number) if vnet not in self._vmx_pairs: raise VMwareError("vnet {} not in VMX file".format(vnet)) return vnet
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier if_statement comparison_operator identifier attribute identifier identifier block raise_statement call ...
Return the vnet will use in ubridge
def to_dict(self): data = {} if self.created_at: data['created_at'] = self.created_at.strftime( '%Y-%m-%dT%H:%M:%S%z') if self.image_id: data['image_id'] = self.image_id if self.permalink_url: data['permalink_url'] = self.permalink_url ...
module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary if_statement attribute identifier identifier block expression_statement assignment subscript identifier string string_start string_content string_end call attribute attribute identifier identifier ide...
Return a dict representation of this instance
def load_trie(filename): trie = marisa_trie.BytesTrie() with warnings.catch_warnings(): warnings.simplefilter("ignore") trie.load(filename) return trie
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list with_statement with_clause with_item call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument...
Load a BytesTrie from the marisa_trie on-disk format.
def read_projected_dos( self ): pdos_list = [] for i in range( self.number_of_atoms ): df = self.read_atomic_dos_as_df( i+1 ) pdos_list.append( df ) self.pdos = np.vstack( [ np.array( df ) for df in pdos_list ] ).reshape( self.number_of_atoms, self.number_of_...
module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement identifier call identifier argument_list attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator ide...
Read the projected density of states data into
def rescorer(self, rescorer): clone = self._clone() clone._rescorer=rescorer return clone
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier identifier return_statement identifier
Returns a new QuerySet with a set rescorer.
def clear(*signals): signals = signals if signals else receivers.keys() for signal in signals: receivers[signal].clear()
module function_definition identifier parameters list_splat_pattern identifier block expression_statement assignment identifier conditional_expression identifier identifier call attribute identifier identifier argument_list for_statement identifier identifier block expression_statement call attribute subscript identifi...
Clears all callbacks for a particular signal or signals
def c(self): if self._client is None: self._parse_settings() self._client = Rumetr(**self.settings) return self._client
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier call identifier argument_list dictionary_s...
Caching client for not repeapting checks
def next(self): if self.iter_next(): self.data, self.label = self._read() return {self.data_name : self.data[0][1], self.label_name : self.label[0][1]} else: raise StopIteration
module function_definition identifier parameters identifier block if_statement call attribute identifier identifier argument_list block expression_statement assignment pattern_list attribute identifier identifier attribute identifier identifier call attribute identifier identifier argument_list return_statement diction...
return one dict which contains "data" and "label"
def merge_asset(self, other): for asset in other.asset: asset_name = asset.get("name") asset_type = asset.tag pattern = "./{}[@name='{}']".format(asset_type, asset_name) if self.asset.find(pattern) is None: self.asset.append(asset)
module function_definition identifier parameters identifier identifier block for_statement identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifi...
Useful for merging other files in a custom logic.
def max_lv_count(self): self.open() count = lvm_vg_get_max_lv(self.handle) self.close() return count
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list retur...
Returns the maximum allowed logical volume count.
def runner(parallel, config): def run_parallel(fn_name, items): items = [x for x in items if x is not None] if len(items) == 0: return [] items = diagnostics.track_parallel(items, fn_name) fn, fn_name = (fn_name, fn_name.__name__) if callable(fn_name) else (get_fn(fn_name...
module function_definition identifier parameters identifier identifier block function_definition identifier parameters identifier identifier block expression_statement assignment identifier list_comprehension identifier for_in_clause identifier identifier if_clause comparison_operator identifier none if_statement compa...
Run functions, provided by string name, on multiple cores on the current machine.
def run(self): with self.output().open('w') as outfile: print("data 0 200 10 50 60", file=outfile) print("data 1 190 9 52 60", file=outfile) print("data 2 200 10 52 60", file=outfile) print("data 3 195 1 52 60", file=outfile)
module function_definition identifier parameters identifier block with_statement with_clause with_item as_pattern call attribute call attribute identifier identifier argument_list identifier argument_list string string_start string_content string_end as_pattern_target identifier block expression_statement call identifi...
The execution of this task will write 4 lines of data on this task's target output.
def FilterFnTable(fn_table, symbol): new_table = list() for entry in fn_table: if entry[0] != symbol: new_table.append(entry) return new_table
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list for_statement identifier identifier block if_statement comparison_operator subscript identifier integer identifier block expression_statement call attribute identifier id...
Remove a specific symbol from a fn_table.
def last(self): self.__file.seek(0, 2) data = self.get(self.length - 1) return data
module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list integer integer expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator attribute identifier identifier int...
Get the last object in file.
def click(self, x, y): return self.server.jsonrpc.click(x, y)
module function_definition identifier parameters identifier identifier identifier block return_statement call attribute attribute attribute identifier identifier identifier identifier argument_list identifier identifier
click at arbitrary coordinates.
def mnest_basename(self): if not hasattr(self, '_mnest_basename'): s = self.labelstring if s=='0_0': s = 'single' elif s=='0_0-0_1': s = 'binary' elif s=='0_0-0_1-0_2': s = 'triple' s = '{}-{}'.format(sel...
module function_definition identifier parameters identifier block if_statement not_operator call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator identifier string string_st...
Full path to basename
def _delete(self, **kwargs): requests_params = self._handle_requests_params(kwargs) delete_uri = self._meta_data['uri'] session = self._meta_data['bigip']._meta_data['icr_session'] response = session.delete(delete_uri, **requests_params) if response.status_code == 200 or 201: ...
module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier subscript attribute identifier identifier string string_start string_c...
Wrapped with delete, override that in a subclass to customize
def find_all_models(models): for model in models: yield model for parent in model._meta.parents.keys(): for parent_model in find_all_models((parent,)): yield parent_model
module function_definition identifier parameters identifier block for_statement identifier identifier block expression_statement yield identifier for_statement identifier call attribute attribute attribute identifier identifier identifier identifier argument_list block for_statement identifier call identifier argument_...
Yield all models and their parents.
def bind_objects(self, *objects): self.control.bind_keys(objects) self.objects += objects
module function_definition identifier parameters identifier list_splat_pattern identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement augmented_assignment attribute identifier identifier identifier
Bind one or more objects
def insertReadGroupSet(self, readGroupSet): programsJson = json.dumps( [protocol.toJsonDict(program) for program in readGroupSet.getPrograms()]) statsJson = json.dumps(protocol.toJsonDict(readGroupSet.getStats())) try: models.Readgroupset.create( ...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier call attribute identifier identifier argume...
Inserts a the specified readGroupSet into this repository.
def to_dict(self): return {'field': self.output_tag, 'expression': self.search_expression, 'coll_id': self.id_collection, 'collection': self.collection.name if self.collection else None}
module function_definition identifier parameters identifier block return_statement dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute...
Return a dict representation of KnwKBDDEF.
def values(self, column_name, exclude_type=STRUCT): column_name = unnest_path(column_name) columns = self.columns output = [] for path in self.query_path: full_path = untype_path(concat_field(path, column_name)) for c in columns: if c.jx_type in ex...
module function_definition identifier parameters identifier identifier default_parameter identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier l...
RETURN ALL COLUMNS THAT column_name REFERS TO
def _updateable(self, obj): if obj.latest_version is None or obj.is_editable: return None else: return obj.latest_version != obj.current_version
module function_definition identifier parameters identifier identifier block if_statement boolean_operator comparison_operator attribute identifier identifier none attribute identifier identifier block return_statement none else_clause block return_statement comparison_operator attribute identifier identifier attribute...
Return True if there are available updates.
def stop_func_accept_retry_state(stop_func): if not six.callable(stop_func): return stop_func if func_takes_retry_state(stop_func): return stop_func @_utils.wraps(stop_func) def wrapped_stop_func(retry_state): warn_about_non_retry_state_deprecation( 'stop', stop_func,...
module function_definition identifier parameters identifier block if_statement not_operator call attribute identifier identifier argument_list identifier block return_statement identifier if_statement call identifier argument_list identifier block return_statement identifier decorated_definition decorator call attribut...
Wrap "stop" function to accept "retry_state" parameter.
def find_actual_cause(self, mechanism, purviews=False): return self.find_causal_link(Direction.CAUSE, mechanism, purviews)
module function_definition identifier parameters identifier identifier default_parameter identifier false block return_statement call attribute identifier identifier argument_list attribute identifier identifier identifier identifier
Return the actual cause of a mechanism.
def _ps_extract_pid(self, line): this_pid = self.regex['pid'].sub(r'\g<1>', line) this_parent = self.regex['parent'].sub(r'\g<1>', line) return this_pid, this_parent
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute subscript attribute identifier identifier string string_start string_content string_end identifier argument_list string string_start string_content string_end identifier expression_stat...
Extract PID and parent PID from an output line from the PS command
def process_prologue(self): for key in ['TCurr', 'TCHED', 'TCTRL', 'TLHED', 'TLTRL', 'TIPFS', 'TINFS', 'TISPC', 'TIECL', 'TIBBC', 'TISTR', 'TLRAN', 'TIIRT', 'TIVIT', 'TCLMT', 'TIONA']: try: self.prologue[key] = make_sgs_time(self.prologue[key])...
module function_definition identifier parameters identifier block for_statement identifier list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content strin...
Reprocess prologue to correct types.
def publish(self, tag, message): payload = self.build_payload(tag, message) self.socket.send(payload)
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier
Publish a message down the socket
def configure_node(self, node): node.slaveinput['cov_master_host'] = socket.gethostname() node.slaveinput['cov_master_topdir'] = self.topdir node.slaveinput['cov_master_rsync_roots'] = [str(root) for root in node.nodemanager.roots]
module function_definition identifier parameters identifier identifier block expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end call attribute identifier identifier argument_list expression_statement assignment subscript attribute identifier identifie...
Slaves need to know if they are collocated and what files have moved.
def schema_file(self): path = os.getcwd() + '/' + self.lazy_folder return path + self.schema_filename
module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator binary_operator call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier return_statement binary_operator identifier attrib...
Gets the full path to the file in which to load configuration schema.
def read_boolean_option(self, section, option): if self.has_option(section, option): self.config[option] = self.getboolean(section, option)
module function_definition identifier parameters identifier identifier identifier block if_statement call attribute identifier identifier argument_list identifier identifier block expression_statement assignment subscript attribute identifier identifier identifier call attribute identifier identifier argument_list iden...
Read a boolean option.
def search(self, q=None, per_page=None, page=None, bbox=None, sort_by="relavance", sort_order="asc"): url = self._url + "/datasets.json" param_dict = { "sort_by" : sort_by, "f" : "json" ...
module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier string string_start string_content string_end default_parameter identifier string string_start ...
searches the opendata site and returns the dataset results
def _dict_to_name_value(data): if isinstance(data, dict): sorted_data = sorted(data.items(), key=lambda s: s[0]) result = [] for name, value in sorted_data: if isinstance(value, dict): result.append({name: _dict_to_name_value(value)}) else: ...
module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list keyword_argument identifier lambda lambda_parameters identi...
Convert a dictionary to a list of dictionaries to facilitate ordering
def cmd_rally_alt(self, args): if (len(args) < 2): print("Usage: rally alt RALLYNUM newAlt <newBreakAlt>") return if not self.have_list: print("Please list rally points first") return idx = int(args[0]) if idx <= 0 or idx > self.rallyloader...
module function_definition identifier parameters identifier identifier block if_statement parenthesized_expression comparison_operator call identifier argument_list identifier integer block expression_statement call identifier argument_list string string_start string_content string_end return_statement if_statement not...
handle rally alt change
def makeService(self, options): return NodeService( port=options['port'], host=options['host'], broker_host=options['broker_host'], broker_port=options['broker_port'], debug=options['debug'] )
module function_definition identifier parameters identifier identifier block return_statement call identifier argument_list keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier subscript identifier string string_start string_content string_end keywor...
Construct a Node Server
def update_cnt(uid, post_data): entry = TabPostHist.update( user_name=post_data['user_name'], cnt_md=tornado.escape.xhtml_escape(post_data['cnt_md']), time_update=tools.timestamp(), ).where(TabPostHist.uid == uid) entry.execute()
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier call attrib...
Update the content by ID.
def _group_by(data, criteria): if isinstance(criteria, str): criteria_str = criteria def criteria(x): return x[criteria_str] res = defaultdict(list) for element in data: key = criteria(element) res[key].append(element) return res
module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier identifier function_definition identifier parameters identifier block return_statement subscript identifier identifier expression...
Group objects in data using a function or a key
def toggleglobalsitepackages_cmd(argv): quiet = argv == ['-q'] site = sitepackages_dir() ngsp_file = site.parent / 'no-global-site-packages.txt' if ngsp_file.exists(): ngsp_file.unlink() if not quiet: print('Enabled global site-packages') else: with ngsp_file.open...
module function_definition identifier parameters identifier block expression_statement assignment identifier comparison_operator identifier list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier binary_operat...
Toggle the current virtualenv between having and not having access to the global site-packages.
def _update_Pxy(self): scipy.copyto(self.Pxy_no_omega, self.Phi_x.transpose(), where=CODON_SINGLEMUT) self.Pxy_no_omega[0][CODON_TRANSITION] *= self.kappa self.Pxy = self.Pxy_no_omega.copy() self.Pxy[0][CODON_NONSYN] *= self.omega _fill_diagonals(self.Pxy, self._d...
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier expression_statement augmented_assignme...
Update `Pxy` using current `omega`, `kappa`, and `Phi_x`.
def mpirun(self): cmd = self.attributes['mpirun'] if cmd and cmd[0] != 'mpirun': cmd = ['mpirun'] return [str(e) for e in cmd]
module function_definition identifier parameters identifier block expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end if_statement boolean_operator identifier comparison_operator subscript identifier integer string string_start string_conten...
Additional options passed as a list to the ``mpirun`` command
def _linearly_scale(inputmatrix, inputmin, inputmax, outputmin, outputmax): inputrange = inputmax - inputmin outputrange = outputmax - outputmin delta = outputrange/inputrange inputmin = inputmin + 1.0 / delta / 2.0 outputmax = outputmax - 1 outputmatrix = (inputmatrix - inputmin) * delta + outp...
module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier binar...
linearly scale input to output, used by Linke turbidity lookup
def prepare(c): actions, state = status(c) if not confirm("Take the above actions?"): sys.exit("Aborting.") if actions.changelog is Changelog.NEEDS_RELEASE: cmd = "$EDITOR {0.packaging.changelog_file}".format(c) c.run(cmd, pty=True, hide=False) if actions.version == VersionFile.N...
module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier if_statement not_operator call identifier argument_list string string_start string_content string_end block expression_statement call attribute id...
Edit changelog & version, git commit, and git tag, to set up for release.
def namespace_to_regex(namespace): db_name, coll_name = namespace.split(".", 1) db_regex = re.escape(db_name).replace(r"\*", "([^.]*)") coll_regex = re.escape(coll_name).replace(r"\*", "(.*)") return re.compile(r"\A" + db_regex + r"\." + coll_regex + r"\Z")
module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end integer expression_statement assignment identifier call attribute call attribute identifie...
Create a RegexObject from a wildcard namespace.
def value(self): pos = self.file.tell() self.file.seek(0) val = self.file.read() self.file.seek(pos) return val.decode(self.charset)
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list integer expression_statement assignment identi...
Data decoded with the specified charset
def sanitize_path(path): storage_option = infer_storage_options(path) protocol = storage_option['protocol'] if protocol in ('http', 'https'): path = os.path.normpath(path.replace("{}://".format(protocol), '')) elif protocol == 'file': path = os.path.normpath(path) path = path.rep...
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier subscript identifier string string_start string_content string_end if_statement comparison_operator identifier tuple string str...
Utility for cleaning up paths.
def utils(opts, whitelist=None, context=None, proxy=proxy): return LazyLoader( _module_dirs(opts, 'utils', ext_type_dirs='utils_dirs'), opts, tag='utils', whitelist=whitelist, pack={'__context__': context, '__proxy__': proxy or {}}, )
module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none default_parameter identifier identifier block return_statement call identifier argument_list call identifier argument_list identifier string string_start string_content string_end keyword_argu...
Returns the utility modules
def request(self, method, endpoint, payload=None, timeout=5): url = self.api_url + endpoint data = None headers = {} if payload is not None: data = json.dumps(payload) headers['Content-Type'] = 'application/json' try: if self.auth_token is not ...
module function_definition identifier parameters identifier identifier identifier default_parameter identifier none default_parameter identifier integer block expression_statement assignment identifier binary_operator attribute identifier identifier identifier expression_statement assignment identifier none expression_...
Send request to API.
def _format_subtree(self, subtree): subtree['children'] = list(subtree['children'].values()) for child in subtree['children']: self._format_subtree(child) return subtree
module function_definition identifier parameters identifier identifier block expression_statement assignment subscript identifier string string_start string_content string_end call identifier argument_list call attribute subscript identifier string string_start string_content string_end identifier argument_list for_sta...
Recursively format all subtrees.
def list_message_files (package, suffix=".mo"): for fname in glob.glob("po/*" + suffix): localename = os.path.splitext(os.path.basename(fname))[0] domainname = "%s.mo" % package.lower() yield (fname, os.path.join( "share", "locale", localename, "LC_MESSAGES", domainname))
module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block for_statement identifier call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier block expression_statement ass...
Return list of all found message files and their installation paths.
def _get_indent(self, node): lineno = node.lineno if lineno > len(self._lines): return -1 wsindent = self._wsregexp.match(self._lines[lineno - 1]) return len(wsindent.group(1))
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator identifier call identifier argument_list attribute identifier identifier block return_statement unary_operator integer expression_state...
Get node indentation level.
def shape(self): "Tuple indicating the number of rows and columns in the Layout." num = len(self) if num <= self._max_cols: return (1, num) nrows = num // self._max_cols last_row_cols = num % self._max_cols return nrows+(1 if last_row_cols else 0), min(num, se...
module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier attribute identifier identifier block return_statement tupl...
Tuple indicating the number of rows and columns in the Layout.
def echo(msg, *args, **kwargs): file = kwargs.pop('file', None) nl = kwargs.pop('nl', True) err = kwargs.pop('err', False) color = kwargs.pop('color', None) msg = safe_unicode(msg).format(*args, **kwargs) click.echo(msg, file=file, nl=nl, err=err, color=color)
module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end none expression_statement assignment identifier ...
Wraps click.echo, handles formatting and check encoding
def modify(self, **patch): if 'monitor' in patch: value = self._format_monitor_parameter(patch['monitor']) patch['monitor'] = value return super(Pool, self)._modify(**patch)
module function_definition identifier parameters identifier dictionary_splat_pattern identifier block if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier call attribute identifier identifier argument_list subscript identifier string ...
Custom modify method to implement monitor parameter formatting.
def create_subword_function(subword_function_name, **kwargs): create_ = registry.get_create_func(SubwordFunction, 'token embedding') return create_(subword_function_name, **kwargs)
module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier string string_start string_content string_end return_statement call identifier argument_list identifier dictionar...
Creates an instance of a subword function.
def sign_envelope(envelope, key_file): doc = etree.fromstring(envelope) body = get_body(doc) queue = SignQueue() queue.push_and_mark(body) security_node = ensure_security_header(doc, queue) security_token_node = create_binary_security_token(key_file) signature_node = Signature( xmlse...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identi...
Sign the given soap request with the given key
def warning (self, msg, pos=None): self.log(msg, 'warning: ' + self.location(pos))
module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement call attribute identifier identifier argument_list identifier binary_operator string string_start string_content string_end call attribute identifier identifier argument_list identifier
Logs a warning message pertaining to the given SeqAtom.
def apply_obfuscation(source): global keyword_args global imported_modules tokens = token_utils.listified_tokenizer(source) keyword_args = analyze.enumerate_keyword_args(tokens) imported_modules = analyze.enumerate_imports(tokens) variables = find_obfuscatables(tokens, obfuscatable_variable) ...
module function_definition identifier parameters identifier block global_statement identifier global_statement identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list...
Returns 'source' all obfuscated.
def SortBy(*qs): sort = [] for q in qs: if q._path.endswith('.desc'): sort.append((q._path[:-5], DESCENDING)) else: sort.append((q._path, ASCENDING)) return sort
module function_definition identifier parameters list_splat_pattern identifier block expression_statement assignment identifier list for_statement identifier identifier block if_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end block expressi...
Convert a list of Q objects into list of sort instructions
def create(self): params = {} return self.send( url=self._base_url + 'create', method='POST', json=params )
module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary return_statement call attribute identifier identifier argument_list keyword_argument identifier binary_operator attribute identifier identifier string string_start string_content string_end keyword_ar...
Create a new reminder.
def iterable(item): if isinstance(item, collections.Iterable) and not isinstance(item, basestring): return item else: return [item]
module function_definition identifier parameters identifier block if_statement boolean_operator call identifier argument_list identifier attribute identifier identifier not_operator call identifier argument_list identifier identifier block return_statement identifier else_clause block return_statement list identifier
generate iterable from item, but leaves out strings
def _make_load_template(self): loader = self._make_loader() def load_template(template_name): return loader.load_name(template_name) return load_template
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list function_definition identifier parameters identifier block return_statement call attribute identifier identifier argument_list identifier return_statement ident...
Return a function that loads a template by name.
def run(self): for cls in self.get_test_classes(): self.logger.info('Running {cls.__name__} test...'.format(cls=cls)) test = cls(runner=self) if test._run(): self.logger.passed('Test {cls.__name__} succeeded!'.format(cls=cls)) else: ...
module function_definition identifier parameters identifier block for_statement identifier call attribute identifier identifier argument_list block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute string string_start string_content string_end identifier argumen...
Runs all enabled tests.
def bin_hex_type(arg): if re.match(r'^[a-f0-9]{2}(:[a-f0-9]{2})+$', arg, re.I): arg = arg.replace(':', '') elif re.match(r'^(\\x[a-f0-9]{2})+$', arg, re.I): arg = arg.replace('\\x', '') try: arg = binascii.a2b_hex(arg) except (binascii.Error, TypeError): raise argparse.ArgumentTypeError("{0} is invalid hex ...
module function_definition identifier parameters identifier block if_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list s...
An argparse type representing binary data encoded in hex.
def _cache_get_last_in_slice(url_dict, start_int, total_int, authn_subj_list): key_str = _gen_cache_key_for_slice(url_dict, start_int, total_int, authn_subj_list) try: last_ts_tup = django.core.cache.cache.get(key_str) except KeyError: last_ts_tup = None logging.debug('Cache get. key="{}...
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier identifier identifier try_statement block expression_statement assignment identifier call attribute attribute attribute attrib...
Return None if cache entry does not exist.
def _classname(self): if self.__class__.__module__ in (None,): return self.__class__.__name__ else: return "%s.%s" % (self.__class__.__module__, self.__class__.__name__)
module function_definition identifier parameters identifier block if_statement comparison_operator attribute attribute identifier identifier identifier tuple none block return_statement attribute attribute identifier identifier identifier else_clause block return_statement binary_operator string string_start string_con...
Return the fully qualified class name.
def _parse_challenge(cls, response): links = _parse_header_links(response) try: authzr_uri = links['up']['url'] except KeyError: raise errors.ClientError('"up" link missing') return ( response.json() .addCallback( lambda bod...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier try_statement block expression_statement assignment identifier subscript subscript identifier string string_start string_content string_end string string_start...
Parse a challenge resource.
def blogroll(request, btype): 'View that handles the generation of blogrolls.' response, site, cachekey = initview(request) if response: return response[0] template = loader.get_template('feedjack/{0}.xml'.format(btype)) ctx = dict() fjlib.get_extra_context(site, ctx) ctx = Context(ctx) response = HttpResponse(...
module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end expression_statement assignment pattern_list identifier identifier identifier call identifier argument_list identifier if_statement identifier block return_statement subscript ...
View that handles the generation of blogrolls.
def init0(self, dae): self.p0 = matrix(self.p, (self.n, 1), 'd') self.q0 = matrix(self.q, (self.n, 1), 'd')
module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier tuple attribute identifier identifier integer string string_start string_content string_end expression_statement assi...
Set initial p and q for power flow
def print_dependencies(_run): print('Dependencies:') for dep in _run.experiment_info['dependencies']: pack, _, version = dep.partition('==') print(' {:<20} == {}'.format(pack, version)) print('\nSources:') for source, digest in _run.experiment_info['sources']: print(' {:<43} {...
module function_definition identifier parameters identifier block expression_statement call identifier argument_list string string_start string_content string_end for_statement identifier subscript attribute identifier identifier string string_start string_content string_end block expression_statement assignment patter...
Print the detected source-files and dependencies.
def create_slug(self): name = self.slug_source counter = 0 while True: if counter == 0: slug = slugify(name) else: slug = slugify('{0} {1}'.format(name, str(counter))) try: self.__class__.objects.exclude(pk=self....
module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier integer while_statement true block if_statement comparison_operator identifier integer block expression_statement assignment identifier ...
Creates slug, checks if slug is unique, and loop if not
def create_entry_file(self, filename, script_map, enapps): if len(script_map) == 0: return template = MakoTemplate( ) content = template.render( enapps=enapps, script_map=script_map, filename=filename, ).strip() if not os.path.exist...
module function_definition identifier parameters identifier identifier identifier identifier block if_statement comparison_operator call identifier argument_list identifier integer block return_statement expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier ...
Creates an entry file for the given script map
def reply_ok(self): return (self.mtype == self.REPLY and self.arguments and self.arguments[0] == self.OK)
module function_definition identifier parameters identifier block return_statement parenthesized_expression boolean_operator boolean_operator comparison_operator attribute identifier identifier attribute identifier identifier attribute identifier identifier comparison_operator subscript attribute identifier identifier ...
Return True if this is a reply and its first argument is 'ok'.
def _update_offset_value(self, f, offset, size, value): f.seek(offset, 0) if (size == 8): f.write(struct.pack('>q', value)) else: f.write(struct.pack('>i', value))
module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement call attribute identifier identifier argument_list identifier integer if_statement parenthesized_expression comparison_operator identifier integer block expression_statement call attribute ...
Writes "value" into location "offset" in file "f".
def unblock_signals(self): self.aggregation_layer_combo.blockSignals(False) self.exposure_layer_combo.blockSignals(False) self.hazard_layer_combo.blockSignals(False)
module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list false expression_statement call attribute attribute identifier identifier identifier argument_list false expression_statement call attribute attribute identifier...
Let the combos listen for event changes again.
def _populate_struct_type_attributes(self, env, data_type): parent_type = None extends = data_type._ast_node.extends if extends: parent_type = self._resolve_type(env, extends, True) if isinstance(parent_type, Alias): raise InvalidSpec( ...
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier none expression_statement assignment identifier attribute attribute identifier identifier identifier if_statement identifier block expression_statement assignment identifier call attribute ...
Converts a forward reference of a struct into a complete definition.
def _normalize_django_header_name(header): new_header = header.rpartition('HTTP_')[2] new_header = '-'.join( x.capitalize() for x in new_header.split('_')) return new_header
module function_definition identifier parameters identifier block expression_statement assignment identifier subscript call attribute identifier identifier argument_list string string_start string_content string_end integer expression_statement assignment identifier call attribute string string_start string_content str...
Unmunge header names modified by Django.
def kill(self, job_id): check_jobid(job_id) queue = self._get_queue() if queue is None: raise QueueDoesntExist ret, output = self._call('%s %s' % ( shell_escape(queue / 'commands/kill'), job_id), ...
module function_definition identifier parameters identifier identifier block expression_statement call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator identifier none block raise_statement identifier expre...
Kills a job on the server.
def properties(self) -> dict: if isinstance(self._last_node, dict): return self._last_node.keys() else: return {}
module function_definition identifier parameters identifier type identifier block if_statement call identifier argument_list attribute identifier identifier identifier block return_statement call attribute attribute identifier identifier identifier argument_list else_clause block return_statement dictionary
Returns the properties of the current node in the iteration.
def updateQTableFromTerminatingState( self, reward ): old_q = self.q_table[self.prev_s][self.prev_a] new_q = old_q self.q_table[self.prev_s][self.prev_a] = new_q
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript subscript attribute identifier identifier attribute identifier identifier attribute identifier identifier expression_statement assignment identifier identifier expression_statement assignmen...
Change q_table to reflect what we have learnt, after reaching a terminal state.
def command_msg(housecode, command): house_byte = 0 if isinstance(housecode, str): house_byte = insteonplm.utils.housecode_to_byte(housecode) << 4 elif isinstance(housecode, int) and housecode < 16: house_byte = housecode << 4 else: house_byte = housec...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier integer if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier binary_operator call attribute attribute identifier identifier identifier argu...
Create an X10 message to send the house code and a command code.
async def run_executor(): parser = argparse.ArgumentParser(description="Run the specified executor.") parser.add_argument('module', help="The module from which to instantiate the concrete executor.") args = parser.parse_args() module_name = '{}.run'.format(args.module) class_name = 'FlowExecutor' ...
module function_definition identifier parameters block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start strin...
Start the actual execution; instantiate the executor and run.
def execute(self, requests, resp_generator, *args, **kwargs): return [resp_generator(request) for request in requests]
module function_definition identifier parameters identifier identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block return_statement list_comprehension call identifier argument_list identifier for_in_clause identifier identifier
Calls the resp_generator for all the requests in sequential order.
def dealloc(subseqs): print(' . dealloc') lines = Lines() lines.add(1, 'cpdef inline dealloc(self):') for seq in subseqs: lines.add(2, 'PyMem_Free(self.%s)' % seq.name) return lines
module function_definition identifier parameters identifier block expression_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list integer stri...
Deallocate memory for 1-dimensional link sequences.