code
stringlengths
51
2.34k
sequence
stringlengths
186
3.94k
docstring
stringlengths
11
171
def iddofobject(data, commdct, key): dtls = data.dtls i = dtls.index(key) return commdct[i]
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement subscript identifier identifier
from commdct, return the idd of the object key
def hours(self,local=False): delta = self.delta(local) return delta.total_seconds()/3600
module function_definition identifier parameters identifier default_parameter identifier false block expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement binary_operator call attribute identifier identifier argument_list integer
Returns the number of hours of difference
def canonical_key(self, key): if key.startswith('/'): return urlparse.urljoin(self.base_uri, key) else: return self.curies.expand(key)
module function_definition identifier parameters identifier identifier block if_statement call attribute identifier identifier argument_list string string_start string_content string_end block return_statement call attribute identifier identifier argument_list attribute identifier identifier identifier else_clause block return_statement call attribute attribute identifier identifier identifier argument_list identifier
Returns the canonical key for the given ``key``.
def turn_left(self): self.at(ardrone.at.pcmd, True, 0, 0, 0, -self.speed)
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list attribute attribute identifier identifier identifier true integer integer integer unary_operator attribute identifier identifier
Make the drone rotate left.
def _compile_seriesflow(self): string = ' ' self.seriesflow = compile(eval(string), '', 'exec')
module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier call identifier argument_list call identifier argument_list identifier string string_start string_end string string_start string_content string_end
Post power flow computation of series device flow
def __get_table(self, bucket): table_name = self.__mapper.convert_bucket(bucket) if self.__dbschema: table_name = '.'.join((self.__dbschema, table_name)) return self.__metadata.tables[table_name]
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier if_statement attribute identifier identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list tuple attribute identifier identifier identifier return_statement subscript attribute attribute identifier identifier identifier identifier
Get table by bucket
def list_command(endpoint_id): client = get_client() rules = client.endpoint_acl_list(endpoint_id) resolved_ids = LazyIdentityMap( x["principal"] for x in rules if x["principal_type"] == "identity" ) def principal_str(rule): principal = rule["principal"] if rule["principal_type"] == "identity": username = resolved_ids.get(principal) return username or principal elif rule["principal_type"] == "group": return (u"https://app.globus.org/groups/{}").format(principal) else: principal = rule["principal_type"] return principal formatted_print( rules, fields=[ ("Rule ID", "id"), ("Permissions", "permissions"), ("Shared With", principal_str), ("Path", "path"), ], )
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier generator_expression subscript identifier string string_start string_content string_end for_in_clause identifier identifier if_clause comparison_operator subscript identifier string string_start string_content string_end string string_start string_content string_end function_definition identifier parameters identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end if_statement comparison_operator subscript identifier string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement boolean_operator identifier identifier elif_clause comparison_operator subscript identifier string string_start string_content string_end string string_start string_content string_end block return_statement call attribute parenthesized_expression string string_start string_content string_end identifier argument_list identifier else_clause block expression_statement assignment identifier subscript identifier string string_start string_content string_end return_statement identifier expression_statement call identifier argument_list identifier keyword_argument identifier list tuple string string_start string_content string_end string string_start string_content string_end tuple string string_start string_content string_end string string_start string_content string_end tuple string string_start string_content string_end identifier tuple string string_start string_content string_end string string_start string_content string_end
Executor for `globus endpoint permission list`
def check(): upgrader = InvenioUpgrader() logger = upgrader.get_logger() try: upgrades = upgrader.get_upgrades() if not upgrades: logger.info("All upgrades have been applied.") return logger.info("Following upgrade(s) have not been applied yet:") for u in upgrades: logger.info( " * {0} {1}".format(u.name, u.info)) logger.info("Running pre-upgrade checks...") upgrader.pre_upgrade_checks(upgrades) logger.info("Upgrade check successful - estimated time for upgrading" " Invenio is %s..." % upgrader.human_estimate(upgrades)) except RuntimeError as e: for msg in e.args: logger.error(unicode(msg)) logger.error("Upgrade check failed. Aborting.") raise
module function_definition identifier parameters block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement not_operator identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement expression_statement call attribute identifier identifier argument_list string string_start string_content string_end for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list binary_operator concatenated_string string string_start string_content string_end string string_start string_content string_end call attribute identifier identifier argument_list identifier except_clause as_pattern identifier as_pattern_target identifier block for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end raise_statement
Command for checking upgrades.
def new_job(self, task, inputdata, launcher_name="Unknown", debug=False): bjobid = uuid.uuid4() self._waiting_jobs.append(str(bjobid)) self._client.new_job(task, inputdata, (lambda result, grade, problems, tests, custom, archive, stdout, stderr: self._callback(bjobid, result, grade, problems, tests, custom, archive, stdout, stderr)), launcher_name, debug) return bjobid
module function_definition identifier parameters identifier identifier identifier default_parameter identifier string string_start string_content string_end default_parameter identifier false block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list call identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier parenthesized_expression lambda lambda_parameters identifier identifier identifier identifier identifier identifier identifier identifier call attribute identifier identifier argument_list identifier identifier identifier identifier identifier identifier identifier identifier identifier identifier identifier return_statement identifier
Runs a new job. It works exactly like the Client class, instead that there is no callback
def unattach_issue(resource_id, issue_id, table): v1_utils.verify_existence_and_get(issue_id, _TABLE) if table.name == 'jobs': join_table = models.JOIN_JOBS_ISSUES where_clause = sql.and_(join_table.c.job_id == resource_id, join_table.c.issue_id == issue_id) else: join_table = models.JOIN_COMPONENTS_ISSUES where_clause = sql.and_(join_table.c.component_id == resource_id, join_table.c.issue_id == issue_id) query = join_table.delete().where(where_clause) result = flask.g.db_conn.execute(query) if not result.rowcount: raise dci_exc.DCIConflict('%s_issues' % table.name, issue_id) return flask.Response(None, 204, content_type='application/json')
module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list identifier identifier if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list comparison_operator attribute attribute identifier identifier identifier identifier comparison_operator attribute attribute identifier identifier identifier identifier else_clause block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list comparison_operator attribute attribute identifier identifier identifier identifier comparison_operator attribute attribute identifier identifier identifier identifier expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier argument_list identifier expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list identifier if_statement not_operator attribute identifier identifier block raise_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier identifier return_statement call attribute identifier identifier argument_list none integer keyword_argument identifier string string_start string_content string_end
Unattach an issue from a specific job.
def populate_cfg_dcnm(self, cfg, dcnm_obj): if not self.fw_init: return self.dcnm_obj = dcnm_obj self.fabric.store_dcnm(dcnm_obj) self.populate_dcnm_obj(dcnm_obj)
module function_definition identifier parameters identifier identifier identifier block if_statement not_operator attribute identifier identifier block return_statement expression_statement assignment attribute identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier
This routine stores the DCNM object.
def parse_directory_index(directory_index): if not directory_index.endswith('/'): directory_index = directory_index + '/' site_index = urllib2.urlopen(directory_index) parsed_site_index = bs(site_index) rpm_link_tags = parsed_site_index.findAll('a', href=re.compile(r'.*rpm$')) rpm_names = [link['href'] for link in rpm_link_tags] remote_list = map(lambda end: "".join([directory_index, end]), rpm_names) return remote_list
module function_definition identifier parameters identifier block if_statement not_operator call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier binary_operator identifier string string_start string_content string_end 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 attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier list_comprehension subscript identifier string string_start string_content string_end for_in_clause identifier identifier expression_statement assignment identifier call identifier argument_list lambda lambda_parameters identifier call attribute string string_start string_end identifier argument_list list identifier identifier identifier return_statement identifier
Retrieve a directory index and make a list of the RPMs listed.
def appliesToEvent(self, event): return ( event in self.individualEvents.all() or event.session in self.eventSessions.all() or event.category in self.seriesCategories.all() or event.category in self.eventCategories.all() )
module function_definition identifier parameters identifier identifier block return_statement parenthesized_expression boolean_operator boolean_operator boolean_operator comparison_operator identifier call attribute attribute identifier identifier identifier argument_list comparison_operator attribute identifier identifier call attribute attribute identifier identifier identifier argument_list comparison_operator attribute identifier identifier call attribute attribute identifier identifier identifier argument_list comparison_operator attribute identifier identifier call attribute attribute identifier identifier identifier argument_list
Check whether this guest list is applicable to an event.
def _get_hanging_wall_coeffs_rrup(self, dists): fhngrrup = np.ones(len(dists.rrup)) idx = dists.rrup > 0.0 fhngrrup[idx] = (dists.rrup[idx] - dists.rjb[idx]) / dists.rrup[idx] return fhngrrup
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list attribute identifier identifier expression_statement assignment identifier comparison_operator attribute identifier identifier float expression_statement assignment subscript identifier identifier binary_operator parenthesized_expression binary_operator subscript attribute identifier identifier identifier subscript attribute identifier identifier identifier subscript attribute identifier identifier identifier return_statement identifier
Returns the hanging wall rrup term defined in equation 13
def add_mutations_and_flush(self, table, muts): if not isinstance(muts, list) and not isinstance(muts, tuple): muts = [muts] cells = {} for mut in muts: cells.setdefault(mut.row, []).extend(mut.updates) self.client.updateAndFlush(self.login, table, cells)
module function_definition identifier parameters identifier identifier identifier block if_statement boolean_operator not_operator call identifier argument_list identifier identifier not_operator call identifier argument_list identifier identifier block expression_statement assignment identifier list identifier expression_statement assignment identifier dictionary for_statement identifier identifier block expression_statement call attribute call attribute identifier identifier argument_list attribute identifier identifier list identifier argument_list attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier identifier identifier
Add mutations to a table without the need to create and manage a batch writer.
def setup_logging(name): logger = logging.getLogger(__name__) if 'NVIM_PYTHON_LOG_FILE' in os.environ: prefix = os.environ['NVIM_PYTHON_LOG_FILE'].strip() major_version = sys.version_info[0] logfile = '{}_py{}_{}'.format(prefix, major_version, name) handler = logging.FileHandler(logfile, 'w', 'utf-8') handler.formatter = logging.Formatter( '%(asctime)s [%(levelname)s @ ' '%(filename)s:%(funcName)s:%(lineno)s] %(process)s - %(message)s') logging.root.addHandler(handler) level = logging.INFO if 'NVIM_PYTHON_LOG_LEVEL' in os.environ: lvl = getattr(logging, os.environ['NVIM_PYTHON_LOG_LEVEL'].strip(), level) if isinstance(lvl, int): level = lvl logger.setLevel(level)
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator string string_start string_content string_end attribute identifier identifier block expression_statement assignment identifier call attribute subscript attribute identifier identifier string string_start string_content string_end identifier argument_list expression_statement assignment identifier subscript attribute identifier identifier integer expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator string string_start string_content string_end attribute identifier identifier block expression_statement assignment identifier call identifier argument_list identifier call attribute subscript attribute identifier identifier string string_start string_content string_end identifier argument_list identifier if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier identifier expression_statement call attribute identifier identifier argument_list identifier
Setup logging according to environment variables.
def format_metric_values(self, metric_values): loss_str = 'N/A' accuracy_str = 'N/A' try: loss_str = 'loss: %.3f' % metric_values[0] accuracy_str = 'accuracy: %.3f' % metric_values[1] except (TypeError, IndexError): pass return '%s, %s' % (loss_str, accuracy_str)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier string string_start string_content string_end try_statement block expression_statement assignment identifier binary_operator string string_start string_content string_end subscript identifier integer expression_statement assignment identifier binary_operator string string_start string_content string_end subscript identifier integer except_clause tuple identifier identifier block pass_statement return_statement binary_operator string string_start string_content string_end tuple identifier identifier
Formats metric values - used for logging purpose.
def visit_Program(self, node): for child in node.children: if not isinstance(child, FunctionDeclaration): self.visit(child)
module function_definition identifier parameters identifier identifier block for_statement identifier attribute identifier identifier block if_statement not_operator call identifier argument_list identifier identifier block expression_statement call attribute identifier identifier argument_list identifier
Vsitor for `Program` AST node.
def commands(config, names): commands = {cmd: Command(**dict((minus_to_underscore(k), v) for k, v in config.items(cmd))) for cmd in config.sections() if cmd != 'packages'} try: return tuple(commands[x] for x in names) except KeyError as e: raise RuntimeError( 'Section [commands] in the config file does not contain the ' 'key {.args[0]!r} you requested to execute.'.format(e))
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary_comprehension pair identifier call identifier argument_list dictionary_splat call identifier generator_expression tuple call identifier argument_list identifier identifier for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list identifier for_in_clause identifier call attribute identifier identifier argument_list if_clause comparison_operator identifier string string_start string_content string_end try_statement block return_statement call identifier generator_expression subscript identifier identifier for_in_clause identifier identifier except_clause as_pattern identifier as_pattern_target identifier block raise_statement call identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list identifier
Return the list of commands to run.
def create_event_object(self, event_type, code, value, timeval=None): if not timeval: self.update_timeval() timeval = self.timeval try: event_code = self.type_codes[event_type] except KeyError: raise UnknownEventType( "We don't know what kind of event a %s is." % event_type) event = struct.pack(EVENT_FORMAT, timeval[0], timeval[1], event_code, code, value) return event
module function_definition identifier parameters identifier identifier identifier identifier default_parameter identifier none block if_statement not_operator identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier attribute identifier identifier try_statement block expression_statement assignment identifier subscript attribute identifier identifier identifier except_clause identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier subscript identifier integer subscript identifier integer identifier identifier identifier return_statement identifier
Create an evdev style structure.
def _update_config(self,directory,filename): basefilename=os.path.splitext(filename)[0] ext=os.path.splitext(filename)[1].lower() if filename==LOCATION_FILE: print("%s - Updating geotag information"%(LOCATION_FILE)) return self._update_config_location(directory) elif filename==TAG_FILE: print("%s - Updating tags"%(TAG_FILE)) return self._update_config_tags(directory) elif filename==SET_FILE: print("%s - Updating sets"%(SET_FILE)) return self._update_config_sets(directory) elif filename==MEGAPIXEL_FILE: print("%s - Updating photo size"%(MEGAPIXEL_FILE)) return self._upload_media(directory,resize_request=True) elif ext in self.FLICKR_META_EXTENSIONS: return self._update_meta(directory,basefilename) return False
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier subscript call attribute attribute identifier identifier identifier argument_list identifier integer expression_statement assignment identifier call attribute subscript call attribute attribute identifier identifier identifier argument_list identifier integer identifier argument_list if_statement comparison_operator identifier identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end parenthesized_expression identifier return_statement call attribute identifier identifier argument_list identifier elif_clause comparison_operator identifier identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end parenthesized_expression identifier return_statement call attribute identifier identifier argument_list identifier elif_clause comparison_operator identifier identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end parenthesized_expression identifier return_statement call attribute identifier identifier argument_list identifier elif_clause comparison_operator identifier identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end parenthesized_expression identifier return_statement call attribute identifier identifier argument_list identifier keyword_argument identifier true elif_clause comparison_operator identifier attribute identifier identifier block return_statement call attribute identifier identifier argument_list identifier identifier return_statement false
Manages FLICKR config files
def anchor_stream(self, stream_id, converter="rtc"): if isinstance(converter, str): converter = self._known_converters.get(converter) if converter is None: raise ArgumentError("Unknown anchor converter string: %s" % converter, known_converters=list(self._known_converters)) self._anchor_streams[stream_id] = converter
module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content string_end block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier if_statement comparison_operator identifier none block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier keyword_argument identifier call identifier argument_list attribute identifier identifier expression_statement assignment subscript attribute identifier identifier identifier identifier
Mark a stream as containing anchor points.
def merge_modified_section_data(self): for section in self.sections: section_data_start = adjust_FileAlignment( section.PointerToRawData, self.OPTIONAL_HEADER.FileAlignment ) section_data_end = section_data_start+section.SizeOfRawData if section_data_start < len(self.__data__) and section_data_end < len(self.__data__): self.__data__ = self.__data__[:section_data_start] + section.get_data() + self.__data__[section_data_end:]
module function_definition identifier parameters identifier block for_statement identifier attribute identifier identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier attribute attribute identifier identifier identifier expression_statement assignment identifier binary_operator identifier attribute identifier identifier if_statement boolean_operator comparison_operator identifier call identifier argument_list attribute identifier identifier comparison_operator identifier call identifier argument_list attribute identifier identifier block expression_statement assignment attribute identifier identifier binary_operator binary_operator subscript attribute identifier identifier slice identifier call attribute identifier identifier argument_list subscript attribute identifier identifier slice identifier
Update the PE image content with any individual section data that has been modified.
def discovery(self, discovery_address: Address) -> Discovery: if not is_binary_address(discovery_address): raise ValueError('discovery_address must be a valid address') with self._discovery_creation_lock: if discovery_address not in self.address_to_discovery: self.address_to_discovery[discovery_address] = Discovery( jsonrpc_client=self.client, discovery_address=discovery_address, contract_manager=self.contract_manager, ) return self.address_to_discovery[discovery_address]
module function_definition identifier parameters identifier typed_parameter identifier type identifier type identifier block if_statement not_operator call identifier argument_list identifier block raise_statement call identifier argument_list string string_start string_content string_end with_statement with_clause with_item attribute identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment subscript attribute identifier identifier identifier call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier return_statement subscript attribute identifier identifier identifier
Return a proxy to interact with the discovery.
def unicode_to_string(self): for tag in self.tags: self.ununicode.append(str(tag))
module function_definition identifier parameters identifier block for_statement identifier attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call identifier argument_list identifier
Convert unicode in string
def dump(self, stream): if self.prettyprint: self.indent(self.xml) document = etree.ElementTree(self.xml) header = '<?xml version="1.0" encoding="%s"?>' % self.encoding stream.write(header.encode(self.encoding)) document.write(stream, encoding=self.encoding)
module function_definition identifier parameters identifier identifier block if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier binary_operator string string_start string_content string_end attribute identifier identifier expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier attribute identifier identifier
Dumps the data to stream after appending header.
def risk_evidence(self, domain, **kwargs): return self._results('risk-evidence', '/v1/risk/evidence/', items_path=('components', ), domain=domain, **kwargs)
module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block return_statement call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end keyword_argument identifier tuple string string_start string_content string_end keyword_argument identifier identifier dictionary_splat identifier
Returns back the detailed risk evidence associated with a given domain
def create_indices(catalog_slug): mapping = { "mappings": { "layer": { "properties": { "layer_geoshape": { "type": "geo_shape", "tree": "quadtree", "precision": REGISTRY_MAPPING_PRECISION } } } } } ESHypermap.es.indices.create(catalog_slug, ignore=[400, 404], body=mapping)
module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end dictionary pair string string_start string_content string_end dictionary pair string string_start string_content string_end dictionary pair string string_start string_content string_end dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end identifier expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list identifier keyword_argument identifier list integer integer keyword_argument identifier identifier
Create ES core indices
def normalise_reads(self): logging.info('Normalising reads to a kmer depth of 100') for sample in self.metadata: sample.general.normalisedreads = [fastq.split('.fastq.gz')[0] + '_normalised.fastq.gz' for fastq in sorted(sample.general.fastqfiles)] try: out, err, cmd = bbtools.bbnorm(forward_in=sorted(sample.general.trimmedcorrectedfastqfiles)[0], forward_out=sample.general.normalisedreads[0], returncmd=True, threads=self.cpus) sample[self.analysistype].normalisecmd = cmd write_to_logfile(out, err, self.logfile, sample.general.logout, sample.general.logerr, None, None) except CalledProcessError: sample.general.normalisedreads = sample.general.trimmedfastqfiles except IndexError: sample.general.normalisedreads = list()
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end for_statement identifier attribute identifier identifier block expression_statement assignment attribute attribute identifier identifier identifier list_comprehension binary_operator subscript call attribute identifier identifier argument_list string string_start string_content string_end integer string string_start string_content string_end for_in_clause identifier call identifier argument_list attribute attribute identifier identifier identifier try_statement block expression_statement assignment pattern_list identifier identifier identifier call attribute identifier identifier argument_list keyword_argument identifier subscript call identifier argument_list attribute attribute identifier identifier identifier integer keyword_argument identifier subscript attribute attribute identifier identifier identifier integer keyword_argument identifier true keyword_argument identifier attribute identifier identifier expression_statement assignment attribute subscript identifier attribute identifier identifier identifier identifier expression_statement call identifier argument_list identifier identifier attribute identifier identifier attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier none none except_clause identifier block expression_statement assignment attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier except_clause identifier block expression_statement assignment attribute attribute identifier identifier identifier call identifier argument_list
Use bbnorm from the bbmap suite of tools to perform read normalisation
def translate(self, exc): from boto.exception import StorageResponseError if isinstance(exc, StorageResponseError): if exc.status == 404: return self.error_cls(str(exc)) return None
module function_definition identifier parameters identifier identifier block import_from_statement dotted_name identifier identifier dotted_name identifier if_statement call identifier argument_list identifier identifier block if_statement comparison_operator attribute identifier identifier integer block return_statement call attribute identifier identifier argument_list call identifier argument_list identifier return_statement none
Return whether or not to do translation.
def returns_super_model(func): def to_super_model(obj): from senaite.core.supermodel import SuperModel if isinstance(obj, SuperModel): return obj if not api.is_object(obj): raise TypeError("Expected a portal object, got '{}'" .format(type(obj))) uid = api.get_uid(obj) portal_type = api.get_portal_type(obj) adapter = queryAdapter(uid, ISuperModel, name=portal_type) if adapter is None: return SuperModel(uid) return adapter @wraps(func) def wrapper(*args, **kwargs): obj = func(*args, **kwargs) if isinstance(obj, (list, tuple)): return map(to_super_model, obj) return to_super_model(obj) return wrapper
module function_definition identifier parameters identifier block function_definition identifier parameters identifier block import_from_statement dotted_name identifier identifier identifier dotted_name identifier if_statement call identifier argument_list identifier identifier block return_statement identifier if_statement not_operator call attribute identifier identifier argument_list identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier identifier keyword_argument identifier identifier if_statement comparison_operator identifier none block return_statement call identifier argument_list identifier return_statement identifier decorated_definition decorator call identifier argument_list identifier 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 if_statement call identifier argument_list identifier tuple identifier identifier block return_statement call identifier argument_list identifier identifier return_statement call identifier argument_list identifier return_statement identifier
Decorator to return standard content objects as SuperModels
def xml(self, indent = ""): if not indent: xml = '<?xml version="1.0" encoding="UTF-8"?>\n' else: xml = "" xml += indent + "<CLAMMetaData format=\"" + self.__class__.__name__ + "\"" if self.mimetype: xml += " mimetype=\""+self.mimetype+"\"" if self.schema: xml += " schema=\""+self.schema+"\"" if self.inputtemplate: xml += " inputtemplate=\""+self.inputtemplate+"\"" xml += ">\n" for key, value in self.data.items(): xml += indent + " <meta id=\""+clam.common.util.xmlescape(key)+"\">"+clam.common.util.xmlescape(str(value))+"</meta>\n" if self.provenance: xml += self.provenance.xml(indent + " ") xml += indent + "</CLAMMetaData>" return xml
module function_definition identifier parameters identifier default_parameter identifier string string_start string_end block if_statement not_operator identifier block expression_statement assignment identifier string string_start string_content escape_sequence string_end else_clause block expression_statement assignment identifier string string_start string_end expression_statement augmented_assignment identifier binary_operator binary_operator binary_operator identifier string string_start string_content escape_sequence string_end attribute attribute identifier identifier identifier string string_start string_content escape_sequence string_end if_statement attribute identifier identifier block expression_statement augmented_assignment identifier binary_operator binary_operator string string_start string_content escape_sequence string_end attribute identifier identifier string string_start string_content escape_sequence string_end if_statement attribute identifier identifier block expression_statement augmented_assignment identifier binary_operator binary_operator string string_start string_content escape_sequence string_end attribute identifier identifier string string_start string_content escape_sequence string_end if_statement attribute identifier identifier block expression_statement augmented_assignment identifier binary_operator binary_operator string string_start string_content escape_sequence string_end attribute identifier identifier string string_start string_content escape_sequence string_end expression_statement augmented_assignment identifier string string_start string_content escape_sequence string_end for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list block expression_statement augmented_assignment identifier binary_operator binary_operator binary_operator binary_operator binary_operator identifier string string_start string_content escape_sequence string_end call attribute attribute attribute identifier identifier identifier identifier argument_list identifier string string_start string_content escape_sequence string_end call attribute attribute attribute identifier identifier identifier identifier argument_list call identifier argument_list identifier string string_start string_content escape_sequence string_end if_statement attribute identifier identifier block expression_statement augmented_assignment identifier call attribute attribute identifier identifier identifier argument_list binary_operator identifier string string_start string_content string_end expression_statement augmented_assignment identifier binary_operator identifier string string_start string_content string_end return_statement identifier
Render an XML representation of the metadata
def add_config_opts_to_parser(parser): parser.add_argument("--config-files", type=str, nargs="+", required=True, help="A file parsable by " "pycbc.workflow.WorkflowConfigParser.") parser.add_argument("--config-overrides", type=str, nargs="+", default=None, metavar="SECTION:OPTION:VALUE", help="List of section:option:value combinations " "to add into the configuration file.")
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier true keyword_argument identifier concatenated_string string string_start string_content string_end string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier none keyword_argument identifier string string_start string_content string_end keyword_argument identifier concatenated_string string string_start string_content string_end string string_start string_content string_end
Adds options for configuration files to the given parser.
def deleteSettings(self, groupName=None): groupName = groupName if groupName else self.settingsGroupName settings = QtCore.QSettings() logger.info("Deleting {} from: {}".format(groupName, settings.fileName())) removeSettingsGroup(groupName)
module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier conditional_expression identifier identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier call attribute identifier identifier argument_list expression_statement call identifier argument_list identifier
Deletes registry items from the persistent store.
def _format_changes(changes, orchestration=False): if not changes: return False, '' if orchestration: return True, _nested_changes(changes) if not isinstance(changes, dict): return True, 'Invalid Changes data: {0}'.format(changes) ret = changes.get('ret') if ret is not None and changes.get('out') == 'highstate': ctext = '' changed = False for host, hostdata in six.iteritems(ret): s, c = _format_host(host, hostdata) ctext += '\n' + '\n'.join((' ' * 14 + l) for l in s.splitlines()) changed = changed or c else: changed = True ctext = _nested_changes(changes) return changed, ctext
module function_definition identifier parameters identifier default_parameter identifier false block if_statement not_operator identifier block return_statement expression_list false string string_start string_end if_statement identifier block return_statement expression_list true call identifier argument_list identifier if_statement not_operator call identifier argument_list identifier identifier block return_statement expression_list true call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement boolean_operator comparison_operator identifier none comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier string string_start string_end expression_statement assignment identifier false for_statement pattern_list identifier identifier call attribute identifier identifier argument_list identifier block expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier identifier expression_statement augmented_assignment identifier binary_operator string string_start string_content escape_sequence string_end call attribute string string_start string_content escape_sequence string_end identifier generator_expression parenthesized_expression binary_operator binary_operator string string_start string_content string_end integer identifier for_in_clause identifier call attribute identifier identifier argument_list expression_statement assignment identifier boolean_operator identifier identifier else_clause block expression_statement assignment identifier true expression_statement assignment identifier call identifier argument_list identifier return_statement expression_list identifier identifier
Format the changes dict based on what the data is
def setup_ci(): gcloud_path = shell.run('which gcloud', capture=True).stdout.strip() sdk_path = normpath(join(gcloud_path, '../../platform/google_appengine')) gcloud_cmd = gcloud_path + ' --quiet' if not exists(sdk_path): log.info("Installing AppEngine SDK") shell.run('sudo {} components install app-engine-python'.format( gcloud_cmd )) else: log.info("AppEngine SDK already initialised") log.info("Using service account authentication") shell.run('{} auth activate-service-account --key-file {}'.format( gcloud_cmd, conf.proj_path('ops/client_secret.json') ))
module function_definition identifier parameters block expression_statement assignment identifier call attribute attribute call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier true identifier identifier argument_list expression_statement assignment identifier call identifier argument_list call identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier binary_operator identifier string string_start string_content string_end if_statement not_operator call identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier else_clause block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier call attribute identifier identifier argument_list string string_start string_content string_end
Setup AppEngine SDK on CircleCI
def load(self, f, line=None): if line is None: line = f.readlin() words = line[1:].split() self.__name = words[0].upper() self.section_parameters = " ".join(words[1:]) try: self.load_children(f) except EOFError: raise FileFormatError("Unexpected end of file, section '%s' not ended." % self.__name)
module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute subscript identifier slice integer identifier argument_list expression_statement assignment attribute identifier identifier call attribute subscript identifier integer identifier argument_list expression_statement assignment attribute identifier identifier call attribute string string_start string_content string_end identifier argument_list subscript identifier slice integer try_statement block expression_statement call attribute identifier identifier argument_list identifier except_clause identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier
Load this section from a file-like object
def validate_api_headers(param, value): if not value: return None headers = {} for kv in value.split(","): try: k, v = kv.split("=", 1) k = k.strip() for bad_header in BAD_API_HEADERS: if bad_header == k: raise click.BadParameter( "%(key)s is not an allowed header" % {"key": bad_header}, param=param, ) if k in API_HEADER_TRANSFORMS: transform_func = API_HEADER_TRANSFORMS[k] v = transform_func(param, v) except ValueError: raise click.BadParameter( "Values need to be a CSV of key=value pairs", param=param ) headers[k] = v return headers
module function_definition identifier parameters identifier identifier block if_statement not_operator identifier block return_statement none expression_statement assignment identifier dictionary for_statement identifier call attribute identifier identifier argument_list string string_start string_content string_end block try_statement 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 identifier identifier argument_list for_statement identifier identifier block if_statement comparison_operator identifier identifier block raise_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end dictionary pair string string_start string_content string_end identifier keyword_argument identifier identifier if_statement comparison_operator identifier identifier block expression_statement assignment identifier subscript identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier except_clause identifier block raise_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier expression_statement assignment subscript identifier identifier identifier return_statement identifier
Validate that API headers is a CSV of k=v pairs.
def _init_file(self): self.keyring_key = self._get_new_password() self.set_password('keyring-setting', 'password reference', 'password reference value') self._write_config_value('keyring-setting', 'scheme', self.scheme) self._write_config_value('keyring-setting', 'version', self.version)
module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end attribute identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end attribute identifier identifier
Initialize a new password file and set the reference password.
def FromTextFormat(cls, text): tmp = cls.protobuf() text_format.Merge(text, tmp) return cls.FromSerializedString(tmp.SerializeToString())
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier identifier return_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list
Parse this object from a text representation.
def headloss_manifold(FlowRate, Diam, Length, KMinor, Nu, PipeRough, NumOutlets): ut.check_range([NumOutlets, ">0, int", 'Number of outlets']) return (headloss(FlowRate, Diam, Length, Nu, PipeRough, KMinor).magnitude * ((1/3 ) + (1 / (2*NumOutlets)) + (1 / (6*NumOutlets**2)) ) )
module function_definition identifier parameters identifier identifier identifier identifier identifier identifier identifier block expression_statement call attribute identifier identifier argument_list list identifier string string_start string_content string_end string string_start string_content string_end return_statement parenthesized_expression binary_operator attribute call identifier argument_list identifier identifier identifier identifier identifier identifier identifier parenthesized_expression binary_operator binary_operator parenthesized_expression binary_operator integer integer parenthesized_expression binary_operator integer parenthesized_expression binary_operator integer identifier parenthesized_expression binary_operator integer parenthesized_expression binary_operator integer binary_operator identifier integer
Return the total head loss through the manifold.
def BROKER_TYPE(self): broker_type = get('BROKER_TYPE', DEFAULT_BROKER_TYPE) if broker_type not in SUPPORTED_BROKER_TYPES: log.warn("Specified BROKER_TYPE {} not supported. Backing to default {}".format( broker_type, DEFAULT_BROKER_TYPE)) return DEFAULT_BROKER_TYPE else: return broker_type
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list string string_start string_content string_end identifier if_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier return_statement identifier else_clause block return_statement identifier
Custom setting allowing switch between rabbitmq, redis
def _force(self,obj,objtype=None): gen=super(Dynamic,self).__get__(obj,objtype) if hasattr(gen,'_Dynamic_last'): return self._produce_value(gen,force=True) else: return gen
module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment identifier call attribute call identifier argument_list identifier identifier identifier argument_list identifier identifier if_statement call identifier argument_list identifier string string_start string_content string_end block return_statement call attribute identifier identifier argument_list identifier keyword_argument identifier true else_clause block return_statement identifier
Force a new value to be generated, and return it.
def addContinuousSet(self, continuousSet): id_ = continuousSet.getId() self._continuousSetIdMap[id_] = continuousSet self._continuousSetIds.append(id_) name = continuousSet.getLocalId() self._continuousSetNameMap[name] = continuousSet
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment subscript attribute identifier identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment subscript attribute identifier identifier identifier identifier
Adds the specified continuousSet to this dataset.
def _extract_url_and_title(self, text, start): idx = self._whitespace.match(text, start + 1).end() if idx == len(text): return None, None end_idx = idx has_anglebrackets = text[idx] == "<" if has_anglebrackets: end_idx = self._find_balanced(text, end_idx+1, "<", ">") end_idx = self._find_balanced(text, end_idx, "(", ")") match = self._inline_link_title.search(text, idx, end_idx) if not match: return None, None url = text[idx:match.start()] if has_anglebrackets: url = self._strip_anglebrackets.sub(r'\1', url) return url, end_idx
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list identifier binary_operator identifier integer identifier argument_list if_statement comparison_operator identifier call identifier argument_list identifier block return_statement expression_list none none expression_statement assignment identifier identifier expression_statement assignment identifier comparison_operator subscript identifier identifier string string_start string_content string_end if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier binary_operator identifier integer string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier identifier if_statement not_operator identifier block return_statement expression_list none none expression_statement assignment identifier subscript identifier slice identifier call attribute identifier identifier argument_list if_statement identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier return_statement expression_list identifier identifier
Extracts the url from the tail of a link.
def imageurl(self): if self._imageurl is None: self._imageurl = 'http://www.chemspider.com/ImagesHandler.ashx?id=%s' % self.csid return self._imageurl
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier binary_operator string string_start string_content string_end attribute identifier identifier return_statement attribute identifier identifier
Return the URL of a png image of the 2D structure
def nth(self, n, *args, **kwargs): self._prep_pandas_groupby() myargs = self._myargs mykwargs = self._mykwargs nthRDD = self._regroup_mergedRDD().mapValues( lambda r: r.nth( n, *args, **kwargs)).values() return DataFrame.fromDataFrameRDD(nthRDD, self.sql_ctx)
module function_definition identifier parameters identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call attribute call attribute call attribute identifier identifier argument_list identifier argument_list lambda lambda_parameters identifier call attribute identifier identifier argument_list identifier list_splat identifier dictionary_splat identifier identifier argument_list return_statement call attribute identifier identifier argument_list identifier attribute identifier identifier
Take the nth element of each grouby.
def format_hexadecimal_field(spec, prec, number, locale): if number < 0: number &= (1 << (8 * int(math.log(-number, 1 << 8) + 1))) - 1 format_ = u'0%d%s' % (int(prec or 0), spec) return format(number, format_)
module function_definition identifier parameters identifier identifier identifier identifier block if_statement comparison_operator identifier integer block expression_statement augmented_assignment identifier binary_operator parenthesized_expression binary_operator integer parenthesized_expression binary_operator integer call identifier argument_list binary_operator call attribute identifier identifier argument_list unary_operator identifier binary_operator integer integer integer integer expression_statement assignment identifier binary_operator string string_start string_content string_end tuple call identifier argument_list boolean_operator identifier integer identifier return_statement call identifier argument_list identifier identifier
Formats a hexadeciaml field.
def cmd_print(self): if not self._valid_lines: return '' return '\n'.join([line.raw_line for line in self._valid_lines]) + '\n'
module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block return_statement string string_start string_end return_statement binary_operator call attribute string string_start string_content escape_sequence string_end identifier argument_list list_comprehension attribute identifier identifier for_in_clause identifier attribute identifier identifier string string_start string_content escape_sequence string_end
Returns the raw lines to be printed.
def tag_namespace(cls, tag): md = re.match("^(?:\{([^\}]*)\})", tag) if md is not None: return md.group(1)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier if_statement comparison_operator identifier none block return_statement call attribute identifier identifier argument_list integer
return the namespace for a given tag, or '' if no namespace given
def check(self, final_line_count): if self._lines_seen["version"]: self._process_version_lines() self._process_plan_lines(final_line_count)
module function_definition identifier parameters identifier identifier block if_statement subscript attribute identifier identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier
Check the status of all provided data and update the suite.
def stop_experiment(args): experiment_id_list = parse_ids(args) if experiment_id_list: experiment_config = Experiments() experiment_dict = experiment_config.get_all_experiments() for experiment_id in experiment_id_list: print_normal('Stoping experiment %s' % experiment_id) nni_config = Config(experiment_dict[experiment_id]['fileName']) rest_port = nni_config.get_config('restServerPort') rest_pid = nni_config.get_config('restServerPid') if rest_pid: kill_command(rest_pid) tensorboard_pid_list = nni_config.get_config('tensorboardPidList') if tensorboard_pid_list: for tensorboard_pid in tensorboard_pid_list: try: kill_command(tensorboard_pid) except Exception as exception: print_error(exception) nni_config.set_config('tensorboardPidList', []) print_normal('Stop experiment success!') experiment_config.update_experiment(experiment_id, 'status', 'STOPPED') time_now = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) experiment_config.update_experiment(experiment_id, 'endTime', str(time_now))
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list for_statement identifier identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement assignment identifier call identifier argument_list subscript subscript identifier identifier string string_start string_content string_end 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_list string string_start string_content string_end if_statement identifier block expression_statement call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement identifier block for_statement identifier identifier block try_statement block expression_statement call identifier argument_list identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end list expression_statement call identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end call identifier argument_list identifier
Stop the experiment which is running
def _manageTags(tagList, guids, add=True): objects = getObjectsFromGuids(guids) tags = [] for tag in tagList: try: t = Tag.objects.get(pk=int(tag)) except ValueError: t = Tag.objects.get_or_create(name=tag.lower())[0] tags.append(t) if add: return _addTags(tags, objects) else: return _removeTags(tags, objects)
module function_definition identifier parameters identifier identifier default_parameter identifier true block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier list for_statement identifier identifier block try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier call identifier argument_list identifier except_clause identifier block expression_statement assignment identifier subscript call attribute attribute identifier identifier identifier argument_list keyword_argument identifier call attribute identifier identifier argument_list integer expression_statement call attribute identifier identifier argument_list identifier if_statement identifier block return_statement call identifier argument_list identifier identifier else_clause block return_statement call identifier argument_list identifier identifier
Adds or Removes Guids from Tags
def _delete_collection(self, **kwargs): error_message = "The request must include \"requests_params\": {\"params\": \"options=<glob pattern>\"} as kwarg" try: if kwargs['requests_params']['params'].split('=')[0] != 'options': raise MissingRequiredRequestsParameter(error_message) except KeyError: raise requests_params = self._handle_requests_params(kwargs) delete_uri = self._meta_data['uri'] session = self._meta_data['bigip']._meta_data['icr_session'] session.delete(delete_uri, **requests_params)
module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier string string_start string_content escape_sequence escape_sequence escape_sequence escape_sequence escape_sequence escape_sequence string_end try_statement block if_statement comparison_operator subscript call attribute subscript subscript identifier string string_start string_content string_end string string_start string_content string_end identifier argument_list string string_start string_content string_end integer string string_start string_content string_end block raise_statement call identifier argument_list identifier except_clause identifier block raise_statement expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier subscript attribute subscript attribute identifier identifier string string_start string_content string_end identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier dictionary_splat identifier
wrapped with delete_collection, override that in a sublcass to customize
async def genTempCoreProxy(mods=None): with s_common.getTempDir() as dirn: async with await s_cortex.Cortex.anit(dirn) as core: if mods: for mod in mods: await core.loadCoreModule(mod) async with core.getLocalProxy() as prox: object.__setattr__(prox, '_core', core) yield prox
module function_definition identifier parameters default_parameter identifier none block with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list as_pattern_target identifier block with_statement with_clause with_item as_pattern await call attribute attribute identifier identifier identifier argument_list identifier as_pattern_target identifier block if_statement identifier block for_statement identifier identifier block expression_statement await call attribute identifier identifier argument_list identifier with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end identifier expression_statement yield identifier
Get a temporary cortex proxy.
def including(self, sequence) -> Generator: return (element for element in sequence if self.indexer(element) in self.predicates)
module function_definition identifier parameters identifier identifier type identifier block return_statement generator_expression identifier for_in_clause identifier identifier if_clause comparison_operator call attribute identifier identifier argument_list identifier attribute identifier identifier
Include the sequence elements matching the filter set.
def _rand_cpu_str(cpu): cpu = int(cpu) avail = __salt__['status.nproc']() if cpu < avail: return '0-{0}'.format(avail) to_set = set() while len(to_set) < cpu: choice = random.randint(0, avail - 1) if choice not in to_set: to_set.add(six.text_type(choice)) return ','.join(sorted(to_set))
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call subscript identifier string string_start string_content string_end argument_list if_statement comparison_operator identifier identifier block return_statement call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier call identifier argument_list while_statement comparison_operator call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list integer binary_operator identifier integer if_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier return_statement call attribute string string_start string_content string_end identifier argument_list call identifier argument_list identifier
Return a random subset of cpus for the cpuset config
def delete_pb_devices(): parser = argparse.ArgumentParser(description='Register PB devices.') parser.add_argument('num_pb', type=int, help='Number of PBs devices to register.') args = parser.parse_args() log = logging.getLogger('sip.tango_control.subarray') tango_db = Database() log.info("Deleting PB devices:") for index in range(args.num_pb): name = 'sip_sdp/pb/{:05d}'.format(index) log.info("\t%s", name) tango_db.delete_device(name)
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 string_content string_end keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier 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 string string_start string_content string_end for_statement identifier call identifier argument_list attribute identifier identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end identifier expression_statement call attribute identifier identifier argument_list identifier
Delete PBs devices from the Tango database.
def do_remove(config, config_dir): if not os.path.exists(config_dir): print "Configuration '{}' does not exist.".format(config) exit(1) if confirm("Confirm removal of the configuration '{}'".format(config)): shutil.rmtree(config_dir) print "Configuration '{}' has been removed.".format(config) else: print "Removal cancelled."
module function_definition identifier parameters identifier identifier block if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block print_statement call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call identifier argument_list integer if_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier print_statement call attribute string string_start string_content string_end identifier argument_list identifier else_clause block print_statement string string_start string_content string_end
CLI action "remove configuration".
def _can_send_eth(irs): for ir in irs: if isinstance(ir, (HighLevelCall, LowLevelCall, Transfer, Send)): if ir.call_value: return True return False
module function_definition identifier parameters identifier block for_statement identifier identifier block if_statement call identifier argument_list identifier tuple identifier identifier identifier identifier block if_statement attribute identifier identifier block return_statement true return_statement false
Detect if the node can send eth
def str_rate(self): if not self._eta.started or self._eta.stalled or not self.rate: return '--- KiB/s' unit_rate, unit = UnitByte(self.rate).auto_no_thousands if unit_rate >= 10: formatter = '%d' else: formatter = '%0.1f' return '{0} {1}/s'.format(locale.format(formatter, unit_rate, grouping=False), unit)
module function_definition identifier parameters identifier block if_statement boolean_operator boolean_operator not_operator attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier not_operator attribute identifier identifier block return_statement string string_start string_content string_end expression_statement assignment pattern_list identifier identifier attribute call identifier argument_list attribute identifier identifier identifier if_statement comparison_operator identifier integer block expression_statement assignment identifier string string_start string_content string_end else_clause block expression_statement assignment identifier string string_start string_content string_end return_statement call attribute string string_start string_content string_end identifier argument_list call attribute identifier identifier argument_list identifier identifier keyword_argument identifier false identifier
Returns the rate with formatting.
def _organize_by_position(orig_file, cmp_file, chunk_size): with open(orig_file) as in_handle: reader1 = csv.reader(in_handle) positions = len(next(reader1)) - 1 for positions in _chunks(range(positions), chunk_size): with open(orig_file) as orig_handle: with open(cmp_file) as cmp_handle: orig_reader = csv.reader(orig_handle) cmp_reader = csv.reader(cmp_handle) for item in _counts_at_position(positions, orig_reader, cmp_reader): yield item
module function_definition identifier parameters identifier identifier identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier binary_operator call identifier argument_list call identifier argument_list identifier integer for_statement identifier call identifier argument_list call identifier argument_list identifier identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier as_pattern_target identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier for_statement identifier call identifier argument_list identifier identifier identifier block expression_statement yield identifier
Read two CSV files of qualities, organizing values by position.
def LE32(value, min_value=None, max_value=None, fuzzable=True, name=None, full_range=False): return UInt32(value, min_value=min_value, max_value=max_value, encoder=ENC_INT_LE, fuzzable=fuzzable, name=name, full_range=full_range)
module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none default_parameter identifier true default_parameter identifier none default_parameter identifier false block return_statement call identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier
32-bit field, Little endian encoded
def active(self) -> bool: states = self._client.get_state(self._state_url)['states'] for state in states: state = state['State'] if int(state['Id']) == self._state_id: return state['IsActive'] == "1" return False
module function_definition identifier parameters identifier type identifier block expression_statement assignment identifier subscript call attribute attribute identifier identifier identifier argument_list attribute identifier identifier string string_start string_content string_end for_statement identifier identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end if_statement comparison_operator call identifier argument_list subscript identifier string string_start string_content string_end attribute identifier identifier block return_statement comparison_operator subscript identifier string string_start string_content string_end string string_start string_content string_end return_statement false
Indicate if this RunState is currently active.
def Process(self, request, context): LOG.debug("Process called") try: metrics = self.plugin.process( [Metric(pb=m) for m in request.Metrics], ConfigMap(pb=request.Config) ) return MetricsReply(metrics=[m.pb for m in metrics]) except Exception as err: msg = "message: {}\n\nstack trace: {}".format( err, traceback.format_exc()) return MetricsReply(metrics=[], error=msg)
module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list list_comprehension call identifier argument_list keyword_argument identifier identifier for_in_clause identifier attribute identifier identifier call identifier argument_list keyword_argument identifier attribute identifier identifier return_statement call identifier argument_list keyword_argument identifier list_comprehension attribute identifier identifier for_in_clause identifier identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement assignment identifier call attribute string string_start string_content escape_sequence escape_sequence string_end identifier argument_list identifier call attribute identifier identifier argument_list return_statement call identifier argument_list keyword_argument identifier list keyword_argument identifier identifier
Dispatches the request to the plugins process method
def cache(self): if self._cache is None: self._cache = django_cache.get_cache(self.cache_name) return self._cache
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 attribute identifier identifier return_statement attribute identifier identifier
Memoize access to the cache backend.
def _viewbox_unset(self, viewbox): self._viewbox = None viewbox.events.mouse_press.disconnect(self.viewbox_mouse_event) viewbox.events.mouse_release.disconnect(self.viewbox_mouse_event) viewbox.events.mouse_move.disconnect(self.viewbox_mouse_event) viewbox.events.mouse_wheel.disconnect(self.viewbox_mouse_event) viewbox.events.resize.disconnect(self.viewbox_resize_event)
module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier none expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list attribute identifier identifier expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list attribute identifier identifier expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list attribute identifier identifier expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list attribute identifier identifier expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list attribute identifier identifier
Friend method of viewbox to unregister itself.
def up(self, role, root_priority, root_times): self.port_priority = root_priority self.port_times = root_times state = (PORT_STATE_LISTEN if self.config_enable else PORT_STATE_DISABLE) self._change_role(role) self._change_status(state)
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment identifier parenthesized_expression conditional_expression identifier attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier
A port is started in the state of LISTEN.
def gen_sls_config_files(stage, region): names = [] for ext in ['yml', 'json']: names.append( os.path.join('env', "%s-%s.%s" % (stage, region, ext)) ) names.append("config-%s-%s.%s" % (stage, region, ext)) names.append( os.path.join('env', "%s.%s" % (stage, ext)) ) names.append("config-%s.%s" % (stage, ext)) return names
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list for_statement identifier list string string_start string_content string_end string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end binary_operator string string_start string_content string_end tuple identifier identifier identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier identifier expression_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end binary_operator string string_start string_content string_end tuple identifier identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier return_statement identifier
Generate possible SLS config files names.
def source(self, newsource): oldsource = self.source for feature in self: if feature.source == oldsource: feature._source = newsource
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute identifier identifier for_statement identifier identifier block if_statement comparison_operator attribute identifier identifier identifier block expression_statement assignment attribute identifier identifier identifier
When modifying source, also update children with matching source.
def advance(parser): prev_end = parser.token.end parser.prev_end = prev_end parser.token = parser.lexer.next_token(prev_end)
module function_definition identifier parameters identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list identifier
Moves the internal parser object to the next lexed token.
def shutdown(self): self.stop_balance.set() self.motor_left.stop() self.motor_right.stop() self.gyro_file.close() self.touch_file.close() self.encoder_left_file.close() self.encoder_right_file.close() self.dc_left_file.close() self.dc_right_file.close()
module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list
Close all file handles and stop all motors.
def tile(lt, width=70, gap=1): from jcvi.utils.iter import grouper max_len = max(len(x) for x in lt) + gap items_per_line = max(width // max_len, 1) lt = [x.rjust(max_len) for x in lt] g = list(grouper(lt, items_per_line, fillvalue="")) return "\n".join("".join(x) for x in g)
module function_definition identifier parameters identifier default_parameter identifier integer default_parameter identifier integer block import_from_statement dotted_name identifier identifier identifier dotted_name identifier expression_statement assignment identifier binary_operator call identifier generator_expression call identifier argument_list identifier for_in_clause identifier identifier identifier expression_statement assignment identifier call identifier argument_list binary_operator identifier identifier integer expression_statement assignment identifier list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier identifier expression_statement assignment identifier call identifier argument_list call identifier argument_list identifier identifier keyword_argument identifier string string_start string_end return_statement call attribute string string_start string_content escape_sequence string_end identifier generator_expression call attribute string string_start string_end identifier argument_list identifier for_in_clause identifier identifier
Pretty print list of items.
def wait(self): if self._go: return True with self.lock: if self._go: return True stopper = _allocate_lock() stopper.acquire() if not self.waiting_threads: self.waiting_threads = [stopper] else: self.waiting_threads.append(stopper) DEBUG and self._name and Log.note("wait for go {{name|quote}}", name=self.name) stopper.acquire() DEBUG and self._name and Log.note("GOing! {{name|quote}}", name=self.name) return True
module function_definition identifier parameters identifier block if_statement attribute identifier identifier block return_statement true with_statement with_clause with_item attribute identifier identifier block if_statement attribute identifier identifier block return_statement true expression_statement assignment identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list if_statement not_operator attribute identifier identifier block expression_statement assignment attribute identifier identifier list identifier else_clause block expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement boolean_operator boolean_operator identifier attribute identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list expression_statement boolean_operator boolean_operator identifier attribute identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier attribute identifier identifier return_statement true
PUT THREAD IN WAIT STATE UNTIL SIGNAL IS ACTIVATED
def _parse_section_links(self, id_tag): soup = BeautifulSoup(self.html, "html.parser") info = soup.find("span", {"id": id_tag}) all_links = list() if info is None: return all_links for node in soup.find(id=id_tag).parent.next_siblings: if not isinstance(node, Tag): continue elif node.get("role", "") == "navigation": continue elif "infobox" in node.get("class", []): continue is_headline = node.find("span", {"class": "mw-headline"}) if is_headline is not None: break elif node.name == "a": all_links.append(self.__parse_link_info(node)) else: for link in node.findAll("a"): all_links.append(self.__parse_link_info(link)) return all_links
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end dictionary pair string string_start string_content string_end identifier expression_statement assignment identifier call identifier argument_list if_statement comparison_operator identifier none block return_statement identifier for_statement identifier attribute attribute call attribute identifier identifier argument_list keyword_argument identifier identifier identifier identifier block if_statement not_operator call identifier argument_list identifier identifier block continue_statement elif_clause comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end string string_start string_content string_end block continue_statement elif_clause comparison_operator string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end list block continue_statement expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end dictionary pair string string_start string_content string_end string string_start string_content string_end if_statement comparison_operator identifier none block break_statement elif_clause comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier else_clause block for_statement identifier call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier return_statement identifier
given a section id, parse the links in the unordered list
def _loader(self, tags): class ConfigLoader(SafeLoader): pass ConfigLoader.add_multi_constructor("", lambda loader, prefix, node: TaggedValue(node.value, node.tag, *tags)) return ConfigLoader
module function_definition identifier parameters identifier identifier block class_definition identifier argument_list identifier block pass_statement expression_statement call attribute identifier identifier argument_list string string_start string_end lambda lambda_parameters identifier identifier identifier call identifier argument_list attribute identifier identifier attribute identifier identifier list_splat identifier return_statement identifier
Create a yaml Loader.
def create_delete_model(record): data = cloudwatch.get_historical_base_info(record) vpc_id = cloudwatch.filter_request_parameters('vpcId', record) arn = get_arn(vpc_id, cloudwatch.get_region(record), record['account']) LOG.debug(F'[-] Deleting Dynamodb Records. Hash Key: {arn}') data.update({ 'configuration': {} }) items = list(CurrentVPCModel.query(arn, limit=1)) if items: model_dict = items[0].__dict__['attribute_values'].copy() model_dict.update(data) model = CurrentVPCModel(**model_dict) model.save() return model return None
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier call identifier argument_list identifier call attribute identifier identifier argument_list identifier subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content interpolation identifier string_end expression_statement call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end dictionary expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list identifier keyword_argument identifier integer if_statement identifier block expression_statement assignment identifier call attribute subscript attribute subscript identifier integer identifier string string_start string_content string_end identifier argument_list expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list dictionary_splat identifier expression_statement call attribute identifier identifier argument_list return_statement identifier return_statement none
Create a vpc model from a record.
def process(self, metric): path = metric.getCollectorPath() path += '.' path += metric.getMetricPath() if self.config['apply_metric_prefix']: path = metric.getPathPrefix() + '.' + path if self.include_reg.match(path): if metric.metric_type == 'GAUGE': m_type = 'gauge' else: m_type = 'counter' self.queue.add(path, float(metric.value), type=m_type, source=metric.host, measure_time=metric.timestamp) self.current_n_measurements += 1 else: self.log.debug("LibratoHandler: Skip %s, no include_filters match", path) if (self.current_n_measurements >= self.queue_max_size or time.time() >= self.queue_max_timestamp): self.log.debug("LibratoHandler: Sending batch size: %d", self.current_n_measurements) self._send()
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement augmented_assignment identifier string string_start string_content string_end expression_statement augmented_assignment identifier call attribute identifier identifier argument_list if_statement subscript attribute identifier identifier string string_start string_content string_end block expression_statement assignment identifier binary_operator binary_operator call attribute identifier identifier argument_list string string_start string_content string_end identifier if_statement call attribute attribute identifier identifier identifier argument_list identifier block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement assignment identifier string string_start string_content string_end else_clause block expression_statement assignment identifier string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list identifier call identifier argument_list attribute identifier identifier keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier expression_statement augmented_assignment attribute identifier identifier integer else_clause block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier if_statement parenthesized_expression boolean_operator comparison_operator attribute identifier identifier attribute identifier identifier comparison_operator call attribute identifier identifier argument_list attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end attribute identifier identifier expression_statement call attribute identifier identifier argument_list
Process a metric by sending it to Librato
def _num_bytes_to_human_readable(num_bytes): if num_bytes < (2 ** 10): return "%d B" % num_bytes elif num_bytes < (2 ** 20): return "%.3f KB" % (float(num_bytes) / (2 ** 10)) elif num_bytes < (2 ** 30): return "%.3f MB" % (float(num_bytes) / (2 ** 20)) else: return "%.3f GB" % (float(num_bytes) / (2 ** 30))
module function_definition identifier parameters identifier block if_statement comparison_operator identifier parenthesized_expression binary_operator integer integer block return_statement binary_operator string string_start string_content string_end identifier elif_clause comparison_operator identifier parenthesized_expression binary_operator integer integer block return_statement binary_operator string string_start string_content string_end parenthesized_expression binary_operator call identifier argument_list identifier parenthesized_expression binary_operator integer integer elif_clause comparison_operator identifier parenthesized_expression binary_operator integer integer block return_statement binary_operator string string_start string_content string_end parenthesized_expression binary_operator call identifier argument_list identifier parenthesized_expression binary_operator integer integer else_clause block return_statement binary_operator string string_start string_content string_end parenthesized_expression binary_operator call identifier argument_list identifier parenthesized_expression binary_operator integer integer
Returns human readable string of how much memory `num_bytes` fills.
def _pipeline_output(self, pipeline, chunks, name): today = normalize_date(self.get_datetime()) try: data = self._pipeline_cache.get(name, today) except KeyError: data, valid_until = self.run_pipeline( pipeline, today, next(chunks), ) self._pipeline_cache.set(name, data, valid_until) try: return data.loc[today] except KeyError: return pd.DataFrame(index=[], columns=data.columns)
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier except_clause identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier identifier call identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier identifier try_statement block return_statement subscript attribute identifier identifier identifier except_clause identifier block return_statement call attribute identifier identifier argument_list keyword_argument identifier list keyword_argument identifier attribute identifier identifier
Internal implementation of `pipeline_output`.
def __connect(self): try: logger.debug("Socket connecting to %s:%s", self.host, self.port) self.sock.connect((self.host, self.port)) except socket.error as e: logger.exception("socket error %s", e) logger.error("Closing socket and recreating a new one.") self.sock.close() self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((self.host, self.port))
module function_definition identifier parameters identifier block try_statement block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list tuple attribute identifier identifier attribute identifier identifier except_clause as_pattern attribute identifier identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list tuple attribute identifier identifier attribute identifier identifier
A helper function to make connection.
def _info(message): span = values() _log.debug(message + ": {span} in trace {trace}. (Parent span: {parent}).".format( span=span.get(b3_span_id), trace=span.get(b3_trace_id), parent=span.get(b3_parent_span_id), ))
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list binary_operator identifier call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier call attribute identifier identifier argument_list identifier keyword_argument identifier call attribute identifier identifier argument_list identifier keyword_argument identifier call attribute identifier identifier argument_list identifier
Convenience function to log current span values.
def _init(self): self.tn = telnetlib.Telnet(self.ip, self.port) self.tn.read_until('User Name') self.tn.write('apc\r\n') self.tn.read_until('Password') self.tn.write('apc\r\n') self.until_done()
module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content escape_sequence escape_sequence string_end expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content escape_sequence escape_sequence string_end expression_statement call attribute identifier identifier argument_list
Initialize the telnet connection
def save(self, name, data, location='local', kind='json'): file_ext = '.json' if kind == 'json' else '.pkl' path = self._get_path(name, location, file_ext=file_ext) _ensure_dir_exists(op.dirname(path)) logger.debug("Save data to `%s`.", path) if kind == 'json': _save_json(path, data) else: _save_pickle(path, data)
module function_definition identifier parameters identifier identifier identifier default_parameter identifier string string_start string_content string_end default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier conditional_expression string string_start string_content string_end comparison_operator identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier keyword_argument identifier identifier expression_statement call identifier argument_list call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier if_statement comparison_operator identifier string string_start string_content string_end block expression_statement call identifier argument_list identifier identifier else_clause block expression_statement call identifier argument_list identifier identifier
Save a dictionary in a JSON file within the cache directory.
def iterator(self): for item in self.query.results(): obj = self.resource(**item) yield obj
module function_definition identifier parameters identifier block for_statement identifier call attribute attribute identifier identifier identifier argument_list block expression_statement assignment identifier call attribute identifier identifier argument_list dictionary_splat identifier expression_statement yield identifier
An iterator over the results from applying this QuerySet to the api.
def _load_track_estimates(track, estimates_dir, output_dir): user_results = {} track_estimate_dir = os.path.join( estimates_dir, track.subset, track.name ) for target in glob.glob( track_estimate_dir + '/*.wav' ): target_name = op.splitext( os.path.basename(target) )[0] try: target_audio, _ = sf.read( target, always_2d=True ) user_results[target_name] = target_audio except RuntimeError: pass if user_results: eval_mus_track( track, user_results, output_dir=output_dir ) return None
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier dictionary expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier attribute identifier identifier attribute identifier identifier for_statement identifier call attribute identifier identifier argument_list binary_operator identifier string string_start string_content string_end block expression_statement assignment identifier subscript call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier integer try_statement block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier keyword_argument identifier true expression_statement assignment subscript identifier identifier identifier except_clause identifier block pass_statement if_statement identifier block expression_statement call identifier argument_list identifier identifier keyword_argument identifier identifier return_statement none
load estimates from disk instead of processing
def unpack_ambiguous(s): sd = [ambiguous_dna_values[x] for x in s] return ["".join(x) for x in list(product(*sd))]
module function_definition identifier parameters identifier block expression_statement assignment identifier list_comprehension subscript identifier identifier for_in_clause identifier identifier return_statement list_comprehension call attribute string string_start string_end identifier argument_list identifier for_in_clause identifier call identifier argument_list call identifier argument_list list_splat identifier
List sequences with ambiguous characters in all possibilities.
def isInfinite(self): return self.x0 > self.x1 or self.y0 > self.y1
module function_definition identifier parameters identifier block return_statement boolean_operator comparison_operator attribute identifier identifier attribute identifier identifier comparison_operator attribute identifier identifier attribute identifier identifier
Check if rectangle is infinite.
def check_nsp(dist, attr, value): ns_packages = value assert_string_list(dist, attr, ns_packages) for nsp in ns_packages: if not dist.has_contents_for(nsp): raise DistutilsSetupError( "Distribution contains no modules or packages for " + "namespace package %r" % nsp ) parent, sep, child = nsp.rpartition('.') if parent and parent not in ns_packages: distutils.log.warn( "WARNING: %r is declared as a package namespace, but %r" " is not: please correct this in setup.py", nsp, parent )
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier identifier expression_statement call identifier argument_list identifier identifier identifier for_statement identifier identifier block if_statement not_operator call attribute identifier identifier argument_list identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end binary_operator string string_start string_content string_end identifier expression_statement assignment pattern_list identifier identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement boolean_operator identifier comparison_operator identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end identifier identifier
Verify that namespace packages are valid
def read_unicode(path, encoding, encoding_errors): try: f = open(path, 'rb') return make_unicode(f.read(), encoding, encoding_errors) finally: f.close()
module function_definition identifier parameters identifier identifier identifier block try_statement block expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end return_statement call identifier argument_list call attribute identifier identifier argument_list identifier identifier finally_clause block expression_statement call attribute identifier identifier argument_list
Return the contents of a file as a unicode string.
def looking_for_friends(self): self.info('I am looking for friends') available_friends = list(self.get_agents(drunk=False, pub=None, state_id=self.looking_for_friends.id)) if not available_friends: self.info('Life sucks and I\'m alone!') return self.at_home befriended = self.try_friends(available_friends) if befriended: return self.looking_for_pub
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list keyword_argument identifier false keyword_argument identifier none keyword_argument identifier attribute attribute identifier identifier identifier if_statement not_operator identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end return_statement attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement identifier block return_statement attribute identifier identifier
Look for friends to drink with
def happy_birthday(name: hug.types.text, age: hug.types.number, hug_timer=3): return {'message': 'Happy {0} Birthday {1}!'.format(age, name), 'took': float(hug_timer)}
module function_definition identifier parameters typed_parameter identifier type attribute attribute identifier identifier identifier typed_parameter identifier type attribute attribute identifier identifier identifier default_parameter identifier integer block return_statement dictionary pair string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list identifier identifier pair string string_start string_content string_end call identifier argument_list identifier
Says happy birthday to a user
def _init_dataframes(self): df = pd.read_sql_query("SELECT elapsed, epoch, scriptrun_time, custom_timers FROM result ORDER BY epoch ASC", db.get_conn()) self._get_all_timers(df) self.main_results = self._get_processed_dataframe(df) for key, value in six.iteritems(self._timers_values): df = pd.DataFrame(value, columns=['epoch', 'scriptrun_time']) df.index = pd.to_datetime(df['epoch'], unit='s') timer_results = self._get_processed_dataframe(df) self.timers_results[key] = timer_results del self._timers_values
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier for_statement pattern_list identifier identifier call attribute identifier identifier argument_list attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier list string string_start string_content string_end string string_start string_content string_end expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment subscript attribute identifier identifier identifier identifier delete_statement attribute identifier identifier
Initialise the main dataframe for the results and the custom timers dataframes
def who_has(self, subid): answer = [] for name in self.__map: if subid in self.__map[name] and not name in answer: answer.append(name) return answer
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list for_statement identifier attribute identifier identifier block if_statement boolean_operator comparison_operator identifier subscript attribute identifier identifier identifier not_operator comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list identifier return_statement identifier
Return a list of names who own subid in their id range set.
def results(self, key): if not results_backend: return json_error_response("Results backend isn't configured") read_from_results_backend_start = now_as_float() blob = results_backend.get(key) stats_logger.timing( 'sqllab.query.results_backend_read', now_as_float() - read_from_results_backend_start, ) if not blob: return json_error_response( 'Data could not be retrieved. ' 'You may want to re-run the query.', status=410, ) query = db.session.query(Query).filter_by(results_key=key).one() rejected_tables = security_manager.rejected_datasources( query.sql, query.database, query.schema) if rejected_tables: return json_error_response(security_manager.get_table_access_error_msg( '{}'.format(rejected_tables)), status=403) payload = utils.zlib_decompress_to_string(blob) display_limit = app.config.get('DEFAULT_SQLLAB_LIMIT', None) if display_limit: payload_json = json.loads(payload) payload_json['data'] = payload_json['data'][:display_limit] return json_success( json.dumps( payload_json, default=utils.json_iso_dttm_ser, ignore_nan=True, ), )
module function_definition identifier parameters identifier identifier block if_statement not_operator identifier block return_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end binary_operator call identifier argument_list identifier if_statement not_operator identifier block return_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end keyword_argument identifier integer expression_statement assignment identifier call attribute call attribute call attribute attribute identifier identifier identifier argument_list identifier identifier argument_list keyword_argument identifier identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier if_statement identifier block return_statement call identifier argument_list call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier keyword_argument identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end none if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment subscript identifier string string_start string_content string_end subscript subscript identifier string string_start string_content string_end slice identifier return_statement call identifier argument_list call attribute identifier identifier argument_list identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier true
Serves a key off of the results backend
def gotoPrevious(self): index = self._currentPanel.currentIndex() - 1 if index < 0: index = self._currentPanel.count() - 1 self._currentPanel.setCurrentIndex(index)
module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator call attribute attribute identifier identifier identifier argument_list integer if_statement comparison_operator identifier integer block expression_statement assignment identifier binary_operator call attribute attribute identifier identifier identifier argument_list integer expression_statement call attribute attribute identifier identifier identifier argument_list identifier
Goes to the previous panel tab.
def _merge_maps(m1, m2): return type(m1)(chain(m1.items(), m2.items()))
module function_definition identifier parameters identifier identifier block return_statement call call identifier argument_list identifier argument_list call identifier argument_list call attribute identifier identifier argument_list call attribute identifier identifier argument_list
merge two Mapping objects, keeping the type of the first mapping
def import_class(import_path): if not '.' in import_path: raise IncorrectImportPath( "Invalid Python-style import path provided: {0}.".format( import_path ) ) path_bits = import_path.split('.') mod_path = '.'.join(path_bits[:-1]) klass_name = path_bits[-1] try: mod = importlib.import_module(mod_path) except ImportError: raise IncorrectImportPath( "Could not import module '{0}'.".format(mod_path) ) try: klass = getattr(mod, klass_name) except AttributeError: raise IncorrectImportPath( "Imported module '{0}' but could not find class '{1}'.".format( mod_path, klass_name ) ) return klass
module function_definition identifier parameters identifier block if_statement not_operator comparison_operator string string_start string_content string_end identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list subscript identifier slice unary_operator integer expression_statement assignment identifier subscript identifier unary_operator integer try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier except_clause identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier try_statement block expression_statement assignment identifier call identifier argument_list identifier identifier except_clause identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier return_statement identifier
Imports a class dynamically from a full import path.
def documentation(self, add_to=None, version=None, prefix="", base_url="", url=""): doc = OrderedDict() if add_to is None else add_to usage = self.interface.spec.__doc__ if usage: doc['usage'] = usage for example in self.examples: example_text = "{0}{1}{2}{3}".format(prefix, base_url, '/v{0}'.format(version) if version else '', url) if isinstance(example, str): example_text += "?{0}".format(example) doc_examples = doc.setdefault('examples', []) if not example_text in doc_examples: doc_examples.append(example_text) doc = super().documentation(doc) if getattr(self, 'output_doc', ''): doc['outputs']['type'] = self.output_doc return doc
module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none default_parameter identifier string string_start string_end default_parameter identifier string string_start string_end default_parameter identifier string string_start string_end block expression_statement assignment identifier conditional_expression call identifier argument_list comparison_operator identifier none identifier expression_statement assignment identifier attribute attribute attribute identifier identifier identifier identifier if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end identifier for_statement identifier attribute identifier identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier identifier conditional_expression call attribute string string_start string_content string_end identifier argument_list identifier identifier string string_start string_end identifier if_statement call identifier argument_list identifier identifier block expression_statement augmented_assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end list if_statement not_operator comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute call identifier argument_list identifier argument_list identifier if_statement call identifier argument_list identifier string string_start string_content string_end string string_start string_end block expression_statement assignment subscript subscript identifier string string_start string_content string_end string string_start string_content string_end attribute identifier identifier return_statement identifier
Returns the documentation specific to an HTTP interface
def lf (self): old_r = self.cur_r self.cursor_down() if old_r == self.cur_r: self.scroll_up () self.erase_line()
module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list if_statement comparison_operator identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list
This moves the cursor down with scrolling.