code
stringlengths
51
2.34k
sequence
stringlengths
186
3.94k
docstring
stringlengths
11
171
def to_json(df, values): records = [] if df.empty: return {"data": []} sum_ = float(np.sum([df[c].iloc[0] for c in values])) for c in values: records.append({ "label": values[c], "value": "%.2f"%np.around(df[c].iloc[0] / sum_, decim...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list if_statement attribute identifier identifier block return_statement dictionary pair string string_start string_content string_end list expression_statement assignment identifier call identifier a...
Format output for the json response.
def cal_model_performance(obsl, siml): nse = MathClass.nashcoef(obsl, siml) r2 = MathClass.rsquare(obsl, siml) rmse = MathClass.rmse(obsl, siml) pbias = MathClass.pbias(obsl, siml) rsr = MathClass.rsr(obsl, siml) print('NSE: %.2f, R-square: %.2f, PBIAS: %.2f%%, RMSE: %.2f, RSR: %.2f' % ...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_...
Calculate model performance indexes.
def dlp_job_path(cls, project, dlp_job): return google.api_core.path_template.expand( "projects/{project}/dlpJobs/{dlp_job}", project=project, dlp_job=dlp_job )
module function_definition identifier parameters identifier identifier identifier block return_statement call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifie...
Return a fully-qualified dlp_job string.
def download_threads(self, url): output_file = os.path.join(self.output_path, '{}.tfa'.format(os.path.split(url)[-1])) size = 0 try: stats = os.stat(output_file) size = stats.st_size except FileNotFoundError: pass if not os.path.isfile(output_f...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier call attribute string string_start string_content string_end identifier argument_list subscript ...
Download the allele files
def run(self): log.debug("Starting Kafka producer I/O thread.") while self._running: try: self.run_once() except Exception: log.exception("Uncaught error in kafka producer I/O thread") log.debug("Beginning shutdown of Kafka producer I/O thr...
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end while_statement attribute identifier identifier block try_statement block expression_statement call attribute identifier identifier argu...
The main run loop for the sender thread.
def history(verbose, range): alembic_command.history( config=get_config(), rev_range=range, verbose=verbose )
module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list keyword_argument identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier
List revision changesets chronologically
def from_string(cls, s): for num, text in cls._STATUS2STR.items(): if text == s: return cls(num) else: raise ValueError("Wrong string %s" % s)
module function_definition identifier parameters identifier identifier block for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list block if_statement comparison_operator identifier identifier block return_statement call identifier argument_list identifi...
Return a `Status` instance from its string representation.
def create_router(self, name, tenant_id, subnet_lst): try: body = {'router': {'name': name, 'tenant_id': tenant_id, 'admin_state_up': True}} router = self.neutronclient.create_router(body=body) rout_dict = router.get('router') rout_i...
module function_definition identifier parameters identifier identifier identifier identifier block try_statement block expression_statement assignment identifier dictionary pair string string_start string_content string_end dictionary pair string string_start string_content string_end identifier pair string string_star...
Create a openstack router and add the interfaces.
def _CreateSudoersGroup(self): if not self._GetGroup(self.google_sudoers_group): try: command = self.groupadd_cmd.format(group=self.google_sudoers_group) subprocess.check_call(command.split(' ')) except subprocess.CalledProcessError as e: self.logger.warning('Could not create the...
module function_definition identifier parameters identifier block if_statement not_operator call attribute identifier identifier argument_list attribute identifier identifier block try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyw...
Create a Linux group for Google added sudo user accounts.
def _get_sql(filename): with open(os.path.join(SQL_DIR, filename), 'r') as f: return f.read()
module function_definition identifier parameters identifier block with_statement with_clause with_item as_pattern call identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier identifier string string_start string_content string_end as_pattern_target identifier block r...
Returns the contents of the sql file from the given ``filename``.
def endSubscription(self, subscriber): self._reqId2Contract.pop(subscriber.reqId, None) self.reqId2Subscriber.pop(subscriber.reqId, None)
module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier none expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier...
Unregister a live subscription.
def sphinx_extension(app, exception): "Wrapped up as a Sphinx Extension" if not app.builder.name in ("html", "dirhtml"): return if not app.config.sphinx_to_github: if app.config.sphinx_to_github_verbose: print("Sphinx-to-github: Disabled, doing nothing.") return if ex...
module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end if_statement not_operator comparison_operator attribute attribute identifier identifier identifier tuple string string_start string_content string_end string string_start strin...
Wrapped up as a Sphinx Extension
def getPreprocessorDefinitions(self, engineRoot, delimiter=' '): return delimiter.join(self.resolveRoot(self.definitions, engineRoot))
module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content string_end block return_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier identifier
Returns the list of preprocessor definitions for this library, joined using the specified delimiter
def check_who_read(self, messages): for m in messages: readers = [] for p in m.thread.participation_set.all(): if p.date_last_check is None: pass elif p.date_last_check > m.sent_at: readers.append(p.participant.id) ...
module function_definition identifier parameters identifier identifier block for_statement identifier identifier block expression_statement assignment identifier list for_statement identifier call attribute attribute attribute identifier identifier identifier identifier argument_list block if_statement comparison_opera...
Check who read each message.
def WaitForSnapshotCompleted(snapshot): print 'Waiting for snapshot %s to be completed...' % (snapshot) while True: snapshot.update() sys.stdout.write('.') sys.stdout.flush() if snapshot.status == 'completed': break time.sleep(5) return
module function_definition identifier parameters identifier block print_statement binary_operator string string_start string_content string_end parenthesized_expression identifier while_statement true block expression_statement call attribute identifier identifier argument_list expression_statement call attribute attri...
Blocks until snapshot is complete.
def validate(self, data, schema, **kwargs): if not isinstance(schema, dict): schema = {'$ref': schema} return validate( data, schema, resolver=self.ref_resolver_cls.from_schema(schema), types=self.app.config.get('RECORDS_VALIDATION_TYPES', {}),...
module function_definition identifier parameters identifier identifier identifier dictionary_splat_pattern identifier block if_statement not_operator call identifier argument_list identifier identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end identif...
Validate data using schema with ``JSONResolver``.
def _checkDragDropEvent(self, ev): mimedata = ev.mimeData() if mimedata.hasUrls(): urls = [str(url.toLocalFile()) for url in mimedata.urls() if url.toLocalFile()] else: urls = [] if urls: ev.acceptProposedAction() return urls else: ...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement call attribute identifier identifier argument_list block expression_statement assignment identifier list_comprehension call identifier a...
Checks if event contains a file URL, accepts if it does, ignores if it doesn't
def setup_multiifo_combine_statmap(workflow, final_bg_file_list, out_dir, tags): if tags is None: tags = [] make_analysis_dir(out_dir) logging.info('Setting up multiifo combine statmap') cstat_exe = PyCBCMultiifoCombineStatmap(workflow.cp, 'combine_sta...
module function_definition identifier parameters identifier identifier identifier identifier block if_statement comparison_operator identifier none block expression_statement assignment identifier list expression_statement call identifier argument_list identifier expression_statement call attribute identifier identifie...
Combine the multiifo statmap files into one background file
def render(self, context, instance, placeholder): if instance and instance.template: self.render_template = instance.template return super(PluginTemplateMixin,self).render(context,instance,placeholder)
module function_definition identifier parameters identifier identifier identifier identifier block if_statement boolean_operator identifier attribute identifier identifier block expression_statement assignment attribute identifier identifier attribute identifier identifier return_statement call attribute call identifie...
Permits setting of the template in the plugin instance configuration
def clean_workspace(self): if os.path.isdir(self._temp_workspace): shutil.rmtree(self._temp_workspace)
module function_definition identifier parameters identifier block if_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier
Clean up the temporary workspace if one exists
def coverage_lineplot (self): data = list() data_labels = list() if len(self.rna_seqc_norm_high_cov) > 0: data.append(self.rna_seqc_norm_high_cov) data_labels.append({'name': 'High Expressed'}) if len(self.rna_seqc_norm_medium_cov) > 0: data.append(sel...
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call identifier argument_list if_statement comparison_operator call identifier argument_list attribute identifier identifier integer block...
Make HTML for coverage line plots
def nearest(self, idx): hi = self.after(idx) lo = self.before(idx) if hi is None: return lo if lo is None: return hi if abs(hi - idx) < abs(lo - idx): return hi return lo
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator ...
Return datetime of record whose datetime is nearest idx.
def Construct(self): self.gdml_parser.Read(self.filename) self.world = self.gdml_parser.GetWorldVolume() self.log.info("Materials:") self.log.info(G4.G4Material.GetMaterialTable()) return self.world
module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argumen...
Construct a cuboid from a GDML file without sensitive detector
def ignored_regions(source): return [(match.start(), match.end()) for match in _str.finditer(source)]
module function_definition identifier parameters identifier block return_statement list_comprehension tuple call attribute identifier identifier argument_list call attribute identifier identifier argument_list for_in_clause identifier call attribute identifier identifier argument_list identifier
Return ignored regions like strings and comments in `source`
def timestamp(self): if self.conf.time_source == CTIME: return os.path.getctime(self.path) return email.utils.mktime_tz(email.utils.parsedate_tz( self.message.get('Date')))
module function_definition identifier parameters identifier block if_statement comparison_operator attribute attribute identifier identifier identifier identifier block return_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier return_statement call attribut...
Compute the normalized canonical timestamp of the mail.
def initialize_dag(self, targets: Optional[List[str]] = [], nested: bool = False) -> SoS_DAG: self.reset_dict() dag = SoS_DAG(name=self.md5) targets = sos_targets(targets) self.add_forward_workflow(dag, self.workflow.sections) if self...
module function_definition identifier parameters identifier typed_default_parameter identifier type generic_type identifier type_parameter type generic_type identifier type_parameter type identifier list typed_default_parameter identifier type identifier false type identifier block expression_statement call attribute i...
Create a DAG by analyzing sections statically.
def make_gym_env(env_id, num_env=2, seed=123, wrapper_kwargs=None, start_index=0): if wrapper_kwargs is None: wrapper_kwargs = {} def make_env(rank): def _thunk(): env = gym.make(env_id) env.seed(seed + rank) return env return _thunk set_global_see...
module function_definition identifier parameters identifier default_parameter identifier integer default_parameter identifier integer default_parameter identifier none default_parameter identifier integer block if_statement comparison_operator identifier none block expression_statement assignment identifier dictionary ...
Create a wrapped, SubprocVecEnv for Gym Environments.
def cast_column(self, keys, func): import utool as ut for key in ut.ensure_iterable(keys): self[key] = [func(v) for v in self[key]]
module function_definition identifier parameters identifier identifier identifier block import_statement aliased_import dotted_name identifier identifier for_statement identifier call attribute identifier identifier argument_list identifier block expression_statement assignment subscript identifier identifier list_comp...
like map column but applies values inplace
def deleted_records(endpoint): @utils.for_each_value def _deleted_records(self, key, value): deleted_recid = maybe_int(value.get('a')) if deleted_recid: return get_record_ref(deleted_recid, endpoint) return _deleted_records
module function_definition identifier parameters identifier block decorated_definition decorator attribute identifier identifier function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier ...
Populate the ``deleted_records`` key.
def delay_or_fail(self, *args, **kwargs): return self.async_or_fail(args=args, kwargs=kwargs)
module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block return_statement call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier
Wrap async_or_fail with a convenience signiture like delay
def _classify_load_constant(self, regs_init, regs_fini, mem_fini, written_regs, read_regs): matches = [] for dst_reg, dst_val in regs_fini.items(): if dst_reg not in written_regs: continue if dst_val == regs_init[dst_reg]: continue dst_...
module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block expression_statement assignment identifier list for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement comparison_operator identifier i...
Classify load-constant gadgets.
def del_module(self, module): rev = util.get_latest_revision(module) del self.modules[(module.arg, rev)]
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier delete_statement subscript attribute identifier identifier tuple attribute identifier identifier identifier
Remove a module from the context
def fix_e731(self, result): (line_index, _, target) = get_index_offset_contents(result, self.source) match = LAMBDA_REGEX.search(target) if match: end = match.end() self.source[line_index] = '{}def {}({}): return...
module function_definition identifier parameters identifier identifier block expression_statement assignment tuple_pattern identifier identifier identifier call identifier argument_list identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_li...
Fix do not assign a lambda expression check.
def pypi( click_ctx, requirements, index=None, python_version=3, exclude_packages=None, output=None, subgraph_check_api=None, no_transitive=True, no_pretty=False, ): requirements = [requirement.strip() for requirement in requirements.split("\\n") if requirement] if not requir...
module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier integer default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier true default_parameter identifier false block e...
Manipulate with dependency requirements using PyPI.
def asDictionary(self): feat_dict = {} if self._geom is not None: if 'feature' in self._dict: feat_dict['geometry'] = self._dict['feature']['geometry'] elif 'geometry' in self._dict: feat_dict['geometry'] = self._dict['geometry'] if 'featu...
module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary if_statement comparison_operator attribute identifier identifier none block if_statement comparison_operator string string_start string_content string_end attribute identifier identifier block express...
returns the feature as a dictionary
def greedy_trails(subg, odds, verbose): if verbose: print('\tCreating edge map') edges = defaultdict(list) for x,y in subg.edges(): edges[x].append(y) edges[y].append(x) if verbose: print('\tSelecting trails') trails = [] for x in subg.nodes(): if verbose ...
module function_definition identifier parameters identifier identifier identifier block if_statement identifier block expression_statement call identifier argument_list string string_start string_content escape_sequence string_end expression_statement assignment identifier call identifier argument_list identifier for_s...
Greedily select trails by making the longest you can until the end
def _clone(self): instance = super(Bungiesearch, self)._clone() instance._raw_results_only = self._raw_results_only return instance
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute call identifier argument_list identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier attribute identifier identifier return_statement identi...
Must clone additional fields to those cloned by elasticsearch-dsl-py.
def mutate(self, p_mutate): new_dna = [] for bit in self.dna: if random.random() < p_mutate: bit = '1' if bit == '0' else '0' new_dna.append(bit) self.dna = ''.join(new_dna)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list for_statement identifier attribute identifier identifier block if_statement comparison_operator call attribute identifier identifier argument_list identifier block expression_statement assignment...
Check each element for mutation, swapping "0" for "1" and vice-versa.
def _get_config(self, unit, filename): file_contents = unit.file_contents(filename) config = configparser.ConfigParser(allow_no_value=True) config.readfp(io.StringIO(file_contents)) return config
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier true ...
Get a ConfigParser object for parsing a unit's config file.
def _version_newer_than(self, vers): v = self.version(self.executable()) vers_num = v[:v.index('-')] if not vers_num[0].isdigit(): return False v1 = list(map(int, vers_num.split('.'))) v2 = list(map(int, vers.split('.'))) assert len(v1) == 3 assert len...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list expression_statement assignment identifier subscript identifier slice call attribute identifier id...
Determine whether the version is greater than some given version
def to_gpu(*args): if len(args) > 1: return (cp.asarray(x) for x in args) else: return cp.asarray(args[0])
module function_definition identifier parameters list_splat_pattern identifier block if_statement comparison_operator call identifier argument_list identifier integer block return_statement generator_expression call attribute identifier identifier argument_list identifier for_in_clause identifier identifier else_clause...
Upload numpy arrays to GPU and return them
def del_pickled_ontology(filename): pickledfile = ONTOSPY_LOCAL_CACHE + "/" + filename + ".pickle" if os.path.isfile(pickledfile) and not GLOBAL_DISABLE_CACHE: os.remove(pickledfile) return True else: return None
module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator binary_operator binary_operator identifier string string_start string_content string_end identifier string string_start string_content string_end if_statement boolean_operator call attribute attr...
try to remove a cached ontology
def xgroup_setid(self, stream, group_name, latest_id='$'): fut = self.execute(b'XGROUP', b'SETID', stream, group_name, latest_id) return wait_ok(fut)
module function_definition identifier parameters identifier identifier identifier default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_sta...
Set the latest ID for a consumer group
def save_png_with_metadata(fig, filename, fig_kwds, kwds): from PIL import Image, PngImagePlugin fig.savefig(filename, **fig_kwds) im = Image.open(filename) meta = PngImagePlugin.PngInfo() for key in kwds: meta.add_text(str(key), str(kwds[key])) im.save(filename, "png", pnginfo=meta)
module function_definition identifier parameters identifier identifier identifier identifier block import_from_statement dotted_name identifier dotted_name identifier dotted_name identifier expression_statement call attribute identifier identifier argument_list identifier dictionary_splat identifier expression_statemen...
Save a matplotlib figure to a png with metadata
def stream_length(self): if self._stream_length is None: try: current_position = self.source_stream.tell() self.source_stream.seek(0, 2) self._stream_length = self.source_stream.tell() self.source_stream.seek(current_position, 0) ...
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribu...
Returns the length of the source stream, determining it if not already known.
def histogram_info(self) -> dict: return { 'support_atoms': self.support_atoms, 'atom_delta': self.atom_delta, 'vmin': self.vmin, 'vmax': self.vmax, 'num_atoms': self.atoms }
module function_definition identifier parameters identifier type 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 stri...
Return extra information about histogram
def create_entity_class(self): entity = Entity() entity.PartitionKey = 'pk{}'.format(str(uuid.uuid4()).replace('-', '')) entity.RowKey = 'rk{}'.format(str(uuid.uuid4()).replace('-', '')) entity.age = 39 entity.large = 933311100 entity.sex = 'male' entity.married =...
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment attribute identifier identifier call attribute string string_start string_content string_end identifier argument_list call attribute call identifier ...
Creates a class-based entity with fixed values, using all of the supported data types.
def objref(obj): ref = _objrefs.get(obj) if ref is None: clsname = obj.__class__.__name__.split('.')[-1] seqno = _lastids.setdefault(clsname, 1) ref = '{}-{}'.format(clsname, seqno) _objrefs[obj] = ref _lastids[clsname] += 1 return ref
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier none block expression_statement assignment identifier subscript call attribute attribute attribute identi...
Return a string that uniquely and compactly identifies an object.
def hostname_text(self): if self._hostname_text is None: self.chain.connection.log("Collecting hostname information") self._hostname_text = self.driver.get_hostname_text() if self._hostname_text: self.chain.connection.log("Hostname info collected") ...
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end expression_stateme...
Return hostname text and collect if not collected.
def _extract_sender( message: Message, resent_dates: List[Union[str, Header]] = None ) -> str: if resent_dates: sender_header = "Resent-Sender" from_header = "Resent-From" else: sender_header = "Sender" from_header = "From" if sender_header in message: sender = me...
module function_definition identifier parameters typed_parameter identifier type identifier typed_default_parameter identifier type generic_type identifier type_parameter type generic_type identifier type_parameter type identifier type identifier none type identifier block if_statement identifier block expression_state...
Extract the sender from the message object given.
def auth_request(self, url, headers, body): return self.req.post(url, headers, body=body)
module function_definition identifier parameters identifier identifier identifier identifier block return_statement call attribute attribute identifier identifier identifier argument_list identifier identifier keyword_argument identifier identifier
Perform auth request for token.
def print_yaml(o): print(yaml.dump(o, default_flow_style=False, indent=4, encoding='utf-8'))
module function_definition identifier parameters identifier block expression_statement call identifier argument_list call attribute identifier identifier argument_list identifier keyword_argument identifier false keyword_argument identifier integer keyword_argument identifier string string_start string_content string_e...
Pretty print an object as YAML.
def loss(loss_value): total_loss = tf.Variable(0.0, False) loss_count = tf.Variable(0, False) total_loss_update = tf.assign_add(total_loss, loss_value) loss_count_update = tf.assign_add(loss_count, 1) loss_op = total_loss / tf.cast(loss_count, tf.float32) return [total_loss_update, loss_count_update], loss_...
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list float false expression_statement assignment identifier call attribute identifier identifier argument_list integer false expression_statement assignment identifi...
Calculates aggregated mean loss.
def _detect(env): QTDIR = None if not QTDIR: QTDIR = env.get('QTDIR',None) if not QTDIR: QTDIR = os.environ.get('QTDIR',None) if not QTDIR: moc = env.WhereIs('moc') if moc: QTDIR = os.path.dirname(os.path.dirname(moc)) SCons.Warnings.warn( ...
module function_definition identifier parameters identifier block expression_statement assignment identifier none if_statement not_operator identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end none if_statement not_o...
Not really safe, but fast method to detect the QT library
def n_hot(ids, c): res = np.zeros((c,), dtype=np.float32) res[ids] = 1 return res
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list tuple identifier keyword_argument identifier attribute identifier identifier expression_statement assignment subscript identifier identifier integer ...
one hot encoding by index. Returns array of length c, where all entries are 0, except for the indecies in ids
def draw_separators(self): total = 1 self._timeline.create_line((0, 1, self.pixel_width, 1)) for index, (category, label) in enumerate(self._category_labels.items()): height = label.winfo_reqheight() self._rows[category] = (total, total + height) total += heig...
module function_definition identifier parameters identifier block expression_statement assignment identifier integer expression_statement call attribute attribute identifier identifier identifier argument_list tuple integer integer attribute identifier identifier integer for_statement pattern_list identifier tuple_patt...
Draw the lines separating the categories on the Canvas
def deploy_webconf(): deployed = [] log_dir = '/'.join([deployment_root(),'log']) if webserver_list(): if env.verbosity: print env.host,"DEPLOYING webconf:" if not exists(log_dir): run('ln -s /var/log log') if 'apache2' in get_packages(): deployed ...
module function_definition identifier parameters block expression_statement assignment identifier list expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list list call identifier argument_list string string_start string_content string_end if_stat...
Deploy nginx and other wsgi server site configurations to the host
def on_retry(self, exc, task_id, args, kwargs, einfo): super(LoggedTask, self).on_retry(exc, task_id, args, kwargs, einfo) log.warning('[{}] retried due to {}'.format(task_id, getattr(einfo, 'traceback', None)))
module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list identifier identifier identifier identifier identifier expression_statement call attri...
Capture the exception that caused the task to be retried, if any.
def create_update_symlink(self, link_destination, remote_path): try: self.sftp.remove(remote_path) except IOError: pass finally: try: self.sftp.symlink(link_destination, remote_path) except OSError as e: self.logger....
module function_definition identifier parameters identifier identifier identifier block try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list identifier except_clause identifier block pass_statement finally_clause block try_statement block expression_statement ...
Create a new link pointing to link_destination in remote_path position.
def contribute_to_class(self, cls, name, virtual_only=False): super(RegexField, self).contribute_to_class(cls, name, virtual_only) setattr(cls, name, CastOnAssignDescriptor(self))
module function_definition identifier parameters identifier identifier identifier default_parameter identifier false block expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list identifier identifier identifier expression_statement call identifier argument_list ...
Cast to the correct value every
def active_plan_summary(self): return self.active().values("plan").order_by().annotate(count=models.Count("plan"))
module function_definition identifier parameters identifier block return_statement call attribute call attribute call attribute call attribute identifier identifier argument_list identifier argument_list string string_start string_content string_end identifier argument_list identifier argument_list keyword_argument ide...
Return active Subscriptions with plan counts annotated.
def feature_analysis(fname="feature_analysis.png"): _, axes = plt.subplots(ncols=2, figsize=(18,6)) data = load_occupancy(split=False) oz = RadViz(ax=axes[0], classes=["unoccupied", "occupied"]) oz.fit(data.X, data.y) oz.finalize() data = load_concrete(split=False) oz = Rank2D(ax=axes[1]) ...
module function_definition identifier parameters default_parameter identifier string string_start string_content string_end block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list keyword_argument identifier integer keyword_argument identifier tuple in...
Create figures for feature analysis
def list_tables(refresh=False, cache_file=None): if not cache_file: cache_file = os.path.join(str(Path.home()), ".bcdata") if refresh or check_cache(cache_file): wfs = WebFeatureService(url=bcdata.OWS_URL, version="2.0.0") bcdata_objects = [i.strip("pub:") for i in list(wfs.contents)] ...
module function_definition identifier parameters default_parameter identifier false default_parameter identifier none block if_statement not_operator identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call identifier argument_list call att...
Return a list of all datasets available via WFS
def resources_assigned(self) -> List[Resource]: resources_str = DB.get_hash_value(self.key, 'resources_assigned') resources_assigned = [] for resource in ast.literal_eval(resources_str): resources_assigned.append(Resource(resource)) return resources_assigned
module function_definition identifier parameters identifier type generic_type identifier type_parameter type identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier string string_start string_content string_end expression_statement a...
Return list of resources assigned to the PB.
def _create_websession(self): from socket import AF_INET from aiohttp import ClientTimeout, TCPConnector _LOGGER.debug('Creating web session') conn = TCPConnector( family=AF_INET, limit_per_host=5, enable_cleanup_closed=True, ) session_...
module function_definition identifier parameters identifier block import_from_statement dotted_name identifier dotted_name identifier import_from_statement dotted_name identifier dotted_name identifier dotted_name identifier expression_statement call attribute identifier identifier argument_list string string_start str...
Create a web session.
def Logger(name, **kargs): path_dirs = PathDirs(**kargs) logging.captureWarnings(True) logger = logging.getLogger(name) logger.setLevel(logging.INFO) handler = logging.handlers.WatchedFileHandler(os.path.join( path_dirs.meta_dir, 'vent.log')) handler.setLevel(logging.INFO) formatter ...
module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list dictionary_splat identifier expression_statement call attribute identifier identifier argument_list true expression_statement assignment identifi...
Create and return logger
def import_it(cls): if not cls in cls._FEATURES: try: cls._FEATURES[cls] = cls._import_it() except ImportError: raise cls.Error(cls._import_error_message(), cls.Error.UNSATISFIED_IMPORT_REQ) return cls._FEATURES[cls]
module function_definition identifier parameters identifier block if_statement not_operator comparison_operator identifier attribute identifier identifier block try_statement block expression_statement assignment subscript attribute identifier identifier identifier call attribute identifier identifier argument_list exc...
Performs the import only once.
def copy_file(filename): print("Updating file %s" % filename) out_dir = os.path.abspath(DIRECTORY) tags = filename[:-4].split("-") tags[-2] = tags[-2].replace("m", "") new_name = "-".join(tags) + ".whl" wheel_flag = "-".join(tags[2:]) with InWheelCtx(os.path.join(DIRECTORY, filename)) as ctx...
module function_definition identifier parameters identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expr...
Copy the file and put the correct tag
def format_call(self, api_version, api_call): api_call = api_call.lstrip('/') api_call = api_call.rstrip('?') logger.debug('api_call post strip =\n%s' % api_call) if (api_version == 2 and api_call[-1] != '/'): logger.debug('Adding "/" to api_call.') api_call += '/...
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_lis...
Return properly formatted QualysGuard API call according to api_version etiquette.
def _get_dL2L(self, imt_per): if imt_per < 0.18: dL2L = -0.06 elif 0.18 <= imt_per < 0.35: dL2L = self._interp_function(0.12, -0.06, 0.35, 0.18, imt_per) elif 0.35 <= imt_per <= 10: dL2L = self._interp_function(0.65, 0.12, 10, 0.35, imt_per) else: ...
module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier float block expression_statement assignment identifier unary_operator float elif_clause comparison_operator float identifier float block expression_statement assignment identifier call attribute iden...
Table 3 and equation 19 of 2013 report.
def _channel_exists_and_not_settled( self, participant1: Address, participant2: Address, block_identifier: BlockSpecification, channel_identifier: ChannelID = None, ) -> bool: try: channel_state = self._get_channel_state( ...
module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_parameter identifier type identifier typed_parameter identifier type identifier typed_default_parameter identifier type identifier none type identifier block try_statement block expression_statement assignment i...
Returns if the channel exists and is in a non-settled state
def mail_json(self): if self.mail.get("date"): self._mail["date"] = self.date.isoformat() return json.dumps(self.mail, ensure_ascii=False, indent=2)
module function_definition identifier parameters identifier block if_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end block expression_statement assignment subscript attribute identifier identifier string string_start string_content string_e...
Return the JSON of mail parsed
def GetParserFromFilename(self, path): handler_name = path.split("://")[0] for parser_cls in itervalues(GRRConfigParser.classes): if parser_cls.name == handler_name: return parser_cls extension = os.path.splitext(path)[1] if extension in [".yaml", ".yml"]: return YamlParser retur...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript call attribute identifier identifier argument_list string string_start string_content string_end integer for_statement identifier call identifier argument_list attribute identifier identifie...
Returns the appropriate parser class from the filename.
def issuperset(self, other): self._binary_sanity_check(other) return set.issuperset(self, other)
module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list identifier identifier
Report whether this RangeSet contains another set.
def kvlclient(self): if self._kvlclient is None: self._kvlclient = kvlayer.client() return self._kvlclient
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list return_statement attribute identifier identifier
Return a thread local ``kvlayer`` client.
def create_untl_xml_subelement(parent, element, prefix=''): subelement = SubElement(parent, prefix + element.tag) if element.content is not None: subelement.text = element.content if element.qualifier is not None: subelement.attrib["qualifier"] = element.qualifier if element.children > 0...
module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_end block expression_statement assignment identifier call identifier argument_list identifier binary_operator identifier attribute identifier identifier if_statement comparison_operator attribu...
Create a UNTL XML subelement.
def save_db(self): with self.db_mutex: if not isinstance(self.db, dict) and not isinstance(self.db, list): return False try: with open(self.json_db_path, "w") as fp: json.dump(self.db, fp, indent=4) except Exception as e: ...
module function_definition identifier parameters identifier block with_statement with_clause with_item attribute identifier identifier block if_statement boolean_operator not_operator call identifier argument_list attribute identifier identifier identifier not_operator call identifier argument_list attribute identifier...
" Save json db to file system.
def s2time(secs, show_secs=True, show_fracs=True): try: secs = float(secs) except: return "--:--:--.--" wholesecs = int(secs) centisecs = int((secs - wholesecs) * 100) hh = int(wholesecs / 3600) hd = int(hh % 24) mm = int((wholesecs / 60) - (hh*60)) ss = int(wholesecs - (...
module function_definition identifier parameters identifier default_parameter identifier true default_parameter identifier true block try_statement block expression_statement assignment identifier call identifier argument_list identifier except_clause block return_statement string string_start string_content string_end...
Converts seconds to time
def _get_hydrated_path(field): if isinstance(field, str) and hasattr(field, 'file_name'): return field if isinstance(field, dict) and 'file' in field: hydrated_path = field['file'] if not hasattr(hydrated_path, 'file_name'): raise TypeError("Filter argument must be a valid file-type ...
module function_definition identifier parameters identifier block if_statement boolean_operator call identifier argument_list identifier identifier call identifier argument_list identifier string string_start string_content string_end block return_statement identifier if_statement boolean_operator call identifier argum...
Return HydratedPath object for file-type field.
def selector(C, style): clas = C.classname(style.name) if style.type == 'paragraph': outlineLvl = int((style.properties.get('outlineLvl') or {}).get('val') or 8) + 1 if outlineLvl < 9: tag = 'h%d' % outlineLvl else: tag = 'p' el...
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block ...
return the selector for the given stylemap style
def sam_readline(sock, partial = None): response = b'' exception = None while True: try: c = sock.recv(1) if not c: raise EOFError('SAM connection died. Partial response %r %r' % (partial, response)) elif c == b'\n': break ...
module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier string string_start string_end expression_statement assignment identifier none while_statement true block try_statement block expression_statement assignment identifier call att...
read a line from a sam control socket
def split(src, chunksize=MINWEIGHT): for i, block in enumerate(block_splitter(src.iter_ruptures(), chunksize, key=operator.attrgetter('mag'))): rup = block[0] source_id = '%s:%d' % (src.source_id, i) amfd = mfd.ArbitraryMFD([rup.mag], [rup.mag_occ...
module function_definition identifier parameters identifier default_parameter identifier identifier block for_statement pattern_list identifier identifier call identifier argument_list call identifier argument_list call attribute identifier identifier argument_list identifier keyword_argument identifier call attribute ...
Split a complex fault source in chunks
def find_all_runs(self, session=None): with self._session(session) as session: return session.query(TaskRecord).all()
module function_definition identifier parameters identifier default_parameter identifier none block with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list identifier as_pattern_target identifier block return_statement call attribute call attribute identifier identifier argume...
Return all tasks that have been updated.
def sanitize_win_path(winpath): intab = '<>:|?*' if isinstance(winpath, six.text_type): winpath = winpath.translate(dict((ord(c), '_') for c in intab)) elif isinstance(winpath, six.string_types): outtab = '_' * len(intab) trantab = ''.maketrans(intab, outtab) if six.PY3 else string.m...
module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_content string_end if_statement call identifier argument_list identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier iden...
Remove illegal path characters for windows
def _set_conn(self): if self._tls: ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER) try: conn = ldap.initialize(self._url) conn.set_option(ldap.OPT_NETWORK_TIMEOUT, self._timeout) conn.simple_bind_s(self._binddn, self._bindpw) exc...
module function_definition identifier parameters identifier block if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier try_statement block expression_statement assignment identifier call...
Establish connection to the server
def _compress_obj(obj, level): return zlib.compress(pickle.dumps(obj, protocol=2), level)
module function_definition identifier parameters identifier identifier block return_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier keyword_argument identifier integer identifier
Compress object to bytes.
def divideHosts(self, hosts, qty): maximumWorkers = sum(host[1] for host in hosts) if qty > maximumWorkers: index = 0 while qty > maximumWorkers: hosts[index] = (hosts[index][0], hosts[index][1] + 1) index = (index + 1) % len(hosts) ...
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier generator_expression subscript identifier integer for_in_clause identifier identifier if_statement comparison_operator identifier identifier block expression_statement assig...
Divide processes among hosts.
def coroutine(func): def __start(*args, **kwargs): __cr = func(*args, **kwargs) next(__cr) return __cr return __start
module function_definition identifier parameters identifier block function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list list_splat identifier dictionary_splat identifier expression_statem...
Basic decorator to implement the coroutine pattern.
def house_exists(self, complex: str, house: str) -> bool: try: self.check_house(complex, house) except exceptions.RumetrHouseNotFound: return False return True
module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_parameter identifier type identifier type identifier block try_statement block expression_statement call attribute identifier identifier argument_list identifier identifier except_clause attribute identifier ide...
Shortcut to check if house exists in our database.
def user_is_submission_owner(self, submission): if not self._user_manager.session_logged_in(): raise Exception("A user must be logged in to verify if he owns a jobid") return self._user_manager.session_username() in submission["username"]
module function_definition identifier parameters identifier identifier block if_statement not_operator call attribute attribute identifier identifier identifier argument_list block raise_statement call identifier argument_list string string_start string_content string_end return_statement comparison_operator call attri...
Returns true if the current user is the owner of this jobid, false else
def ConsultarLiquidacionesPorContrato(self, nro_contrato=None, cuit_comprador=None, cuit_vendedor=None, cuit_corredor=None, co...
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 none dictionary_splat_pattern identifier block expression_statement string string_start string_...
Obtener los COE de liquidaciones relacionadas a un contrato
def delete(ctx, resource, id): session, api_url, project_id = build_client_from_context(ctx) url = '/'.join([api_url, resource, id]) r = session.delete(url) if r.status_code != 200: raise failed_request_exception('failed to delete resource', r) click.echo(r.text)
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment pattern_list identifier identifier identifier call identifier argument_list identifier expression_statement assignment identifier call attribute string string_start string_content string_end identifie...
Delete given device model or instance.
def draw(self, surf): if self.shown: for w in self.widgets: surf.blit(w.image, self.convert_rect(w.rect)) for c in self.containers: c.draw(surf)
module function_definition identifier parameters identifier identifier block if_statement attribute identifier identifier block for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier call attribute identifier...
Draw all widgets and sub-containers to @surf.
def _parse_title(line_iter, cur_line, conf): title = [] conf['title'].append(title) title.append(('title_name', cur_line.split('title', 1)[1].strip())) while (True): line = next(line_iter) if line.startswith("title "): return line cmd, opt = _parse_cmd(line) t...
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier list expression_statement call attribute subscript identifier string string_start string_content string_end identifier argument_list identifier expression_statement call attribute identifie...
Parse "title" in grub v1 config
def runlist_remove(name, **kwargs): ctx = Context(**kwargs) ctx.execute_action('runlist:remove', **{ 'storage': ctx.repo.create_secure_service('storage'), 'name': name, })
module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list dictionary_splat identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end...
Remove runlist from the storage.
def categories(self): if not getattr(self, '_categories', False): self._categories = [re.sub(r'^Category:', '', x) for x in [link['title'] for link in self.__continued_query({ 'prop': 'categories', 'cllimit': 'max' }) ]] return self._categories
module function_definition identifier parameters identifier block if_statement not_operator call identifier argument_list identifier string string_start string_content string_end false block expression_statement assignment attribute identifier identifier list_comprehension call attribute identifier identifier argument_...
List of categories of a page.
def causally_significant_nodes(cm): inputs = cm.sum(0) outputs = cm.sum(1) nodes_with_inputs_and_outputs = np.logical_and(inputs > 0, outputs > 0) return tuple(np.where(nodes_with_inputs_and_outputs)[0])
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list integer expression_statement assignment identifier call attribute identifier identifier argument_list integer expression_statement assignment identifier call at...
Return indices of nodes that have both inputs and outputs.
def register_db(cls, dbname): def decorator(subclass): cls._dbs[dbname] = subclass subclass.name = dbname return subclass return decorator
module function_definition identifier parameters identifier identifier block function_definition identifier parameters identifier block expression_statement assignment subscript attribute identifier identifier identifier identifier expression_statement assignment attribute identifier identifier identifier return_statem...
Register method to keep list of dbs.
def project(self, lng_lat): (lng, lat) = lng_lat x = lng * DEG_TO_RAD lat = max(min(MAX_LATITUDE, lat), -MAX_LATITUDE) y = lat * DEG_TO_RAD y = log(tan((pi / 4) + (y / 2))) return (x*EARTH_RADIUS, y*EARTH_RADIUS)
module function_definition identifier parameters identifier identifier block expression_statement assignment tuple_pattern identifier identifier identifier expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier call identifier argument_list call ident...
Returns the coordinates in meters from WGS84
def ExtendAnomalies(self, other): for o in other: if o is not None: self.anomaly.Extend(list(o.anomaly))
module function_definition identifier parameters identifier identifier block for_statement identifier identifier block if_statement comparison_operator identifier none block expression_statement call attribute attribute identifier identifier identifier argument_list call identifier argument_list attribute identifier id...
Merge anomalies from another CheckResult.