code
stringlengths
51
2.34k
sequence
stringlengths
186
3.94k
docstring
stringlengths
11
171
def consume_normals(self): while True: yield ( float(self.values[1]), float(self.values[2]), float(self.values[3]), ) try: self.next_line() except StopIteration: break if not self.values: break if self.values[0] != "vn": break
module function_definition identifier parameters identifier block while_statement true block expression_statement yield tuple call identifier argument_list subscript attribute identifier identifier integer call identifier argument_list subscript attribute identifier identifier integer call identifier argument_list subscript attribute identifier identifier integer try_statement block expression_statement call attribute identifier identifier argument_list except_clause identifier block break_statement if_statement not_operator attribute identifier identifier block break_statement if_statement comparison_operator subscript attribute identifier identifier integer string string_start string_content string_end block break_statement
Consumes all consecutive texture coordinate lines
def read_reg(self, addr): val, data = self.command(self.ESP_READ_REG, struct.pack('<I', addr)) if byte(data, 0) != 0: raise FatalError.WithResult("Failed to read register address %08x" % addr, data) return val
module function_definition identifier parameters identifier identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list attribute identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier if_statement comparison_operator call identifier argument_list identifier integer integer block raise_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier identifier return_statement identifier
Read memory address in target
def refresh_interval(self, refresh_interval): if isinstance(refresh_interval, int) and refresh_interval > 0: self._refresh_interval = refresh_interval else: self._refresh_interval = None
module function_definition identifier parameters identifier identifier block if_statement boolean_operator call identifier argument_list identifier identifier comparison_operator identifier integer block expression_statement assignment attribute identifier identifier identifier else_clause block expression_statement assignment attribute identifier identifier none
Set the new cache refresh interval
def safe_int(value): try: result = int(value) if result < 0: raise NegativeDurationError( 'Negative values in duration strings are not allowed!' ) except NegativeDurationError as exc: raise exc except (TypeError, ValueError): result = 0 return result
module function_definition identifier parameters identifier block try_statement block expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier integer block raise_statement call identifier argument_list string string_start string_content string_end except_clause as_pattern identifier as_pattern_target identifier block raise_statement identifier except_clause tuple identifier identifier block expression_statement assignment identifier integer return_statement identifier
Tries to convert a value to int; returns 0 if conversion failed
def reset(project, user): d = Project.path(project, user) + "output" if os.path.isdir(d): shutil.rmtree(d) os.makedirs(d) else: raise flask.abort(404) if os.path.exists(Project.path(project, user) + ".done"): os.unlink(Project.path(project, user) + ".done") if os.path.exists(Project.path(project, user) + ".status"): os.unlink(Project.path(project, user) + ".status")
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier binary_operator call attribute identifier identifier argument_list identifier identifier string string_start string_content string_end if_statement call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier else_clause block raise_statement call attribute identifier identifier argument_list integer if_statement call attribute attribute identifier identifier identifier argument_list binary_operator call attribute identifier identifier argument_list identifier identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list binary_operator call attribute identifier identifier argument_list identifier identifier string string_start string_content string_end if_statement call attribute attribute identifier identifier identifier argument_list binary_operator call attribute identifier identifier argument_list identifier identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list binary_operator call attribute identifier identifier argument_list identifier identifier string string_start string_content string_end
Reset system, delete all output files and prepare for a new run
def getBoundsColor(self, nNumOutputColors, flCollisionBoundsFadeDistance): fn = self.function_table.getBoundsColor pOutputColorArray = HmdColor_t() pOutputCameraColor = HmdColor_t() fn(byref(pOutputColorArray), nNumOutputColors, flCollisionBoundsFadeDistance, byref(pOutputCameraColor)) return pOutputColorArray, pOutputCameraColor
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call identifier argument_list expression_statement call identifier argument_list call identifier argument_list identifier identifier identifier call identifier argument_list identifier return_statement expression_list identifier identifier
Get the current chaperone bounds draw color and brightness
def stem_leaf_plot(data, vmin, vmax, bins, digit=1, title=None): assert bins > 0 range = vmax - vmin step = range * 1. / bins if isinstance(range, int): step = int(ceil(step)) step = step or 1 bins = np.arange(vmin, vmax + step, step) hist, bin_edges = np.histogram(data, bins=bins) bin_edges = bin_edges[:len(hist)] asciiplot(bin_edges, hist, digit=digit, title=title) print("Last bin ends in {0}, inclusive.".format(vmax), file=sys.stderr) return bin_edges, hist
module function_definition identifier parameters identifier identifier identifier identifier default_parameter identifier integer default_parameter identifier none block assert_statement comparison_operator identifier integer expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier binary_operator binary_operator identifier float identifier if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list call identifier argument_list identifier expression_statement assignment identifier boolean_operator identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier binary_operator identifier identifier identifier expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier expression_statement assignment identifier subscript identifier slice call identifier argument_list identifier expression_statement call identifier argument_list identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier keyword_argument identifier attribute identifier identifier return_statement expression_list identifier identifier
Generate stem and leaf plot given a collection of numbers
def from_bucket(cls, connection, bucket): if bucket is None: raise errors.NoContainerException return cls(connection, bucket.name)
module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator identifier none block raise_statement attribute identifier identifier return_statement call identifier argument_list identifier attribute identifier identifier
Create from bucket object.
def token_permission_view(token): scopes = [current_oauth2server.scopes[x] for x in token.scopes] return render_template( "invenio_oauth2server/settings/token_permission_view.html", token=token, scopes=scopes, )
module function_definition identifier parameters identifier block expression_statement assignment identifier list_comprehension subscript attribute identifier identifier identifier for_in_clause identifier attribute identifier identifier return_statement call identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifier
Show permission garanted to authorized application token.
def unpack(cls, msg): flags, cursor_id, _, number_returned = cls.UNPACK_FROM(msg) documents = bytes(msg[20:]) return cls(flags, cursor_id, number_returned, documents)
module function_definition identifier parameters identifier identifier block expression_statement assignment pattern_list identifier identifier identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list subscript identifier slice integer return_statement call identifier argument_list identifier identifier identifier identifier
Construct an _OpReply from raw bytes.
def parse_headers(self, req, name, field): return req.get_header(name, required=False) or core.missing
module function_definition identifier parameters identifier identifier identifier identifier block return_statement boolean_operator call attribute identifier identifier argument_list identifier keyword_argument identifier false attribute identifier identifier
Pull a header value from the request.
def find_spectrum_match(spec, spec_lib, method='euclidian'): spec = spec / np.max(spec) if method == 'dot': d1 = (spec_lib * lil_matrix(spec).T).sum(axis=1).A ** 2 d2 = np.sum(spec ** 2) * spec_lib.multiply(spec_lib).sum(axis=1).A dist = d1 / d2 elif method == 'euclidian': st_spc = dia_matrix((spec, [0]), shape=(len(spec), len(spec))) dist_sp = spec_lib.multiply(spec_lib) - 2 * spec_lib.dot(st_spc) dist = dist_sp.sum(axis=1).A + np.sum(spec ** 2) return (dist.argmin(), dist.min())
module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier binary_operator identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier binary_operator attribute call attribute parenthesized_expression binary_operator identifier attribute call identifier argument_list identifier identifier identifier argument_list keyword_argument identifier integer identifier integer expression_statement assignment identifier binary_operator call attribute identifier identifier argument_list binary_operator identifier integer attribute call attribute call attribute identifier identifier argument_list identifier identifier argument_list keyword_argument identifier integer identifier expression_statement assignment identifier binary_operator identifier identifier elif_clause comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list tuple identifier list integer keyword_argument identifier tuple call identifier argument_list identifier call identifier argument_list identifier expression_statement assignment identifier binary_operator call attribute identifier identifier argument_list identifier binary_operator integer call attribute identifier identifier argument_list identifier expression_statement assignment identifier binary_operator attribute call attribute identifier identifier argument_list keyword_argument identifier integer identifier call attribute identifier identifier argument_list binary_operator identifier integer return_statement tuple call attribute identifier identifier argument_list call attribute identifier identifier argument_list
Find spectrum in spec_lib most similar to spec.
def execute(self): cluster_name = self.params.cluster creator = make_creator(self.params.config, storage_path=self.params.storage) try: cluster = creator.load_cluster(cluster_name) except (ClusterNotFound, ConfigurationError) as e: log.error("Cannot load cluster `%s`: %s", cluster_name, e) return os.EX_NOINPUT if not self.params.yes: confirm_or_abort( "Do you want really want to pause cluster `{cluster_name}`?" .format(cluster_name=cluster_name), msg="Aborting upon user request.") print("Pausing cluster `%s` ..." % cluster_name) cluster.pause()
module function_definition identifier parameters identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list attribute attribute identifier identifier identifier keyword_argument identifier attribute attribute identifier identifier identifier try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier except_clause as_pattern tuple identifier identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier return_statement attribute identifier identifier if_statement not_operator attribute attribute identifier identifier identifier block expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end expression_statement call identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list
Pause the cluster if it is running.
def njsd(network, ref_gene_expression_dict, query_gene_expression_dict, gene_set): gene_jsd_dict = dict() reference_genes = ref_gene_expression_dict.keys() assert len(reference_genes) != 'Reference gene expression profile should have > 0 genes.' for gene in gene_set: if gene not in network.nodes: continue neighbors = find_neighbors(network, gene) query_expression_vec = get_neighbor_expression_vector(neighbors, query_gene_expression_dict) ref_expression_vec = get_neighbor_expression_vector(neighbors, ref_gene_expression_dict) assert len(query_expression_vec) == len(ref_expression_vec), 'Topology of reference network and query network differs. Please check.' if np.sum(query_expression_vec) == 0 and np.sum(ref_expression_vec) == 0: continue query_p_vec = exp2prob(query_expression_vec) ref_p_vec = exp2prob(ref_expression_vec) gene_jsd_dict[gene] = jsd(query_p_vec, ref_p_vec) return np.mean(list(gene_jsd_dict.values()))
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list assert_statement comparison_operator call identifier argument_list identifier string string_start string_content string_end for_statement identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block continue_statement expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier assert_statement comparison_operator call identifier argument_list identifier call identifier argument_list identifier string string_start string_content string_end if_statement boolean_operator comparison_operator call attribute identifier identifier argument_list identifier integer comparison_operator call attribute identifier identifier argument_list identifier integer block continue_statement expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment subscript identifier identifier call identifier argument_list identifier identifier return_statement call attribute identifier identifier argument_list call identifier argument_list call attribute identifier identifier argument_list
Calculate Jensen-Shannon divergence between query and reference gene expression profile.
def reverse_reference(self): self.ref_start = self.ref_length - self.ref_start - 1 self.ref_end = self.ref_length - self.ref_end - 1
module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier binary_operator binary_operator attribute identifier identifier attribute identifier identifier integer expression_statement assignment attribute identifier identifier binary_operator binary_operator attribute identifier identifier attribute identifier identifier integer
Changes the coordinates as if the reference sequence has been reverse complemented
def aot_blpop(self): if self.tcex.default_args.tc_playbook_db_type == 'Redis': res = None try: self.tcex.log.info('Blocking for AOT message.') msg_data = self.db.blpop( self.tcex.default_args.tc_action_channel, timeout=self.tcex.default_args.tc_terminate_seconds, ) if msg_data is None: self.tcex.exit(0, 'AOT subscription timeout reached.') msg_data = json.loads(msg_data[1]) msg_type = msg_data.get('type', 'terminate') if msg_type == 'execute': res = msg_data.get('params', {}) elif msg_type == 'terminate': self.tcex.exit(0, 'Received AOT terminate message.') else: self.tcex.log.warn('Unsupported AOT message type: ({}).'.format(msg_type)) res = self.aot_blpop() except Exception as e: self.tcex.exit(1, 'Exception during AOT subscription ({}).'.format(e)) return res
module function_definition identifier parameters identifier block if_statement comparison_operator attribute attribute attribute identifier identifier identifier identifier string string_start string_content string_end block expression_statement assignment identifier none try_statement block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute attribute attribute identifier identifier identifier identifier keyword_argument identifier attribute attribute attribute identifier identifier identifier identifier if_statement comparison_operator identifier none block expression_statement call attribute attribute identifier identifier identifier argument_list integer string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list subscript identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end dictionary elif_clause comparison_operator identifier string string_start string_content string_end block expression_statement call attribute attribute identifier identifier identifier argument_list integer string string_start string_content string_end else_clause block expression_statement call attribute attribute attribute identifier identifier identifier 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 except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute attribute identifier identifier identifier argument_list integer call attribute string string_start string_content string_end identifier argument_list identifier return_statement identifier
Subscribe to AOT action channel.
def clear_measurements(self): mid_list = self.assignments.get('measurements', None) if mid_list is not None: for mid in mid_list: self.configs.delete_measurements(mid=mid) self.assignments['measurements'] = None
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end none if_statement comparison_operator identifier none block for_statement identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end none
Forget any previous measurements
def call(self, method, *args, **params): transaction_id = params.get("transaction_id") if not transaction_id: self.transaction_id += 1 transaction_id = self.transaction_id obj = params.get("obj") args = [method, transaction_id, obj] + list(args) args_encoded = map(lambda x: encode_amf(x), args) body = b"".join(args_encoded) format = params.get("format", PACKET_SIZE_MEDIUM) channel = params.get("channel", 0x03) packet = RTMPPacket(type=PACKET_TYPE_INVOKE, format=format, channel=channel, body=body) self.send_packet(packet) return RTMPCall(self, transaction_id)
module function_definition identifier parameters identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement not_operator identifier block expression_statement augmented_assignment attribute identifier identifier integer expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier binary_operator list identifier identifier identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list lambda lambda_parameters identifier call identifier argument_list identifier identifier expression_statement assignment identifier call attribute string string_start string_end 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 attribute identifier identifier argument_list string string_start string_content string_end integer expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list identifier return_statement call identifier argument_list identifier identifier
Calls a method on the server.
def _add_numeric_methods_binary(cls): cls.__add__ = _make_arithmetic_op(operator.add, cls) cls.__radd__ = _make_arithmetic_op(ops.radd, cls) cls.__sub__ = _make_arithmetic_op(operator.sub, cls) cls.__rsub__ = _make_arithmetic_op(ops.rsub, cls) cls.__rpow__ = _make_arithmetic_op(ops.rpow, cls) cls.__pow__ = _make_arithmetic_op(operator.pow, cls) cls.__truediv__ = _make_arithmetic_op(operator.truediv, cls) cls.__rtruediv__ = _make_arithmetic_op(ops.rtruediv, cls) cls.__mod__ = _make_arithmetic_op(operator.mod, cls) cls.__floordiv__ = _make_arithmetic_op(operator.floordiv, cls) cls.__rfloordiv__ = _make_arithmetic_op(ops.rfloordiv, cls) cls.__divmod__ = _make_arithmetic_op(divmod, cls) cls.__mul__ = _make_arithmetic_op(operator.mul, cls) cls.__rmul__ = _make_arithmetic_op(ops.rmul, cls)
module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier identifier expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier identifier expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier identifier expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier identifier expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier identifier expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier identifier expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier identifier expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier identifier expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier identifier expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier identifier expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier identifier expression_statement assignment attribute identifier identifier call identifier argument_list identifier identifier expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier identifier expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier identifier
Add in numeric methods.
def _unpack(self, record, key, expected): attrs = record.get(key) if attrs is None: return obj = unpack_from_dynamodb( attrs=attrs, expected=expected, model=self.model, engine=self.engine ) object_loaded.send(self.engine, engine=self.engine, obj=obj) record[key] = obj
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier none block return_statement expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier expression_statement assignment subscript identifier identifier identifier
Replaces the attr dict at the given key with an instance of a Model
def copy(self): other = ContextModel(self._context, self.parent()) other._stale = self._stale other._modified = self._modified other.request = self.request[:] other.packages_path = self.packages_path other.implicit_packages = self.implicit_packages other.package_filter = self.package_filter other.caching = self.caching other.default_patch_lock = self.default_patch_lock other.patch_locks = copy.deepcopy(self.patch_locks) return other
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier subscript attribute identifier identifier slice expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier return_statement identifier
Returns a copy of the context.
def _write_to_file(self, filename, bytesvalue): fh, tmp = tempfile.mkstemp() with os.fdopen(fh, self._flag) as f: f.write(self._dumps(bytesvalue)) rename(tmp, filename) os.chmod(filename, self._mode)
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list identifier attribute identifier identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier expression_statement call identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list identifier attribute identifier identifier
Write bytesvalue to filename.
def owned_ecs(self): with self._mutex: if not self._owned_ecs: self._owned_ecs = [ExecutionContext(ec, self._obj.get_context_handle(ec)) \ for ec in self._obj.get_owned_contexts()] return self._owned_ecs
module function_definition identifier parameters identifier block with_statement with_clause with_item attribute identifier identifier block if_statement not_operator attribute identifier identifier block expression_statement assignment attribute identifier identifier list_comprehension call identifier argument_list identifier call attribute attribute identifier identifier identifier argument_list identifier line_continuation for_in_clause identifier call attribute attribute identifier identifier identifier argument_list return_statement attribute identifier identifier
A list of the execution contexts owned by this component.
def list_zip(archive, compression, cmd, verbosity, interactive): try: with zipfile.ZipFile(archive, "r") as zfile: for name in zfile.namelist(): if verbosity >= 0: print(name) except Exception as err: msg = "error listing %s: %s" % (archive, err) raise util.PatoolError(msg) return None
module function_definition identifier parameters identifier identifier identifier identifier identifier block try_statement block with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block for_statement identifier call attribute identifier identifier argument_list block if_statement comparison_operator identifier integer block expression_statement call identifier argument_list identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end tuple identifier identifier raise_statement call attribute identifier identifier argument_list identifier return_statement none
List member of a ZIP archive with the zipfile Python module.
def _path_to_be_kept(self, path): if self.excludes and (path in self.excludes or helpers.is_inside_any(self.excludes, path)): return False if self.includes: return (path in self.includes or helpers.is_inside_any(self.includes, path)) return True
module function_definition identifier parameters identifier identifier block if_statement boolean_operator attribute identifier identifier parenthesized_expression boolean_operator comparison_operator identifier attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier identifier block return_statement false if_statement attribute identifier identifier block return_statement parenthesized_expression boolean_operator comparison_operator identifier attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier identifier return_statement true
Does the given path pass the filtering criteria?
def error_handler(_, event): evt = event.contents ERROR.details = { "type": evt.type, "serial": evt.serial, "error_code": evt.error_code, "request_code": evt.request_code, "minor_code": evt.minor_code, } return 0
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment attribute identifier identifier dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier return_statement integer
Specifies the program's supplied error handler.
def upload_artifacts(self): deploy_strategy = self.properties["deploy_strategy"] mirror = False if deploy_strategy == "mirror": mirror = True self._upload_artifacts_to_path(mirror=mirror) if deploy_strategy == "highlander": self._sync_to_uri(self.s3_latest_uri) elif deploy_strategy == "canary": self._sync_to_uri(self.s3_canary_uri) elif deploy_strategy == "alpha": self._sync_to_uri(self.s3_alpha_uri) elif deploy_strategy == "mirror": pass else: raise NotImplementedError
module function_definition identifier parameters identifier block expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier false if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier true expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier if_statement comparison_operator identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list attribute identifier identifier elif_clause comparison_operator identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list attribute identifier identifier elif_clause comparison_operator identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list attribute identifier identifier elif_clause comparison_operator identifier string string_start string_content string_end block pass_statement else_clause block raise_statement identifier
Upload artifacts to S3 and copy to correct path depending on strategy.
def all(): dir() cmd3() banner("CLEAN PREVIOUS CLOUDMESH INSTALLS") r = int(local("pip freeze |fgrep cloudmesh | wc -l", capture=True)) while r > 0: local('echo "y\n" | pip uninstall cloudmesh') r = int(local("pip freeze |fgrep cloudmesh | wc -l", capture=True))
module function_definition identifier parameters block expression_statement call identifier argument_list expression_statement call identifier argument_list expression_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list call identifier argument_list string string_start string_content string_end keyword_argument identifier true while_statement comparison_operator identifier integer block expression_statement call identifier argument_list string string_start string_content escape_sequence string_end expression_statement assignment identifier call identifier argument_list call identifier argument_list string string_start string_content string_end keyword_argument identifier true
clean the dis and uninstall cloudmesh
def _from_dict(cls, _dict): args = {} if 'generic' in _dict: args['generic'] = [ DialogRuntimeResponseGeneric._from_dict(x) for x in (_dict.get('generic')) ] if 'intents' in _dict: args['intents'] = [ RuntimeIntent._from_dict(x) for x in (_dict.get('intents')) ] if 'entities' in _dict: args['entities'] = [ RuntimeEntity._from_dict(x) for x in (_dict.get('entities')) ] if 'actions' in _dict: args['actions'] = [ DialogNodeAction._from_dict(x) for x in (_dict.get('actions')) ] if 'debug' in _dict: args['debug'] = MessageOutputDebug._from_dict(_dict.get('debug')) if 'user_defined' in _dict: args['user_defined'] = _dict.get('user_defined') return cls(**args)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier parenthesized_expression call attribute identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier parenthesized_expression call attribute identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier parenthesized_expression call attribute identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier parenthesized_expression call attribute identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end return_statement call identifier argument_list dictionary_splat identifier
Initialize a MessageOutput object from a json dictionary.
def execute(self, conn, site_name= "", transaction = False): sql = self.sql if site_name == "": result = self.dbi.processData(sql, conn=conn, transaction=transaction) else: sql += "WHERE S.SITE_NAME = :site_name" binds = { "site_name" : site_name } result = self.dbi.processData(sql, binds, conn, transaction) return self.formatDict(result)
module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_end default_parameter identifier false block expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator identifier string string_start string_end block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier else_clause block expression_statement augmented_assignment identifier string string_start string_content string_end expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier identifier identifier return_statement call attribute identifier identifier argument_list identifier
Lists all sites types if site_name is not provided.
def take_function_register(self, rtype = SharedData.TYPES.NO_TYPE): reg = SharedData.FUNCTION_REGISTER if reg not in self.free_registers: self.error("function register already taken") self.free_registers.remove(reg) self.used_registers.append(reg) self.symtab.set_type(reg, rtype) return reg
module function_definition identifier parameters identifier default_parameter identifier attribute attribute identifier identifier identifier block expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator identifier attribute identifier identifier block 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 identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier return_statement identifier
Reserves register for function return value and sets its type
def word_to_vector(word): vector = [] for char in list(word): vector.append(char2int(char)) return vector
module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement identifier call identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier return_statement identifier
Convert character vectors to integer vectors.
def _detect(self): results = [] for c in self.contracts: unindexed_params = self.detect_erc20_unindexed_event_params(c) if unindexed_params: info = "{} ({}) does not mark important ERC20 parameters as 'indexed':\n" info = info.format(c.name, c.source_mapping_str) for (event, parameter) in unindexed_params: info += "\t-{} ({}) does not index parameter '{}'\n".format(event.name, event.source_mapping_str, parameter.name) json = self.generate_json_result(info) self.add_functions_to_json([event for event, _ in unindexed_params], json) results.append(json) return results
module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement identifier block expression_statement assignment identifier string string_start string_content escape_sequence string_end expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier for_statement tuple_pattern identifier identifier identifier block expression_statement augmented_assignment identifier call attribute string string_start string_content escape_sequence escape_sequence string_end identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list list_comprehension identifier for_in_clause pattern_list identifier identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier
Detect un-indexed ERC20 event parameters in all contracts.
def substitution_set(string, indexes): strlen = len(string) return {mutate_string(string, x) for x in indexes if valid_substitution(strlen, x)}
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier return_statement set_comprehension call identifier argument_list identifier identifier for_in_clause identifier identifier if_clause call identifier argument_list identifier identifier
for a string, return a set of all possible substitutions
def emit_node(self, node): emit = getattr(self, "%s_emit" % node.kind, self.default_emit) return emit(node)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier binary_operator string string_start string_content string_end attribute identifier identifier attribute identifier identifier return_statement call identifier argument_list identifier
Emit a single node.
def _get_cibfile_tmp(cibname): cibfile_tmp = '{0}.tmp'.format(_get_cibfile(cibname)) log.trace('cibfile_tmp: %s', cibfile_tmp) return cibfile_tmp
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier return_statement identifier
Get the full path of a temporary CIB-file with the name of the CIB
def removeDuplicates(inFileName, outFileName) : f = open(inFileName) legend = f.readline() data = '' h = {} h[legend] = 0 lines = f.readlines() for l in lines : if not h.has_key(l) : h[l] = 0 data += l f.flush() f.close() f = open(outFileName, 'w') f.write(legend+data) f.flush() f.close()
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier string string_start string_end expression_statement assignment identifier dictionary expression_statement assignment subscript identifier identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list for_statement identifier identifier block if_statement not_operator call attribute identifier identifier argument_list identifier block expression_statement assignment subscript identifier identifier integer expression_statement augmented_assignment identifier identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list binary_operator identifier identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list
removes duplicated lines from a 'inFileName' CSV file, the results are witten in 'outFileName
def _get_struct_matrix(self): obj = _make_object("Matrix") bc = BitConsumer(self._src) obj.HasScale = bc.u_get(1) if obj.HasScale: obj.NScaleBits = n_scale_bits = bc.u_get(5) obj.ScaleX = bc.fb_get(n_scale_bits) obj.ScaleY = bc.fb_get(n_scale_bits) obj.HasRotate = bc.u_get(1) if obj.HasRotate: obj.NRotateBits = n_rotate_bits = bc.u_get(5) obj.RotateSkew0 = bc.fb_get(n_rotate_bits) obj.RotateSkew1 = bc.fb_get(n_rotate_bits) obj.NTranslateBits = n_translate_bits = bc.u_get(5) obj.TranslateX = bc.s_get(n_translate_bits) obj.TranslateY = bc.s_get(n_translate_bits) if not self._read_twips: obj.TranslateX /= 20.0 obj.TranslateY /= 20.0 return obj
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list integer if_statement attribute identifier identifier block expression_statement assignment attribute identifier identifier assignment identifier call attribute identifier identifier argument_list integer expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list integer if_statement attribute identifier identifier block expression_statement assignment attribute identifier identifier assignment identifier call attribute identifier identifier argument_list integer expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier assignment identifier call attribute identifier identifier argument_list integer expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier if_statement not_operator attribute identifier identifier block expression_statement augmented_assignment attribute identifier identifier float expression_statement augmented_assignment attribute identifier identifier float return_statement identifier
Get the values for the MATRIX record.
def _transform_legacy_stats(self, stats): if stats and 'pools' not in stats: pool = stats.copy() pool['pool_name'] = self.id for key in ('driver_version', 'shared_targets', 'sparse_copy_volume', 'storage_protocol', 'vendor_name', 'volume_backend_name'): pool.pop(key, None) stats['pools'] = [pool] return stats
module function_definition identifier parameters identifier identifier block if_statement boolean_operator identifier comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier for_statement identifier tuple string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list identifier none expression_statement assignment subscript identifier string string_start string_content string_end list identifier return_statement identifier
Convert legacy stats to new stats with pools key.
def generic_find_fk_constraint_names(table, columns, referenced, insp): names = set() for fk in insp.get_foreign_keys(table): if fk['referred_table'] == referenced and set(fk['referred_columns']) == columns: names.add(fk['name']) return names
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call identifier argument_list for_statement identifier call attribute identifier identifier argument_list identifier block if_statement boolean_operator comparison_operator subscript identifier string string_start string_content string_end identifier comparison_operator call identifier argument_list subscript identifier string string_start string_content string_end identifier block expression_statement call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end return_statement identifier
Utility to find foreign-key constraint names in alembic migrations
def process_unset(line, annotations): matches = re.match('UNSET\s+"?(.*?)"?\s*$', line) if matches: val = matches.group(1) if val == "ALL" or val == "STATEMENT_GROUP": annotations = {} elif re.match("{", val): vals = convert_csv_str_to_list(val) for val in vals: annotations.pop(val, None) else: annotations.pop(val, None) else: log.warn(f"Problem with UNSET line: {line}") return annotations
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 identifier block expression_statement assignment identifier call attribute identifier identifier argument_list integer if_statement boolean_operator comparison_operator identifier string string_start string_content string_end comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier dictionary elif_clause call attribute identifier identifier argument_list string string_start string_content string_end identifier block expression_statement assignment identifier call identifier argument_list identifier for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list identifier none else_clause block expression_statement call attribute identifier identifier argument_list identifier none else_clause block expression_statement call attribute identifier identifier argument_list string string_start string_content interpolation identifier string_end return_statement identifier
Process UNSET lines in BEL Script
def __configure_client(self, config): self.logger.info("Configuring p4 client...") client_dict = config.to_dict() client_dict['root_path'] = os.path.expanduser(config.get('root_path')) os.chdir(client_dict['root_path']) client_dict['hostname'] = system.NODE client_dict['p4view'] = config['p4view'] % self.environment.target.get_context_dict() client = re.sub('//depot', ' //depot', p4client_template % client_dict) self.logger.info(lib.call("%s client -i" % self.p4_command, stdin=client, env=self.p4environ, cwd=client_dict['root_path']))
module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment subscript identifier string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier expression_statement assignment subscript identifier string string_start string_content string_end binary_operator subscript identifier string string_start string_content string_end call attribute attribute attribute identifier identifier identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end binary_operator identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier subscript identifier string string_start string_content string_end
write the perforce client
def copy_heroku_to_local(id): heroku_app = HerokuApp(dallinger_uid=id) try: subprocess.call(["dropdb", heroku_app.name]) except Exception: pass heroku_app.pg_pull()
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier try_statement block expression_statement call attribute identifier identifier argument_list list string string_start string_content string_end attribute identifier identifier except_clause identifier block pass_statement expression_statement call attribute identifier identifier argument_list
Copy a Heroku database locally.
def show_version(self): version_info = self.get_cli_version() version_info += self.get_runtime_version() print(version_info, file=self.out_file)
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement augmented_assignment identifier call attribute identifier identifier argument_list expression_statement call identifier argument_list identifier keyword_argument identifier attribute identifier identifier
Print version information to the out file.
def send_hid_event(use_page, usage, down): message = create(protobuf.SEND_HID_EVENT_MESSAGE) event = message.inner() abstime = binascii.unhexlify(b'438922cf08020000') data = use_page.to_bytes(2, byteorder='big') data += usage.to_bytes(2, byteorder='big') data += (1 if down else 0).to_bytes(2, byteorder='big') event.hidEventData = abstime + \ binascii.unhexlify(b'00000000000000000100000000000000020' + b'00000200000000300000001000000000000') + \ data + \ binascii.unhexlify(b'0000000000000001000000') return message
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier 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 attribute identifier identifier argument_list integer keyword_argument identifier string string_start string_content string_end expression_statement augmented_assignment identifier call attribute identifier identifier argument_list integer keyword_argument identifier string string_start string_content string_end expression_statement augmented_assignment identifier call attribute parenthesized_expression conditional_expression integer identifier integer identifier argument_list integer keyword_argument identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier binary_operator binary_operator binary_operator identifier line_continuation call attribute identifier identifier argument_list binary_operator string string_start string_content string_end string string_start string_content string_end line_continuation identifier line_continuation call attribute identifier identifier argument_list string string_start string_content string_end return_statement identifier
Create a new SEND_HID_EVENT_MESSAGE.
def ripple_carry_add(A, B, cin=0): if len(A) != len(B): raise ValueError("expected A and B to be equal length") ss, cs = list(), list() for i, a in enumerate(A): c = (cin if i == 0 else cs[i-1]) ss.append(a ^ B[i] ^ c) cs.append(a & B[i] | a & c | B[i] & c) return farray(ss), farray(cs)
module function_definition identifier parameters identifier identifier default_parameter identifier integer block if_statement comparison_operator call identifier argument_list identifier call identifier argument_list identifier block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment pattern_list identifier identifier expression_list call identifier argument_list call identifier argument_list for_statement pattern_list identifier identifier call identifier argument_list identifier block expression_statement assignment identifier parenthesized_expression conditional_expression identifier comparison_operator identifier integer subscript identifier binary_operator identifier integer expression_statement call attribute identifier identifier argument_list binary_operator binary_operator identifier subscript identifier identifier identifier expression_statement call attribute identifier identifier argument_list binary_operator binary_operator binary_operator identifier subscript identifier identifier binary_operator identifier identifier binary_operator subscript identifier identifier identifier return_statement expression_list call identifier argument_list identifier call identifier argument_list identifier
Return symbolic logic for an N-bit ripple carry adder.
def handle_ajax_request(self): func_arg = self.traverse_subpath[0] func_name = "ajax_{}".format(func_arg) func = getattr(self, func_name, None) if func is None: return self.fail("Invalid function", status=400) args = self.traverse_subpath[1:] func_sig = inspect.getargspec(func) required_args = func_sig.args[1:] if len(args) < len(required_args): return self.fail("Wrong signature, please use '{}/{}'" .format(func_arg, "/".join(required_args)), 400) return func(*args)
module function_definition identifier parameters identifier block 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 expression_statement assignment identifier call identifier argument_list identifier identifier none if_statement comparison_operator identifier none block return_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier integer expression_statement assignment identifier subscript attribute identifier identifier slice integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier subscript attribute identifier identifier slice integer if_statement comparison_operator call identifier argument_list identifier call identifier argument_list identifier block return_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier call attribute string string_start string_content string_end identifier argument_list identifier integer return_statement call identifier argument_list list_splat identifier
Handle requests ajax routes
def _is_compress_filetype(self, inpath): if self._is_common_binary(inpath): return False elif self._is_common_text(inpath): return True else: the_file_size = file_size(inpath) if the_file_size > 10240: if the_file_size > 512000: try: system_command = "file --mime-type -b " + quote(inpath) response = muterun(system_command) if response.stdout[0:5] == "text/": return True else: return False except Exception: return False else: return True else: return False
module function_definition identifier parameters identifier identifier block if_statement call attribute identifier identifier argument_list identifier block return_statement false elif_clause call attribute identifier identifier argument_list identifier block return_statement true else_clause block expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier integer block if_statement comparison_operator identifier integer block try_statement block expression_statement assignment identifier binary_operator string string_start string_content string_end call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator subscript attribute identifier identifier slice integer integer string string_start string_content string_end block return_statement true else_clause block return_statement false except_clause identifier block return_statement false else_clause block return_statement true else_clause block return_statement false
private method that performs magic number and size check on file to determine whether to compress the file
def buildfeed(request, feedclass, **criterias): 'View that handles the feeds.' view_data = initview(request) wrap = lambda func: ft.partial(func, _view_data=view_data, **criterias) return condition( etag_func=wrap(cache_etag), last_modified_func=wrap(cache_last_modified) )\ (_buildfeed)(request, feedclass, view_data, **criterias)
module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier lambda lambda_parameters identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier dictionary_splat identifier return_statement call call call identifier argument_list keyword_argument identifier call identifier argument_list identifier keyword_argument identifier call identifier argument_list identifier line_continuation argument_list identifier argument_list identifier identifier identifier dictionary_splat identifier
View that handles the feeds.
def addBiosample(self): self._openRepo() dataset = self._repo.getDatasetByName(self._args.datasetName) biosample = bio_metadata.Biosample( dataset, self._args.biosampleName) biosample.populateFromJson(self._args.biosample) self._updateRepo(self._repo.insertBiosample, biosample)
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute attribute identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier attribute attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list attribute attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list attribute attribute identifier identifier identifier identifier
Adds a new biosample into this repo
def cache_set(cache_dir, cache_key, content): filename = os.path.join(cache_dir, cache_key) with open(filename, 'w') as f: f.write(content)
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier
Creates a new cache file in the cache directory
def _head_temp_file(self, temp_file, num_lines): if not isinstance(num_lines, int): raise DagobahError('num_lines must be an integer') temp_file.seek(0) result, curr_line = [], 0 for line in temp_file: curr_line += 1 result.append(line.strip()) if curr_line >= num_lines: break return result
module function_definition identifier parameters identifier identifier identifier block if_statement not_operator call identifier argument_list identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list integer expression_statement assignment pattern_list identifier identifier expression_list list integer for_statement identifier identifier block expression_statement augmented_assignment identifier integer expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list if_statement comparison_operator identifier identifier block break_statement return_statement identifier
Returns a list of the first num_lines lines from a temp file.
def getparent(self, profile): assert self.parent for inputtemplate in profile.input: if inputtemplate == self.parent: return inputtemplate raise Exception("Parent InputTemplate '"+self.parent+"' not found!")
module function_definition identifier parameters identifier identifier block assert_statement attribute identifier identifier for_statement identifier attribute identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block return_statement identifier raise_statement call identifier argument_list binary_operator binary_operator string string_start string_content string_end attribute identifier identifier string string_start string_content string_end
Resolve a parent ID
def normalize(self): self.__v = self.__v - np.amin(self.__v) self.__v = self.__v / np.amax(self.__v)
module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier binary_operator attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier binary_operator attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier
Sets the potential range 0 to 1.
def flush(self): self.log.info('Flushing tables and arrays to disk...') for tab in self._tables.values(): tab.flush() self._write_ndarrays_cache_to_disk()
module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end for_statement identifier call attribute attribute identifier identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list
Flush tables and arrays to disk
def _stdlib_paths(): attr_candidates = [ 'prefix', 'real_prefix', 'base_prefix', ] prefixes = (getattr(sys, a) for a in attr_candidates if hasattr(sys, a)) version = 'python%s.%s' % sys.version_info[0:2] return set(os.path.abspath(os.path.join(p, 'lib', version)) for p in prefixes)
module function_definition identifier parameters block expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier generator_expression call identifier argument_list identifier identifier for_in_clause identifier identifier if_clause call identifier argument_list identifier identifier expression_statement assignment identifier binary_operator string string_start string_content string_end subscript attribute identifier identifier slice integer integer return_statement call identifier generator_expression call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end identifier for_in_clause identifier identifier
Return a set of paths from which Python imports the standard library.
def _get_raw(source, bitarray): offset = int(source['offset']) size = int(source['size']) return int(''.join(['1' if digit else '0' for digit in bitarray[offset:offset + size]]), 2)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list subscript identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list subscript identifier string string_start string_content string_end return_statement call identifier argument_list call attribute string string_start string_end identifier argument_list list_comprehension conditional_expression string string_start string_content string_end identifier string string_start string_content string_end for_in_clause identifier subscript identifier slice identifier binary_operator identifier identifier integer
Get raw data as integer, based on offset and size
def active_brokers(self): return { broker for broker in six.itervalues(self.brokers) if not broker.inactive and not broker.decommissioned }
module function_definition identifier parameters identifier block return_statement set_comprehension identifier for_in_clause identifier call attribute identifier identifier argument_list attribute identifier identifier if_clause boolean_operator not_operator attribute identifier identifier not_operator attribute identifier identifier
Set of brokers that are not inactive or decommissioned.
def build_upstream_edge_predicate(nodes: Iterable[BaseEntity]) -> EdgePredicate: nodes = set(nodes) def upstream_filter(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool: return v in nodes and graph[u][v][k][RELATION] in CAUSAL_RELATIONS return upstream_filter
module function_definition identifier parameters typed_parameter identifier type generic_type identifier type_parameter type identifier type identifier block expression_statement assignment identifier call identifier argument_list identifier function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier typed_parameter identifier type identifier typed_parameter identifier type identifier type identifier block return_statement boolean_operator comparison_operator identifier identifier comparison_operator subscript subscript subscript subscript identifier identifier identifier identifier identifier identifier return_statement identifier
Build an edge predicate that pass for relations for which one of the given nodes is the object.
def _start_dev_proc(self, device_os, device_config): log.info('Starting the child process for %s', device_os) dos = NapalmLogsDeviceProc(device_os, self.opts, device_config) os_proc = Process(target=dos.start) os_proc.start() os_proc.description = '%s device process' % device_os log.debug('Started process %s for %s, having PID %s', os_proc._name, device_os, os_proc.pid) return os_proc
module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier call identifier argument_list identifier attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list keyword_argument identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier binary_operator string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier identifier attribute identifier identifier return_statement identifier
Start the device worker process.
def evaluate(self, model, threshold=0.1): with model: if self.medium is not None: self.medium.apply(model) if self.objective is not None: model.objective = self.objective model.add_cons_vars(self.constraints) threshold *= model.slim_optimize() growth = list() for row in self.data.itertuples(index=False): with model: exchange = model.reactions.get_by_id(row.exchange) if bool(exchange.reactants): exchange.lower_bound = -row.uptake else: exchange.upper_bound = row.uptake growth.append(model.slim_optimize() >= threshold) return DataFrame({ "exchange": self.data["exchange"], "growth": growth })
module function_definition identifier parameters identifier identifier default_parameter identifier float block with_statement with_clause with_item identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement call attribute attribute identifier identifier identifier argument_list identifier if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement augmented_assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list for_statement identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier false block with_statement with_clause with_item identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier if_statement call identifier argument_list attribute identifier identifier block expression_statement assignment attribute identifier identifier unary_operator attribute identifier identifier else_clause block expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list comparison_operator call attribute identifier identifier argument_list identifier return_statement call identifier argument_list dictionary pair string string_start string_content string_end subscript attribute identifier identifier string string_start string_content string_end pair string string_start string_content string_end identifier
Evaluate in silico growth rates.
def _log_error_and_abort(ret, obj): ret['result'] = False ret['abort'] = True if 'error' in obj: ret['comment'] = '{0}'.format(obj.get('error')) return ret
module function_definition identifier parameters identifier identifier block expression_statement assignment subscript identifier string string_start string_content string_end false expression_statement assignment subscript identifier string string_start string_content string_end true if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end return_statement identifier
helper function to update errors in the return structure
async def send(self, data): self.writer.write(data) await self.writer.drain()
module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement await call attribute attribute identifier identifier identifier argument_list
Add data to send queue.
def load_file_to_list(self): lst = [] try: with open(self.fullname, 'r') as f: for line in f: lst.append(line) return lst except IOError: return lst
module function_definition identifier parameters identifier block expression_statement assignment identifier list try_statement block with_statement with_clause with_item as_pattern call identifier argument_list attribute identifier identifier string string_start string_content string_end as_pattern_target identifier block for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list identifier return_statement identifier except_clause identifier block return_statement identifier
load a file to a list
def run(ident): source = get_source(ident) cls = backends.get(current_app, source.backend) backend = cls(source) backend.harvest()
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list
Launch or resume an harvesting for a given source if none is running
def swap_across(idx, idy, mat_a, mat_r, perm): size = mat_a.shape[0] perm_new = numpy.eye(size, dtype=int) perm_row = 1.0*perm[:, idx] perm[:, idx] = perm[:, idy] perm[:, idy] = perm_row row_p = 1.0 * perm_new[idx] perm_new[idx] = perm_new[idy] perm_new[idy] = row_p mat_a = numpy.dot(perm_new, numpy.dot(mat_a, perm_new)) mat_r = numpy.dot(mat_r, perm_new) return mat_a, mat_r, perm
module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier expression_statement assignment identifier binary_operator float subscript identifier slice identifier expression_statement assignment subscript identifier slice identifier subscript identifier slice identifier expression_statement assignment subscript identifier slice identifier identifier expression_statement assignment identifier binary_operator float subscript identifier identifier expression_statement assignment subscript identifier identifier subscript identifier identifier expression_statement assignment subscript identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier return_statement expression_list identifier identifier identifier
Interchange row and column idy and idx.
def logs(self): if self._resources is None: self.__init() if "logs" in self._resources: url = self._url + "/logs" return _logs.Log(url=url, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port, initialize=True) else: return None
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement call attribute identifier identifier argument_list if_statement comparison_operator string string_start string_content string_end attribute identifier identifier block expression_statement assignment identifier binary_operator attribute identifier identifier string string_start string_content string_end return_statement call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier true else_clause block return_statement none
returns an object to work with the site logs
def make_links(self, project): self.doc = ford.utils.sub_links(self.doc,project) if 'summary' in self.meta: self.meta['summary'] = ford.utils.sub_links(self.meta['summary'],project) for item in self.iterator('variables', 'types', 'enums', 'modules', 'submodules', 'subroutines', 'functions', 'interfaces', 'absinterfaces', 'programs', 'boundprocs', 'args', 'bindings'): if isinstance(item, FortranBase): item.make_links(project) if hasattr(self, 'retvar'): if self.retvar: if isinstance(self.retvar, FortranBase): self.retvar.make_links(project) if hasattr(self, 'procedure'): if isinstance(self.procedure, FortranBase): self.procedure.make_links(project)
module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier identifier if_statement comparison_operator string string_start string_content string_end attribute identifier identifier block expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list subscript attribute identifier identifier string string_start string_content string_end identifier for_statement identifier 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 string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end block if_statement call identifier argument_list identifier identifier block expression_statement call attribute identifier identifier argument_list identifier if_statement call identifier argument_list identifier string string_start string_content string_end block if_statement attribute identifier identifier block if_statement call identifier argument_list attribute identifier identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier if_statement call identifier argument_list identifier string string_start string_content string_end block if_statement call identifier argument_list attribute identifier identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier
Process intra-site links to documentation of other parts of the program.
def _create_date_slug(self): if not self.pk: d = utc_now() elif self.published and self.published_on: d = self.published_on elif self.updated_on: d = self.updated_on self.date_slug = u"{0}/{1}".format(d.strftime("%Y/%m/%d"), self.slug)
module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block expression_statement assignment identifier call identifier argument_list elif_clause boolean_operator attribute identifier identifier attribute identifier identifier block expression_statement assignment identifier attribute identifier identifier elif_clause attribute identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment attribute identifier identifier call attribute string string_start string_content string_end identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier
Prefixes the slug with the ``published_on`` date.
def _get_db_names(self): query = conn = self._connect(self.config['dbname']) cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor) cursor.execute(query) datnames = [d['datname'] for d in cursor.fetchall()] conn.close() if not datnames: datnames = ['postgres'] return datnames
module function_definition identifier parameters identifier block expression_statement assignment identifier assignment identifier call attribute identifier identifier argument_list subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier attribute attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier list_comprehension subscript identifier string string_start string_content string_end for_in_clause identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list if_statement not_operator identifier block expression_statement assignment identifier list string string_start string_content string_end return_statement identifier
Try to get a list of db names
def compare_password(expected, actual): if expected == actual: return True, "OK" msg = [] ver_exp = expected[-8:].rstrip() ver_act = actual[-8:].rstrip() if expected[:-8] != actual[:-8]: msg.append("Password mismatch") if ver_exp != ver_act: msg.append("asterisk_mbox version mismatch. Client: '" + ver_act + "', Server: '" + ver_exp + "'") return False, ". ".join(msg)
module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier identifier block return_statement expression_list true string string_start string_content string_end expression_statement assignment identifier list expression_statement assignment identifier call attribute subscript identifier slice unary_operator integer identifier argument_list expression_statement assignment identifier call attribute subscript identifier slice unary_operator integer identifier argument_list if_statement comparison_operator subscript identifier slice unary_operator integer subscript identifier slice unary_operator integer block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list binary_operator binary_operator binary_operator binary_operator string string_start string_content string_end identifier string string_start string_content string_end identifier string string_start string_content string_end return_statement expression_list false call attribute string string_start string_content string_end identifier argument_list identifier
Compare two 64byte encoded passwords.
def parse_declarations(self, declarations): declarations = self.declaration_re.findall(declarations) return dict(declarations)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier return_statement call identifier argument_list identifier
parse a css declaration list
def capture(command, input=None, cwd=None, shell=False, raiseOnError=False): proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd, shell=shell, universal_newlines=True) (stdout, stderr) = proc.communicate(input) if raiseOnError == True and proc.returncode != 0: raise Exception( 'child process ' + str(command) + ' failed with exit code ' + str(proc.returncode) + '\nstdout: "' + stdout + '"' + '\nstderr: "' + stderr + '"' ) return CommandOutput(proc.returncode, stdout, stderr)
module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none default_parameter identifier false default_parameter identifier false block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier true expression_statement assignment tuple_pattern identifier identifier call attribute identifier identifier argument_list identifier if_statement boolean_operator comparison_operator identifier true comparison_operator attribute identifier identifier integer block raise_statement call identifier argument_list binary_operator binary_operator binary_operator binary_operator binary_operator binary_operator binary_operator binary_operator binary_operator string string_start string_content string_end call identifier argument_list identifier string string_start string_content string_end call identifier argument_list attribute identifier identifier string string_start string_content escape_sequence string_end identifier string string_start string_content string_end string string_start string_content escape_sequence string_end identifier string string_start string_content string_end return_statement call identifier argument_list attribute identifier identifier identifier identifier
Executes a child process and captures its output
def insert_draft_child(self, child_pid): if child_pid.status != PIDStatus.RESERVED: raise PIDRelationConsistencyError( "Draft child should have status 'RESERVED'") if not self.draft_child: with db.session.begin_nested(): super(PIDNodeVersioning, self).insert_child(child_pid, index=-1) else: raise PIDRelationConsistencyError( "Draft child already exists for this relation: {0}".format( self.draft_child))
module function_definition identifier parameters identifier identifier block if_statement comparison_operator attribute identifier identifier attribute identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end if_statement not_operator attribute identifier identifier block with_statement with_clause with_item call attribute attribute identifier identifier identifier argument_list block expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list identifier keyword_argument identifier unary_operator integer else_clause block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier
Insert a draft child to versioning.
def prune(manager: Manager): nodes_to_delete = [ node for node in tqdm(manager.session.query(Node), total=manager.count_nodes()) if not node.networks ] manager.session.delete(nodes_to_delete) manager.session.commit()
module function_definition identifier parameters typed_parameter identifier type identifier block expression_statement assignment identifier list_comprehension identifier for_in_clause identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier call attribute identifier identifier argument_list if_clause not_operator attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list
Prune nodes not belonging to any edges.
def def_linear(fun): defjvp_argnum(fun, lambda argnum, g, ans, args, kwargs: fun(*subval(args, argnum, g), **kwargs))
module function_definition identifier parameters identifier block expression_statement call identifier argument_list identifier lambda lambda_parameters identifier identifier identifier identifier identifier call identifier argument_list list_splat call identifier argument_list identifier identifier identifier dictionary_splat identifier
Flags that a function is linear wrt all args
def check_url_does_not_exists(form, field): if field.data != field.object_data and Reuse.url_exists(field.data): raise validators.ValidationError(_('This URL is already registered'))
module function_definition identifier parameters identifier identifier block if_statement boolean_operator comparison_operator attribute identifier identifier attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier block raise_statement call attribute identifier identifier argument_list call identifier argument_list string string_start string_content string_end
Ensure a reuse URL is not yet registered
def model_reaction_limits(model): for reaction in sorted(model.reactions, key=lambda r: r.id): equation = reaction.properties.get('equation') if equation is None: continue lower_default, upper_default = None, None if model.default_flux_limit is not None: if equation.direction.reverse: lower_default = -model.default_flux_limit else: lower_default = 0.0 if equation.direction.forward: upper_default = model.default_flux_limit else: upper_default = 0.0 lower_flux, upper_flux = None, None if reaction.id in model.limits: _, lower, upper = model.limits[reaction.id] lower_flux = _get_output_limit(lower, lower_default) upper_flux = _get_output_limit(upper, upper_default) if lower_flux is not None or upper_flux is not None: d = OrderedDict([('reaction', reaction.id)]) d.update(_generate_limit_items(lower_flux, upper_flux)) yield d
module function_definition identifier parameters identifier block for_statement identifier call identifier argument_list attribute identifier identifier keyword_argument identifier lambda lambda_parameters identifier attribute identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier none block continue_statement expression_statement assignment pattern_list identifier identifier expression_list none none if_statement comparison_operator attribute identifier identifier none block if_statement attribute attribute identifier identifier identifier block expression_statement assignment identifier unary_operator attribute identifier identifier else_clause block expression_statement assignment identifier float if_statement attribute attribute identifier identifier identifier block expression_statement assignment identifier attribute identifier identifier else_clause block expression_statement assignment identifier float expression_statement assignment pattern_list identifier identifier expression_list none none if_statement comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement assignment pattern_list identifier identifier identifier subscript attribute identifier identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier if_statement boolean_operator comparison_operator identifier none comparison_operator identifier none block expression_statement assignment identifier call identifier argument_list list tuple string string_start string_content string_end attribute identifier identifier expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier identifier expression_statement yield identifier
Yield model reaction limits as YAML dicts.
def open_links(self): if self._is_open: raise Exception('Already opened') try: self.parallel_safe(lambda scf: scf.open_link()) self._is_open = True except Exception as e: self.close_links() raise e
module function_definition identifier parameters identifier block if_statement attribute identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end try_statement block expression_statement call attribute identifier identifier argument_list lambda lambda_parameters identifier call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier true except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list raise_statement identifier
Open links to all individuals in the swarm
def _dyn_loader(self, module: str, kwargs: str): package_directory: str = os.path.dirname(os.path.abspath(__file__)) modules: str = package_directory + "/modules" module = module + ".py" if module not in os.listdir(modules): raise Exception("Module %s is not valid" % module) module_name: str = module[:-3] import_path: str = "%s.%s" % (self.MODULE_PATH, module_name) imported = import_module(import_path) obj = getattr(imported, 'Module') return obj(**kwargs)
module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_parameter identifier type identifier block expression_statement assignment identifier type identifier call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier type identifier binary_operator identifier string string_start string_content string_end expression_statement assignment identifier binary_operator identifier string string_start string_content string_end if_statement comparison_operator identifier call attribute identifier identifier argument_list identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement assignment identifier type identifier subscript identifier slice unary_operator integer expression_statement assignment identifier type identifier binary_operator string string_start string_content string_end tuple attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end return_statement call identifier argument_list dictionary_splat identifier
Dynamically load a specific module instance.
def handle_json_GET_routes(self, params): schedule = self.server.schedule result = [] for r in schedule.GetRouteList(): result.append( (r.route_id, r.route_short_name, r.route_long_name) ) result.sort(key = lambda x: x[1:3]) return result
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier list for_statement identifier call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list tuple attribute identifier identifier attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list keyword_argument identifier lambda lambda_parameters identifier subscript identifier slice integer integer return_statement identifier
Return a list of all routes.
def instantiate_database(sqlite_file='ftwj.sqlite'): table_name = 'ftw' col1 = 'rule_id' col1_t = 'INTEGER' col2 = 'test_id' col2_t = 'STRING' col3 = 'time_start' col3_t = 'TEXT' col4 = 'time_end' col4_t = 'TEXT' col5 = 'response_blob' col5_t = 'TEXT' col6 = 'status_code' col6_t = 'INTEGER' col7 = 'stage' col7_t = 'INTEGER' conn = sqlite3.connect(sqlite_file) cur = conn.cursor() q = 'CREATE TABLE {tn}({col1} {col1_t},{col2} {col2_t},{col3} {col3_t},{col4} {col4_t},{col5} {col5_t},{col6} {col6_t},{col7} {col7_t})'.format( tn=table_name, col1=col1, col1_t=col1_t, col2=col2, col2_t=col2_t, col3=col3, col3_t=col3_t, col4=col4, col4_t=col4_t, col5=col5, col5_t=col5_t, col6=col6, col6_t=col6_t, col7=col7, col7_t=col7_t) cur.execute(q) conn.commit() conn.close()
module function_definition identifier parameters default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier 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 keyword_argument identifier 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 keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list
Create journal database for FTW runs
def optimize_spot_bid(ctx, instance_type, spot_bid): spot_history = _get_spot_history(ctx, instance_type) if spot_history: _check_spot_bid(spot_bid, spot_history) zones = ctx.ec2.get_all_zones() most_stable_zone = choose_spot_zone(zones, spot_bid, spot_history) logger.debug("Placing spot instances in zone %s.", most_stable_zone) return most_stable_zone
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier if_statement identifier block expression_statement call identifier argument_list identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call identifier argument_list identifier identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier return_statement identifier
Check whether the bid is sane and makes an effort to place the instance in a sensible zone.
def floor_point(self): floor_point = self.centroid floor_point[1] = self.v[:, 1].min() return floor_point
module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment subscript identifier integer call attribute subscript attribute identifier identifier slice integer identifier argument_list return_statement identifier
Return the point on the floor that lies below the centroid.
def _add_unqualified_edge(self, source: Node, target: Node, key: str, bel: str, data: EdgeData) -> Edge: return self.get_or_create_edge( source=source, target=target, relation=data[RELATION], bel=bel, sha512=key, data=data, )
module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_parameter identifier type identifier typed_parameter identifier type identifier typed_parameter identifier type identifier typed_parameter identifier type identifier type identifier block return_statement call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier subscript identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier
Add an unqualified edge to the network.
def build_package_data(self): for package, src_dir, build_dir, filenames in self.data_files: for filename in filenames: target = os.path.join(build_dir, filename) self.mkpath(os.path.dirname(target)) srcfile = os.path.join(src_dir, filename) outf, copied = self.copy_file(srcfile, target) srcfile = os.path.abspath(srcfile) if (copied and srcfile in self.distribution.convert_2to3_doctests): self.__doctests_2to3.append(outf)
module function_definition identifier parameters identifier block for_statement pattern_list identifier identifier identifier identifier attribute identifier identifier block for_statement identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier if_statement parenthesized_expression boolean_operator identifier comparison_operator identifier attribute attribute identifier identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier
Copy data files into build directory
def _get_cookie_referrer_host(self): referer = self._original_request.fields.get('Referer') if referer: return URLInfo.parse(referer).hostname else: return None
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end if_statement identifier block return_statement attribute call attribute identifier identifier argument_list identifier identifier else_clause block return_statement none
Return the referrer hostname.
def pclink(self, parent, child): if parent._children is None: parent._children = set() if child._parents is None: child._parents = set() parent._children.add(child) child._parents.add(parent)
module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier call identifier argument_list if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier call identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier
Create a parent-child relationship.
def distancePointToPolygon(point, polygon, perpendicular=False): p = point s = polygon minDist = None for i in range(0, len(s) - 1): dist = distancePointToLine(p, s[i], s[i + 1], perpendicular) if dist == INVALID_DISTANCE and perpendicular and i != 0: dist = distance(point, s[i]) if dist != INVALID_DISTANCE: if minDist is None or dist < minDist: minDist = dist if minDist is not None: return minDist else: return INVALID_DISTANCE
module function_definition identifier parameters identifier identifier default_parameter identifier false block expression_statement assignment identifier identifier expression_statement assignment identifier identifier expression_statement assignment identifier none for_statement identifier call identifier argument_list integer binary_operator call identifier argument_list identifier integer block expression_statement assignment identifier call identifier argument_list identifier subscript identifier identifier subscript identifier binary_operator identifier integer identifier if_statement boolean_operator boolean_operator comparison_operator identifier identifier identifier comparison_operator identifier integer block expression_statement assignment identifier call identifier argument_list identifier subscript identifier identifier if_statement comparison_operator identifier identifier block if_statement boolean_operator comparison_operator identifier none comparison_operator identifier identifier block expression_statement assignment identifier identifier if_statement comparison_operator identifier none block return_statement identifier else_clause block return_statement identifier
Return the minimum distance between point and polygon
def register_event(self, event_name, event_level, message): self.events[event_name] = (event_level, message)
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment subscript attribute identifier identifier identifier tuple identifier identifier
Registers an event so that it can be logged later.
def upload(resume, message): data_config = DataConfigManager.get_config() if not upload_is_resumable(data_config) or not opt_to_resume(resume): abort_previous_upload(data_config) access_token = AuthConfigManager.get_access_token() initialize_new_upload(data_config, access_token, message) complete_upload(data_config)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement boolean_operator not_operator call identifier argument_list identifier not_operator call identifier argument_list identifier block expression_statement call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call identifier argument_list identifier identifier identifier expression_statement call identifier argument_list identifier
Upload files in the current dir to FloydHub.
def fetch_and_parse(url, bodyLines): pageHtml = fetch_page(url) return parse(url, pageHtml, bodyLines)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier return_statement call identifier argument_list identifier identifier identifier
Takes a url, and returns a dictionary of data with 'bodyLines' lines
def RetryQuestion(question_text, output_re="", default_val=None): while True: if default_val is not None: new_text = "%s [%s]: " % (question_text, default_val) else: new_text = "%s: " % question_text output = builtins.input(new_text) or str(default_val) output = output.strip() if not output_re or re.match(output_re, output): break else: print("Invalid input, must match %s" % output_re) return output
module function_definition identifier parameters identifier default_parameter identifier string string_start string_end default_parameter identifier none block while_statement true block if_statement comparison_operator identifier none block expression_statement assignment identifier binary_operator string string_start string_content string_end tuple identifier identifier else_clause block expression_statement assignment identifier binary_operator string string_start string_content string_end identifier expression_statement assignment identifier boolean_operator call attribute identifier identifier argument_list identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list if_statement boolean_operator not_operator identifier call attribute identifier identifier argument_list identifier identifier block break_statement else_clause block expression_statement call identifier argument_list binary_operator string string_start string_content string_end identifier return_statement identifier
Continually ask a question until the output_re is matched.
def to_json(payload, mode="history"): for key, val in six.iteritems(payload): if isinstance(val, dict): payload[key] = to_json(val, mode) else: payload[key] = val_to_json( key, val, mode, step=payload.get("_step")) return payload
module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block for_statement pattern_list identifier identifier call attribute identifier identifier argument_list identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment subscript identifier identifier call identifier argument_list identifier identifier else_clause block expression_statement assignment subscript identifier identifier call identifier argument_list identifier identifier identifier keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end return_statement identifier
Converts all keys in a potentially nested array into their JSON representation
def publish(self, name, value, raw_value=None, precision=0, metric_type='GAUGE', instance=None): if self.config['metrics_whitelist']: if not self.config['metrics_whitelist'].match(name): return elif self.config['metrics_blacklist']: if self.config['metrics_blacklist'].match(name): return path = self.get_metric_path(name, instance=instance) ttl = float(self.config['interval']) * float( self.config['ttl_multiplier']) try: metric = Metric(path, value, raw_value=raw_value, timestamp=None, precision=precision, host=self.get_hostname(), metric_type=metric_type, ttl=ttl) except DiamondException: self.log.error(('Error when creating new Metric: path=%r, ' 'value=%r'), path, value) raise self.publish_metric(metric)
module function_definition identifier parameters identifier identifier identifier default_parameter identifier none default_parameter identifier integer default_parameter identifier string string_start string_content string_end default_parameter identifier none block if_statement subscript attribute identifier identifier string string_start string_content string_end block if_statement not_operator call attribute subscript attribute identifier identifier string string_start string_content string_end identifier argument_list identifier block return_statement elif_clause subscript attribute identifier identifier string string_start string_content string_end block if_statement call attribute subscript attribute identifier identifier string string_start string_content string_end identifier argument_list identifier block return_statement expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier expression_statement assignment identifier binary_operator call identifier argument_list subscript attribute identifier identifier string string_start string_content string_end call identifier argument_list subscript attribute identifier identifier string string_start string_content string_end try_statement block expression_statement assignment identifier call identifier argument_list identifier identifier keyword_argument identifier identifier keyword_argument identifier none keyword_argument identifier identifier keyword_argument identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier except_clause identifier block expression_statement call attribute attribute identifier identifier identifier argument_list parenthesized_expression concatenated_string string string_start string_content string_end string string_start string_content string_end identifier identifier raise_statement expression_statement call attribute identifier identifier argument_list identifier
Publish a metric with the given name
def _extract(archive, compression, cmd, format, verbosity, outdir): targetname = util.get_single_outfile(outdir, archive) try: with lzma.LZMAFile(archive, **_get_lzma_options(format)) as lzmafile: with open(targetname, 'wb') as targetfile: data = lzmafile.read(READ_SIZE_BYTES) while data: targetfile.write(data) data = lzmafile.read(READ_SIZE_BYTES) except Exception as err: msg = "error extracting %s to %s: %s" % (archive, targetname, err) raise util.PatoolError(msg) return None
module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier try_statement block with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list identifier dictionary_splat call identifier argument_list identifier as_pattern_target identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier while_statement identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end tuple identifier identifier identifier raise_statement call attribute identifier identifier argument_list identifier return_statement none
Extract an LZMA or XZ archive with the lzma Python module.
def _poll_queue(self): while not self._stop_event.is_set(): reply = self.run_job() self.send(reply) if self.queue: continue time.sleep(0.02)
module function_definition identifier parameters identifier block while_statement not_operator call attribute attribute identifier identifier identifier argument_list block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier if_statement attribute identifier identifier block continue_statement expression_statement call attribute identifier identifier argument_list float
Poll the queue for work.
def probe(gandi, resource, enable, disable, test, host, interval, http_method, http_response, threshold, timeout, url, window): result = gandi.webacc.probe(resource, enable, disable, test, host, interval, http_method, http_response, threshold, timeout, url, window) output_keys = ['status', 'timeout'] output_generic(gandi, result, output_keys, justify=14) return result
module function_definition identifier parameters identifier identifier identifier identifier identifier identifier identifier identifier identifier identifier identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier identifier identifier identifier identifier identifier identifier identifier identifier identifier identifier expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end expression_statement call identifier argument_list identifier identifier identifier keyword_argument identifier integer return_statement identifier
Manage a probe for a webaccelerator
def increment(self, batch_size): self.example_count += batch_size self.example_total += batch_size if self.log_unit == "seconds": self.unit_count = int(self.timer.elapsed()) self.unit_total = int(self.timer.total_elapsed()) elif self.log_unit == "examples": self.unit_count = self.example_count self.unit_total = self.example_total elif self.log_unit == "batches": self.unit_count += 1 self.unit_total += 1 elif self.log_unit == "epochs": if self.example_count >= self.epoch_size: self.unit_count += 1 self.unit_total += 1 else: raise Exception(f"Unrecognized log_unit: {self.log_unit}")
module function_definition identifier parameters identifier identifier block expression_statement augmented_assignment attribute identifier identifier identifier expression_statement augmented_assignment attribute identifier identifier identifier if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement assignment attribute identifier identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list elif_clause comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier elif_clause comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement augmented_assignment attribute identifier identifier integer expression_statement augmented_assignment attribute identifier identifier integer elif_clause comparison_operator attribute identifier identifier string string_start string_content string_end block if_statement comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement augmented_assignment attribute identifier identifier integer expression_statement augmented_assignment attribute identifier identifier integer else_clause block raise_statement call identifier argument_list string string_start string_content interpolation attribute identifier identifier string_end
Update the total and relative unit counts
def _create_tmpfile(cls, status): tmpl = string.Template(cls._TMPFILE_PATTERN) filename = tmpl.substitute( id=status.mapreduce_id, shard=status.shard, random=random.getrandbits(cls._RAND_BITS)) return cls._open_file(status.writer_spec, filename, use_tmp_bucket=True)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier call attribute identifier identifier argument_list attribute identifier identifier return_statement call attribute identifier identifier argument_list attribute identifier identifier identifier keyword_argument identifier true
Creates a new random-named tmpfile.