text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def parse_fields(attributes): """Parse model fields.""" return tuple(field.bind_name(name) for name, field in six.iteritems(attributes) if isinstance(field, fields.Field))
[ "def", "parse_fields", "(", "attributes", ")", ":", "return", "tuple", "(", "field", ".", "bind_name", "(", "name", ")", "for", "name", ",", "field", "in", "six", ".", "iteritems", "(", "attributes", ")", "if", "isinstance", "(", "field", ",", "fields", ...
45
10.8
def format_message_type(message_type): """ Get printable version for message type :param message_type: Message type :type message_type: int :return: Printable version :rtype: str """ if message_type == MsgType.NOT_SET: return "NOT_SET" elif message_type == MsgType.ACK: ...
[ "def", "format_message_type", "(", "message_type", ")", ":", "if", "message_type", "==", "MsgType", ".", "NOT_SET", ":", "return", "\"NOT_SET\"", "elif", "message_type", "==", "MsgType", ".", "ACK", ":", "return", "\"ACK\"", "elif", "message_type", "==", "MsgTyp...
27.2
10.4
def valid_host(host): """ check valid hostname """ for part in host.split("."): if not _valid_host_part.match(part): return False return True
[ "def", "valid_host", "(", "host", ")", ":", "for", "part", "in", "host", ".", "split", "(", "\".\"", ")", ":", "if", "not", "_valid_host_part", ".", "match", "(", "part", ")", ":", "return", "False", "return", "True" ]
24
16
def set_policy_attack_strength(self, policy_ids, attack_strength): """Set the attack strength for the given policies.""" for policy_id in policy_ids: self.logger.debug('Setting strength for policy {0} to {1}'.format(policy_id, attack_strength)) result = self.zap.ascan.set_policy_...
[ "def", "set_policy_attack_strength", "(", "self", ",", "policy_ids", ",", "attack_strength", ")", ":", "for", "policy_id", "in", "policy_ids", ":", "self", ".", "logger", ".", "debug", "(", "'Setting strength for policy {0} to {1}'", ".", "format", "(", "policy_id",...
71.285714
32.285714
def invoke_shell(self): """ Request an interactive shell session on this channel. If the server allows it, the channel will then be directly connected to the stdin, stdout, and stderr of the shell. Normally you would call `get_pty` before this, in which case the ...
[ "def", "invoke_shell", "(", "self", ")", ":", "if", "self", ".", "closed", "or", "self", ".", "eof_received", "or", "self", ".", "eof_sent", "or", "not", "self", ".", "active", ":", "raise", "SSHException", "(", "'Channel is not open'", ")", "m", "=", "M...
41.692308
19.461538
def delete_file(self, path, prefixed_path, source_storage): """ Override delete_file to skip modified time and exists lookups. """ if not self.collectfast_enabled: return super(Command, self).delete_file( path, prefixed_path, source_storage) if not sel...
[ "def", "delete_file", "(", "self", ",", "path", ",", "prefixed_path", ",", "source_storage", ")", ":", "if", "not", "self", ".", "collectfast_enabled", ":", "return", "super", "(", "Command", ",", "self", ")", ".", "delete_file", "(", "path", ",", "prefixe...
38.538462
12.230769
def _AbandonInactiveProcessingTasks(self): """Marks processing tasks that exceed the inactive time as abandoned. This method does not lock the manager and should be called by a method holding the manager lock. """ if self._tasks_processing: inactive_time = time.time() - self._TASK_INACTIVE_TI...
[ "def", "_AbandonInactiveProcessingTasks", "(", "self", ")", ":", "if", "self", ".", "_tasks_processing", ":", "inactive_time", "=", "time", ".", "time", "(", ")", "-", "self", ".", "_TASK_INACTIVE_TIME", "inactive_time", "=", "int", "(", "inactive_time", "*", ...
42.833333
20
def range_return(request, items): """ Determine what range of objects to return. Will check fot both `Range` and `X-Range` headers in the request and set both `Content-Range` and 'X-Content-Range' headers. :rtype: list """ if ('Range' in request.headers): range = parse_range_header...
[ "def", "range_return", "(", "request", ",", "items", ")", ":", "if", "(", "'Range'", "in", "request", ".", "headers", ")", ":", "range", "=", "parse_range_header", "(", "request", ".", "headers", "[", "'Range'", "]", ")", "elif", "'X-Range'", "in", "requ...
39.419355
20.064516
def plotSegmentationResults(flags_ind, flags_ind_gt, class_names, mt_step, ONLY_EVALUATE=False): ''' This function plots statistics on the classification-segmentation results produced either by the fix-sized supervised method or the HMM method. It also computes the overall accuracy achieved by the respectiv...
[ "def", "plotSegmentationResults", "(", "flags_ind", ",", "flags_ind_gt", ",", "class_names", ",", "mt_step", ",", "ONLY_EVALUATE", "=", "False", ")", ":", "flags", "=", "[", "class_names", "[", "int", "(", "f", ")", "]", "for", "f", "in", "flags_ind", "]",...
42.485294
21.808824
def _load_int(self): """Load internal data from file and return it.""" values = numpy.fromfile(self.filepath_int) if self.NDIM > 0: values = values.reshape(self.seriesshape) return values
[ "def", "_load_int", "(", "self", ")", ":", "values", "=", "numpy", ".", "fromfile", "(", "self", ".", "filepath_int", ")", "if", "self", ".", "NDIM", ">", "0", ":", "values", "=", "values", ".", "reshape", "(", "self", ".", "seriesshape", ")", "retur...
37.666667
12.833333
def add_task_db(self, task, force=True): '''向数据库中写入一个新的任务记录, 并返回它的fid''' sql = '''INSERT INTO upload ( name, source_path, path, size, curr_size, state, state_name, human_size, percent, tooltip, threshold) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)''' req = self.cursor.execu...
[ "def", "add_task_db", "(", "self", ",", "task", ",", "force", "=", "True", ")", ":", "sql", "=", "'''INSERT INTO upload (\n name, source_path, path, size, curr_size, state, state_name,\n human_size, percent, tooltip, threshold)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?,...
43.666667
7.666667
def generate_mask(cls, mask_key, data): """ Mask data. :Parameters: mask_key: byte string 4 byte string(byte), e.g. '\x10\xc6\xc4\x16' data: str data to mask """ # Masking of WebSocket traffic from client to server is required ...
[ "def", "generate_mask", "(", "cls", ",", "mask_key", ",", "data", ")", ":", "# Masking of WebSocket traffic from client to server is required", "# because of the unlikely chance that malicious code could cause", "# some broken proxies to do the wrong thing and use this as an", "# attack of...
33.551724
20.758621
def prepare_sort_key(self): ''' Triggered by view_function._sort_converters when our sort key should be created. This can't be called in the constructor because Django models might not be ready yet. ''' if isinstance(self.convert_type, str): try: app_n...
[ "def", "prepare_sort_key", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "convert_type", ",", "str", ")", ":", "try", ":", "app_name", ",", "model_name", "=", "self", ".", "convert_type", ".", "split", "(", "'.'", ")", "except", "ValueErro...
57.611111
36.833333
def got_response(self): """ :returns: Whether or not the :class:`~.MessageThread`. has received a response. """ return any(message.sender != self.initiator for message in self.messages)
[ "def", "got_response", "(", "self", ")", ":", "return", "any", "(", "message", ".", "sender", "!=", "self", ".", "initiator", "for", "message", "in", "self", ".", "messages", ")" ]
35.428571
12.285714
def _validate_slices_form_uniform_grid(slice_datasets): ''' Perform various data checks to ensure that the list of slices form a evenly-spaced grid of data. Some of these checks are probably not required if the data follows the DICOM specification, however it seems pertinent to check anyway. '''...
[ "def", "_validate_slices_form_uniform_grid", "(", "slice_datasets", ")", ":", "invariant_properties", "=", "[", "'Modality'", ",", "'SOPClassUID'", ",", "'SeriesInstanceUID'", ",", "'Rows'", ",", "'Columns'", ",", "'PixelSpacing'", ",", "'PixelRepresentation'", ",", "'B...
33.428571
23.714286
def input_option(message, options="yn", error_message=None): """ Reads an option from the screen, with a specified prompt. Keeps asking until a valid option is sent by the user. """ def _valid(character): if character not in options: print(error_message % character) retur...
[ "def", "input_option", "(", "message", ",", "options", "=", "\"yn\"", ",", "error_message", "=", "None", ")", ":", "def", "_valid", "(", "character", ")", ":", "if", "character", "not", "in", "options", ":", "print", "(", "error_message", "%", "character",...
42.888889
14.222222
def rc2_cbc_pkcs5_encrypt(key, data, iv): """ Encrypts plaintext using RC2 with a 64 bit key :param key: The encryption key - a byte string 8 bytes long :param data: The plaintext - a byte string :param iv: The 8-byte initialization vector to use - a byte string - set as N...
[ "def", "rc2_cbc_pkcs5_encrypt", "(", "key", ",", "data", ",", "iv", ")", ":", "if", "len", "(", "key", ")", "<", "5", "or", "len", "(", "key", ")", ">", "16", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n key must be 5 to 16 byt...
27.380952
23.047619
def get_identities(self, item): """ Return the identities from an item """ # All identities are in the post stream # The first post is the question. Next replies posts = item['data']['post_stream']['posts'] for post in posts: user = self.get_sh_identity(post) ...
[ "def", "get_identities", "(", "self", ",", "item", ")", ":", "# All identities are in the post stream", "# The first post is the question. Next replies", "posts", "=", "item", "[", "'data'", "]", "[", "'post_stream'", "]", "[", "'posts'", "]", "for", "post", "in", "...
29.727273
18.090909
def create_config_map(self, name, data): """ Create an ConfigMap object on the server Raises exception on error :param name: str, name of configMap :param data: dict, dictionary of data to be stored :returns: ConfigMapResponse containing the ConfigMap with name and data...
[ "def", "create_config_map", "(", "self", ",", "name", ",", "data", ")", ":", "config_data_file", "=", "os", ".", "path", ".", "join", "(", "self", ".", "os_conf", ".", "get_build_json_store", "(", ")", ",", "'config_map.json'", ")", "with", "open", "(", ...
38.363636
15.090909
def mkdir(dir_path): # type: (AnyStr) -> None """Make directory if not existed""" if not os.path.isdir(dir_path) or not os.path.exists(dir_path): os.makedirs(dir_path)
[ "def", "mkdir", "(", "dir_path", ")", ":", "# type: (AnyStr) -> None", "if", "not", "os", ".", "path", ".", "isdir", "(", "dir_path", ")", "or", "not", "os", ".", "path", ".", "exists", "(", "dir_path", ")", ":", "os", ".", "makedirs", "(", "dir_path",...
39.8
13.2
def get_storage(self, hex_contract_address: str, hex_key: str, is_full: bool = False) -> str: """ This interface is used to get the corresponding stored value based on hexadecimal contract address and stored key. :param hex_contract_address: hexadecimal contract address. :param ...
[ "def", "get_storage", "(", "self", ",", "hex_contract_address", ":", "str", ",", "hex_key", ":", "str", ",", "is_full", ":", "bool", "=", "False", ")", "->", "str", ":", "payload", "=", "self", ".", "generate_json_rpc_payload", "(", "RpcMethod", ".", "GET_...
44.8
21.733333
def p_expr_function(p): 'expr : FUNCTION is_reference LPAREN parameter_list RPAREN lexical_vars LBRACE inner_statement_list RBRACE' p[0] = ast.Closure(p[4], p[6], p[8], p[2], lineno=p.lineno(1))
[ "def", "p_expr_function", "(", "p", ")", ":", "p", "[", "0", "]", "=", "ast", ".", "Closure", "(", "p", "[", "4", "]", ",", "p", "[", "6", "]", ",", "p", "[", "8", "]", ",", "p", "[", "2", "]", ",", "lineno", "=", "p", ".", "lineno", "(...
66.666667
38
def finddives2(depths, min_dive_thresh=10): '''Find dives in depth data below a minimum dive threshold Args ---- depths: ndarray Datalogger depth measurements min_dive_thresh: float Minimum depth threshold for which to classify a dive Returns ------- dives: ndarray ...
[ "def", "finddives2", "(", "depths", ",", "min_dive_thresh", "=", "10", ")", ":", "import", "numpy", "import", "pandas", "from", ".", "import", "utils", "# Get start and stop indices for each dive above `min_dive_thresh`", "condition", "=", "depths", ">", "min_dive_thres...
32.775
22.05
def stop_replace(self, accountID, orderID, **kwargs): """ Shortcut to replace a pending Stop Order in an Account Args: accountID : The ID of the Account orderID : The ID of the Stop Order to replace kwargs : The arguments to create a StopOrderRequest ...
[ "def", "stop_replace", "(", "self", ",", "accountID", ",", "orderID", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "replace", "(", "accountID", ",", "orderID", ",", "order", "=", "StopOrderRequest", "(", "*", "*", "kwargs", ")", ")" ]
30.5
19.166667
def encode_zarr_variable(var, needs_copy=True, name=None): """ Converts an Variable into an Variable which follows some of the CF conventions: - Nans are masked using _FillValue (or the deprecated missing_value) - Rescaling via: scale_factor and add_offset - datetimes are converted ...
[ "def", "encode_zarr_variable", "(", "var", ",", "needs_copy", "=", "True", ",", "name", "=", "None", ")", ":", "var", "=", "conventions", ".", "encode_cf_variable", "(", "var", ",", "name", "=", "name", ")", "# zarr allows unicode, but not variable-length strings,...
33.322581
22.741935
def generate_new_address(coin_symbol='btc', api_key=None): ''' Takes a coin_symbol and returns a new address with it's public and private keys. This method will create the address server side, which is inherently insecure and should only be used for testing. If you want to create a secure address clie...
[ "def", "generate_new_address", "(", "coin_symbol", "=", "'btc'", ",", "api_key", "=", "None", ")", ":", "assert", "api_key", ",", "'api_key required'", "assert", "is_valid_coin_symbol", "(", "coin_symbol", ")", "if", "coin_symbol", "not", "in", "(", "'btc-testnet'...
35.766667
26.366667
def install(config): # pragma: no cover """Install user's SSH public key to the local system.""" client = Client() client.prepare_connection() key_api = API(client) key_api.install()
[ "def", "install", "(", "config", ")", ":", "# pragma: no cover", "client", "=", "Client", "(", ")", "client", ".", "prepare_connection", "(", ")", "key_api", "=", "API", "(", "client", ")", "key_api", ".", "install", "(", ")" ]
36.333333
7.666667
def has_been_completed_by(poll, user): """ This will return a boolean indicating if the passed user has already voted in the given poll. Usage:: {% if poll|has_been_completed_by:user %}...{% endif %} """ user_votes = TopicPollVote.objects.filter( poll_option__poll=poll) if ...
[ "def", "has_been_completed_by", "(", "poll", ",", "user", ")", ":", "user_votes", "=", "TopicPollVote", ".", "objects", ".", "filter", "(", "poll_option__poll", "=", "poll", ")", "if", "user", ".", "is_anonymous", ":", "forum_key", "=", "get_anonymous_user_forum...
34.294118
17.588235
def _get_all_offsets(self, offset_ns=None): """ returns all token offsets of this document as a generator of (token node ID str, character onset int, character offset int) tuples. Parameters ---------- offset_ns : str or None The namespace from which the offs...
[ "def", "_get_all_offsets", "(", "self", ",", "offset_ns", "=", "None", ")", ":", "for", "token_id", ",", "_token_str", "in", "self", ".", "get_tokens", "(", ")", ":", "onset", "=", "self", ".", "node", "[", "token_id", "]", "[", "'{0}:{1}'", ".", "form...
42.26087
22.695652
def marshall(values): """ Marshall a `dict` into something DynamoDB likes. :param dict values: The values to marshall :rtype: dict :raises ValueError: if an unsupported type is encountered Return the values in a nested dict structure that is required for writing the values to DynamoDB. ...
[ "def", "marshall", "(", "values", ")", ":", "serialized", "=", "{", "}", "for", "key", "in", "values", ":", "serialized", "[", "key", "]", "=", "_marshall_value", "(", "values", "[", "key", "]", ")", "return", "serialized" ]
26.875
19.25
def enable_servicegroup_svc_notifications(self, servicegroup): """Enable service notifications for a servicegroup Format of the line that triggers function call:: ENABLE_SERVICEGROUP_SVC_NOTIFICATIONS;<servicegroup_name> :param servicegroup: servicegroup to enable :type service...
[ "def", "enable_servicegroup_svc_notifications", "(", "self", ",", "servicegroup", ")", ":", "for", "service_id", "in", "servicegroup", ".", "get_services", "(", ")", ":", "self", ".", "enable_svc_notifications", "(", "self", ".", "daemon", ".", "services", "[", ...
43.5
20.916667
def _get_webapi_requests(self): """Update headers of webapi for Requests.""" headers = { 'Accept': '*/*', 'Accept-Language': 'zh-CN,zh;q=0.8,gl;q=0.6,zh-TW;q=0.4', 'Connection': 'keep-alive', 'Content-Type': ...
[ "def", "_get_webapi_requests", "(", "self", ")", ":", "headers", "=", "{", "'Accept'", ":", "'*/*'", ",", "'Accept-Language'", ":", "'zh-CN,zh;q=0.8,gl;q=0.6,zh-TW;q=0.4'", ",", "'Connection'", ":", "'keep-alive'", ",", "'Content-Type'", ":", "'application/x-www-form-ur...
32.904762
18.809524
def add_group_member(self, grp_name, user): """ Add the given user to the named group. Both group and user must already exist for this to succeed. Args: name (string): Name of group. user_name (string): User to add to group. Raises: requests...
[ "def", "add_group_member", "(", "self", ",", "grp_name", ",", "user", ")", ":", "self", ".", "project_service", ".", "set_auth", "(", "self", ".", "_token_project", ")", "self", ".", "project_service", ".", "add_group_member", "(", "grp_name", ",", "user", "...
30.733333
17.533333
def build_param_schema(schema, param_type): """Turn a swagger endpoint schema into an equivalent one to validate our request. As an example, this would take this swagger schema: { "paramType": "query", "name": "query", "description": "Location to query", ...
[ "def", "build_param_schema", "(", "schema", ",", "param_type", ")", ":", "properties", "=", "filter_params_by_type", "(", "schema", ",", "param_type", ")", "if", "not", "properties", ":", "return", "# Generate a jsonschema that describes the set of all query parameters. We"...
33.631579
19.763158
def pivot(self, index, **kwargs): """ Pivots a dataframe """ try: df = self._pivot(index, **kwargs) return pd.pivot_table(self.df, index=kwargs["index"], **kwargs) """if df is None: self.err("Can not pivot table") retur...
[ "def", "pivot", "(", "self", ",", "index", ",", "*", "*", "kwargs", ")", ":", "try", ":", "df", "=", "self", ".", "_pivot", "(", "index", ",", "*", "*", "kwargs", ")", "return", "pd", ".", "pivot_table", "(", "self", ".", "df", ",", "index", "=...
32.230769
10.384615
def renderJsonReadsSince(self, timestamp, meter): """ Simple since Time_Stamp query returned as JSON records. Args: timestamp (int): Epoch time in seconds. meter (str): 12 character meter address to query Returns: str: JSON rendered read records. ""...
[ "def", "renderJsonReadsSince", "(", "self", ",", "timestamp", ",", "meter", ")", ":", "result", "=", "\"\"", "try", ":", "connection", "=", "sqlite3", ".", "connect", "(", "self", ".", "m_connection_string", ")", "connection", ".", "row_factory", "=", "self"...
37.12
21.52
def ecfp(mol, radius=2): """Compute the Extended-Connectivity fingerprint for a molecule. :param mol: molecule object parsed from SMILES string :param radius: The number of iterations to perform. Defaults to 2 which is equivilent to ECFP4. :rtype: dictionary representing the molecular fingprint (at...
[ "def", "ecfp", "(", "mol", ",", "radius", "=", "2", ")", ":", "atom_ids", "=", "invariants", "(", "mol", ")", "fp", "=", "{", "}", "for", "i", "in", "atom_ids", ".", "values", "(", ")", ":", "fp", "[", "i", "]", "=", "fp", ".", "get", "(", ...
34.603774
21.075472
def _required_idiom(tag_name, index, notfoundmsg): """ Generate code, which make sure that `tag_name` has enoug items. Args: tag_name (str): Name of the container. index (int): Index of the item you want to obtain from container. notfoundmsg (str): Raise :class:`.UserWarning` with d...
[ "def", "_required_idiom", "(", "tag_name", ",", "index", ",", "notfoundmsg", ")", ":", "cond", "=", "\"\"", "if", "index", ">", "0", ":", "cond", "=", "\" or len(el) - 1 < %d\"", "%", "index", "tag_name", "=", "str", "(", "tag_name", ")", "output", "=", ...
34.25
21.107143
def MultiListChildren(self, urns, limit=None, age=NEWEST_TIME): """Lists bunch of directories efficiently. Args: urns: List of urns to list children. limit: Max number of children to list (NOTE: this is per urn). age: The age of the items to retrieve. Should be one of ALL_TIMES, NEWES...
[ "def", "MultiListChildren", "(", "self", ",", "urns", ",", "limit", "=", "None", ",", "age", "=", "NEWEST_TIME", ")", ":", "checked_subjects", "=", "set", "(", ")", "for", "subject", ",", "values", "in", "data_store", ".", "DB", ".", "AFF4MultiFetchChildre...
31.793103
21.137931
def convert_references_json(ref_content, soup=None): "Check for references that will not pass schema validation, fix or convert them to unknown" # Convert reference to unkonwn if still missing important values if ( (ref_content.get("type") == "other") or (ref_content.get("type") == ...
[ "def", "convert_references_json", "(", "ref_content", ",", "soup", "=", "None", ")", ":", "# Convert reference to unkonwn if still missing important values", "if", "(", "(", "ref_content", ".", "get", "(", "\"type\"", ")", "==", "\"other\"", ")", "or", "(", "ref_con...
42.142857
30.785714
def create(self, name, img_format=None, img_container_format=None, data=None, container=None, obj=None, metadata=None): """ Creates a new image with the specified name. The image data can either be supplied directly in the 'data' parameter, or it can be an image stored in the...
[ "def", "create", "(", "self", ",", "name", ",", "img_format", "=", "None", ",", "img_container_format", "=", "None", ",", "data", "=", "None", ",", "container", "=", "None", ",", "obj", "=", "None", ",", "metadata", "=", "None", ")", ":", "if", "img_...
42.777778
18.111111
def exclude_downhole(filt, threshold=2): """ Exclude all data after the first excluded portion. This makes sense for spot measurements where, because of the signal mixing inherent in LA-ICPMS, once a contaminant is ablated, it will always be present to some degree in signals from further down t...
[ "def", "exclude_downhole", "(", "filt", ",", "threshold", "=", "2", ")", ":", "cfilt", "=", "filt", ".", "copy", "(", ")", "inds", "=", "bool_2_indices", "(", "~", "filt", ")", "rem", "=", "(", "np", ".", "diff", "(", "inds", ")", ">=", "threshold"...
22.419355
20.677419
def refresh(self, *objects, **kwargs): ''' This method is an alternate API for refreshing many entities (possibly not tracked by the session). You can call:: session.refresh(obj) session.refresh(obj1, obj2, ...) session.refresh([obj1, obj2, ...]) And...
[ "def", "refresh", "(", "self", ",", "*", "objects", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_init", "(", ")", "from", "rom", "import", "Model", "force", "=", "kwargs", ".", "get", "(", "'force'", ")", "for", "o", "in", "objects", ":", "i...
37.2
18.733333
def download_file(self, container, resource, save_path=None, accept=None, query_items=None): """Download a file. If a timeout defined, it is not a time limit on the entire download; rather, an exception is raised if the server has not issued a response for timeout ...
[ "def", "download_file", "(", "self", ",", "container", ",", "resource", ",", "save_path", "=", "None", ",", "accept", "=", "None", ",", "query_items", "=", "None", ")", ":", "url", "=", "self", ".", "make_url", "(", "container", ",", "resource", ")", "...
37.574468
23.446809
def _get_service(client, organisation_id, name): """ Get service belonging to organisation which matches given service name :param client: Accounts Service API Client :param organisation_id: Id of Organisation :param name: Service Name :return: Service Id """ try: response = clie...
[ "def", "_get_service", "(", "client", ",", "organisation_id", ",", "name", ")", ":", "try", ":", "response", "=", "client", ".", "accounts", ".", "services", ".", "get", "(", "organisation_id", "=", "organisation_id", ")", "except", "httpclient", ".", "HTTPE...
37.75
21.916667
def _create_attachment(self, filename, content, mimetype=None): """Convert the filename, content, mimetype triple to attachment.""" if mimetype is None: mimetype, _ = mimetypes.guess_type(filename) if mimetype is None: mimetype = DEFAULT_ATTACHMENT_MIME_TYPE ...
[ "def", "_create_attachment", "(", "self", ",", "filename", ",", "content", ",", "mimetype", "=", "None", ")", ":", "if", "mimetype", "is", "None", ":", "mimetype", ",", "_", "=", "mimetypes", ".", "guess_type", "(", "filename", ")", "if", "mimetype", "is...
42.857143
15.142857
def set_branch_ids(self): """ Performs generation and setting of ids of branches for all MV and underlying LV grids. See Also -------- ding0.core.network.grids.MVGridDing0.set_branch_ids """ for grid_district in self.mv_grid_districts(): ...
[ "def", "set_branch_ids", "(", "self", ")", ":", "for", "grid_district", "in", "self", ".", "mv_grid_districts", "(", ")", ":", "grid_district", ".", "mv_grid", ".", "set_branch_ids", "(", ")", "logger", ".", "info", "(", "'=====> Branch IDs set'", ")" ]
33.083333
18.166667
def uploadAsset(self, data, async=False, metadata=None, callback=None): """Takes an array of bytes or a BufferedReader and uploads it. If async=false a json with the result is returned otherwise a json with an asset_id is returned. :param data: array of bytes or BufferedReader :param metadata: arbitrary add...
[ "def", "uploadAsset", "(", "self", ",", "data", ",", "async", "=", "False", ",", "metadata", "=", "None", ",", "callback", "=", "None", ")", ":", "#todo: has atter read would be better here", "if", "isinstance", "(", "data", ",", "io", ".", "BufferedReader", ...
41.64
17.96
def get_time_period(period_name): """ Given a time period name, fetch the hydra-compatible time abbreviation. """ time_abbreviation = time_map.get(period_name.lower()) if time_abbreviation is None: raise Exception("Symbol %s not recognised as a time period"%period_name) ret...
[ "def", "get_time_period", "(", "period_name", ")", ":", "time_abbreviation", "=", "time_map", ".", "get", "(", "period_name", ".", "lower", "(", ")", ")", "if", "time_abbreviation", "is", "None", ":", "raise", "Exception", "(", "\"Symbol %s not recognised as a tim...
30.090909
18.818182
def get_thermostats(self): ''' Set self.thermostats to a json list of thermostats from ecobee ''' url = 'https://api.ecobee.com/1/thermostat' header = {'Content-Type': 'application/json;charset=UTF-8', 'Authorization': 'Bearer ' + self.access_token} params = {'json': ('...
[ "def", "get_thermostats", "(", "self", ")", ":", "url", "=", "'https://api.ecobee.com/1/thermostat'", "header", "=", "{", "'Content-Type'", ":", "'application/json;charset=UTF-8'", ",", "'Authorization'", ":", "'Bearer '", "+", "self", ".", "access_token", "}", "param...
49.5
19.033333
def p_let_arr_substr(p): """ statement : LET ARRAY_ID arg_list substr EQ expr | ARRAY_ID arg_list substr EQ expr """ i = 2 if p[1].upper() == 'LET' else 1 id_ = p[i] arg_list = p[i + 1] substr = p[i + 2] expr_ = p[i + 4] p[0] = make_array_substr_assign(p.lineno(i), id_...
[ "def", "p_let_arr_substr", "(", "p", ")", ":", "i", "=", "2", "if", "p", "[", "1", "]", ".", "upper", "(", ")", "==", "'LET'", "else", "1", "id_", "=", "p", "[", "i", "]", "arg_list", "=", "p", "[", "i", "+", "1", "]", "substr", "=", "p", ...
30.545455
17.181818
def generate_pdf(self): """Generate a PDF from the displayed content.""" printer = QtGui.QPrinter(QtGui.QPrinter.HighResolution) printer.setPageSize(QtGui.QPrinter.A4) printer.setColorMode(QtGui.QPrinter.Color) printer.setOutputFormat(QtGui.QPrinter.PdfFormat) report_path...
[ "def", "generate_pdf", "(", "self", ")", ":", "printer", "=", "QtGui", ".", "QPrinter", "(", "QtGui", ".", "QPrinter", ".", "HighResolution", ")", "printer", ".", "setPageSize", "(", "QtGui", ".", "QPrinter", ".", "A4", ")", "printer", ".", "setColorMode",...
48.416667
11.916667
def rho(self): r'''Mass density of the chemical at its current phase and temperature and pressure, in units of [kg/m^3]. Utilizes the object oriented interfaces :obj:`thermo.volume.VolumeSolid`, :obj:`thermo.volume.VolumeLiquid`, and :obj:`thermo.volume.VolumeGas` to per...
[ "def", "rho", "(", "self", ")", ":", "return", "phase_select_property", "(", "phase", "=", "self", ".", "phase", ",", "s", "=", "self", ".", "rhos", ",", "l", "=", "self", ".", "rhol", ",", "g", "=", "self", ".", "rhog", ")" ]
37.941176
21.705882
def modify(self, sort=None, purge=False, done=None, undone=None): """Handles the 'm' command. :sort: Sort pattern. :purge: Whether to purge items marked as 'done'. :done: Done pattern. :undone: Not done pattern. """ self.model.modifyInPlace( sort=sel...
[ "def", "modify", "(", "self", ",", "sort", "=", "None", ",", "purge", "=", "False", ",", "done", "=", "None", ",", "undone", "=", "None", ")", ":", "self", ".", "model", ".", "modifyInPlace", "(", "sort", "=", "self", ".", "_getPattern", "(", "sort...
29.071429
14.928571
def underToMixed(name): """ >>> underToMixed('some_large_model_name_perhaps') 'someLargeModelNamePerhaps' >>> underToMixed('exception_for_id') 'exceptionForID' """ if name.endswith('_id'): return underToMixed(name[:-3] + "ID") return _underToMixedRE.sub(lambda m: m.group(0)[1].u...
[ "def", "underToMixed", "(", "name", ")", ":", "if", "name", ".", "endswith", "(", "'_id'", ")", ":", "return", "underToMixed", "(", "name", "[", ":", "-", "3", "]", "+", "\"ID\"", ")", "return", "_underToMixedRE", ".", "sub", "(", "lambda", "m", ":",...
29.416667
11.916667
def _resolve_version(version): """ Resolve LATEST version """ if version is not LATEST: return version resp = urlopen('https://pypi.python.org/pypi/setuptools/json') with contextlib.closing(resp): try: charset = resp.info().get_content_charset() except Except...
[ "def", "_resolve_version", "(", "version", ")", ":", "if", "version", "is", "not", "LATEST", ":", "return", "version", "resp", "=", "urlopen", "(", "'https://pypi.python.org/pypi/setuptools/json'", ")", "with", "contextlib", ".", "closing", "(", "resp", ")", ":"...
27.888889
13.555556
def get_processes(sort_by_name=True): """Retrieve a list of processes sorted by name. Args: sort_by_name (bool): Sort the list by name or by process ID's. Returns: list of (int, str) or list of (int, str, str): List of process id, process name and optional cmdline tuple...
[ "def", "get_processes", "(", "sort_by_name", "=", "True", ")", ":", "if", "sort_by_name", ":", "return", "sorted", "(", "_list_processes", "(", ")", ",", "key", "=", "cmp_to_key", "(", "lambda", "p1", ",", "p2", ":", "(", "cmp", "(", "p1", ".", "name",...
30.125
22.041667
def _file_lists(load, form): ''' Return a dict containing the file lists for files, dirs, emptydirs and symlinks ''' if 'env' in load: # "env" is not supported; Use "saltenv". load.pop('env') if 'saltenv' not in load or load['saltenv'] not in envs(): return [] list_cach...
[ "def", "_file_lists", "(", "load", ",", "form", ")", ":", "if", "'env'", "in", "load", ":", "# \"env\" is not supported; Use \"saltenv\".", "load", ".", "pop", "(", "'env'", ")", "if", "'saltenv'", "not", "in", "load", "or", "load", "[", "'saltenv'", "]", ...
38.144928
18.144928
def matching_line(freq, data, tref, bin_size=1): """ Find the parameter of the line with frequency 'freq' in the data. Parameters ---------- freq: float Frequency of the line to find in the data. data: pycbc.types.TimeSeries Data from which the line wants to be measured. tref: f...
[ "def", "matching_line", "(", "freq", ",", "data", ",", "tref", ",", "bin_size", "=", "1", ")", ":", "template_line", "=", "line_model", "(", "freq", ",", "data", ",", "tref", "=", "tref", ")", "# Measure amplitude and phase of the line in the data", "_", ",", ...
37.08
17.56
def ensure_dir(dir_path): """ If DIR_PATH does not exist, makes it. Failing that, raises Exception. Returns True if dir already existed; False if it had to be made. """ exists = dir_exists(dir_path) if not exists: try: os.makedirs(dir_path) except(Exception,RuntimeErr...
[ "def", "ensure_dir", "(", "dir_path", ")", ":", "exists", "=", "dir_exists", "(", "dir_path", ")", "if", "not", "exists", ":", "try", ":", "os", ".", "makedirs", "(", "dir_path", ")", "except", "(", "Exception", ",", "RuntimeError", ")", ",", "e", ":",...
34.461538
15.230769
def assert_called_once_with(_mock_self, *args, **kwargs): """assert that the mock was called exactly once and with the specified arguments.""" self = _mock_self if not self.call_count == 1: msg = ("Expected '%s' to be called once. Called %s times." % (self....
[ "def", "assert_called_once_with", "(", "_mock_self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", "=", "_mock_self", "if", "not", "self", ".", "call_count", "==", "1", ":", "msg", "=", "(", "\"Expected '%s' to be called once. Called %s times.\"",...
49.444444
12.222222
def find_one_project(zero_ok=False, more_ok=True, **kwargs): """ :param zero_ok: If False (default), :class:`~dxpy.exceptions.DXSearchError` is raised if the search has 0 results; if True, returns None if the search has 0 results :type zero_ok: bool :param more_ok: If Fal...
[ "def", "find_one_project", "(", "zero_ok", "=", "False", ",", "more_ok", "=", "True", ",", "*", "*", "kwargs", ")", ":", "return", "_find_one", "(", "find_projects", ",", "zero_ok", "=", "zero_ok", ",", "more_ok", "=", "more_ok", ",", "*", "*", "kwargs",...
39.888889
22.222222
def organisation_logo(self, logo): """Set image that will be used as organisation logo in reports. :param logo: Path to the organisation logo image. :type logo: str """ if isinstance(logo, str) and os.path.exists(logo): self._organisation_logo = logo else: ...
[ "def", "organisation_logo", "(", "self", ",", "logo", ")", ":", "if", "isinstance", "(", "logo", ",", "str", ")", "and", "os", ".", "path", ".", "exists", "(", "logo", ")", ":", "self", ".", "_organisation_logo", "=", "logo", "else", ":", "self", "."...
36.9
14.7
def turn_physical_on(Pot,ro=None,vo=None): """ NAME: turn_physical_on PURPOSE: turn on automatic returning of outputs in physical units INPUT: ro= reference distance (kpc; can be Quantity) vo= reference velocity (km/s; can be Quantity) OUT...
[ "def", "turn_physical_on", "(", "Pot", ",", "ro", "=", "None", ",", "vo", "=", "None", ")", ":", "if", "isinstance", "(", "Pot", ",", "list", ")", ":", "for", "pot", "in", "Pot", ":", "turn_physical_on", "(", "pot", ",", "ro", "=", "ro", ",", "vo...
18.064516
23.548387
def l2(Ks, dim, X_rhos, Y_rhos, required, clamp=True, to_self=False): r''' Estimates the L2 distance between distributions, via \int (p - q)^2 = \int p^2 - \int p q - \int q p + \int q^2. \int pq and \int qp are estimated with the linear function (in both directions), while \int p^2 and \int q^...
[ "def", "l2", "(", "Ks", ",", "dim", ",", "X_rhos", ",", "Y_rhos", ",", "required", ",", "clamp", "=", "True", ",", "to_self", "=", "False", ")", ":", "n_X", "=", "len", "(", "X_rhos", ")", "n_Y", "=", "len", "(", "Y_rhos", ")", "linears", "=", ...
32.972222
21.916667
def source(self, format='xml', accessible=False): """ Args: format (str): only 'xml' and 'json' source types are supported accessible (bool): when set to true, format is always 'json' """ if accessible: return self.http.get('/wda/accessibleSource').val...
[ "def", "source", "(", "self", ",", "format", "=", "'xml'", ",", "accessible", "=", "False", ")", ":", "if", "accessible", ":", "return", "self", ".", "http", ".", "get", "(", "'/wda/accessibleSource'", ")", ".", "value", "return", "self", ".", "http", ...
41.555556
18
def _result_type_many(*arrays_and_dtypes): """ wrapper around numpy.result_type which overcomes the NPY_MAXARGS (32) argument limit """ try: return np.result_type(*arrays_and_dtypes) except ValueError: # we have > NPY_MAXARGS terms in our expression return reduce(np.result_type, ...
[ "def", "_result_type_many", "(", "*", "arrays_and_dtypes", ")", ":", "try", ":", "return", "np", ".", "result_type", "(", "*", "arrays_and_dtypes", ")", "except", "ValueError", ":", "# we have > NPY_MAXARGS terms in our expression", "return", "reduce", "(", "np", "....
41.375
11.5
def dict_to_dataset(data, *, attrs=None, library=None, coords=None, dims=None): """Convert a dictionary of numpy arrays to an xarray.Dataset. Parameters ---------- data : dict[str] -> ndarray Data to convert. Keys are variable names. attrs : dict Json serializable metadata to attach...
[ "def", "dict_to_dataset", "(", "data", ",", "*", ",", "attrs", "=", "None", ",", "library", "=", "None", ",", "coords", "=", "None", ",", "dims", "=", "None", ")", ":", "if", "dims", "is", "None", ":", "dims", "=", "{", "}", "data_vars", "=", "{"...
31.828571
25.428571
def find_path(dirs, path_to_find): """ Go through a bunch of dirs and see if dir+path_to_find exists there. Returns the first dir that matches. Otherwise, return None. """ for dir in dirs: if os.path.exists(os.path.join(dir, path_to_find)): return dir return None
[ "def", "find_path", "(", "dirs", ",", "path_to_find", ")", ":", "for", "dir", "in", "dirs", ":", "if", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "dir", ",", "path_to_find", ")", ")", ":", "return", "dir", "return",...
33.222222
15.888889
def base_elts(elt, cls=None, depth=None): """Get bases elements of the input elt. - If elt is an instance, get class and all base classes. - If elt is a method, get all base methods. - If elt is a class, get all base classes. - In other case, get an empty list. :param elt: supposed inherited e...
[ "def", "base_elts", "(", "elt", ",", "cls", "=", "None", ",", "depth", "=", "None", ")", ":", "result", "=", "[", "]", "elt_name", "=", "getattr", "(", "elt", ",", "'__name__'", ",", "None", ")", "if", "elt_name", "is", "not", "None", ":", "cls", ...
33.540816
20.704082
def send_audio(self, peer: Peer, audio: str, reply: int=None, on_success: callable=None, reply_markup: botapi.ReplyMarkup=None): """ Send audio clip to peer. :param peer: Peer to send message to. :param audio: File path to audio to send. :param reply: Message o...
[ "def", "send_audio", "(", "self", ",", "peer", ":", "Peer", ",", "audio", ":", "str", ",", "reply", ":", "int", "=", "None", ",", "on_success", ":", "callable", "=", "None", ",", "reply_markup", ":", "botapi", ".", "ReplyMarkup", "=", "None", ")", ":...
39.166667
17.5
def deployments(self): """ Access the deployments :returns: twilio.rest.serverless.v1.service.environment.deployment.DeploymentList :rtype: twilio.rest.serverless.v1.service.environment.deployment.DeploymentList """ if self._deployments is None: self._deploym...
[ "def", "deployments", "(", "self", ")", ":", "if", "self", ".", "_deployments", "is", "None", ":", "self", ".", "_deployments", "=", "DeploymentList", "(", "self", ".", "_version", ",", "service_sid", "=", "self", ".", "_solution", "[", "'service_sid'", "]...
37.214286
17.928571
def parse(self, vd, extent_loc): # type: (bytes, int) -> None ''' A method to parse a Volume Descriptor Set Terminator out of a string. Parameters: vd - The string to parse. extent_loc - The extent this VDST is currently located at. Returns: Nothing. ...
[ "def", "parse", "(", "self", ",", "vd", ",", "extent_loc", ")", ":", "# type: (bytes, int) -> None", "if", "self", ".", "_initialized", ":", "raise", "pycdlibexception", ".", "PyCdlibInternalError", "(", "'Volume Descriptor Set Terminator already initialized'", ")", "("...
41.941176
26.176471
def _adjustSectionAlignment(self, value, fileAlignment, sectionAlignment): """ Align a value to C{SectionAligment}. @type value: int @param value: The value to be aligned. @type fileAlignment: int @param fileAlignment: The value to be used as C{FileAlig...
[ "def", "_adjustSectionAlignment", "(", "self", ",", "value", ",", "fileAlignment", ",", "sectionAlignment", ")", ":", "if", "fileAlignment", "<", "consts", ".", "DEFAULT_FILE_ALIGNMENT", ":", "if", "fileAligment", "!=", "sectionAlignment", ":", "print", "\"FileAlign...
36.653846
19.115385
def ImportBoarding(self, drop_off_file): "Reads the bedverb.mdv file." for trip_id, seq, code in \ ReadCSV(drop_off_file, ['FRT_FID', 'LI_LFD_NR', 'BEDVERB_CODE']): key = (trip_id, int(seq) - 1) if code == 'A': self.pickup_type[key] = '1' # '1' = no pick-up elif code == 'E': ...
[ "def", "ImportBoarding", "(", "self", ",", "drop_off_file", ")", ":", "for", "trip_id", ",", "seq", ",", "code", "in", "ReadCSV", "(", "drop_off_file", ",", "[", "'FRT_FID'", ",", "'LI_LFD_NR'", ",", "'BEDVERB_CODE'", "]", ")", ":", "key", "=", "(", "tri...
41.5625
17.8125
def parse(self, line, namespace=None): """Parses a line into a dictionary of arguments, expanding meta-variables from a namespace. """ try: if namespace is None: ipy = IPython.get_ipython() namespace = ipy.user_ns args = CommandParser.create_args(line, namespace) return self.pa...
[ "def", "parse", "(", "self", ",", "line", ",", "namespace", "=", "None", ")", ":", "try", ":", "if", "namespace", "is", "None", ":", "ipy", "=", "IPython", ".", "get_ipython", "(", ")", "namespace", "=", "ipy", ".", "user_ns", "args", "=", "CommandPa...
35.363636
12.727273
def vcl(self, name, content): """ Create a new VCL under this version. """ vcl = VCL() vcl.conn = self.conn vcl.attrs = { # Parent params 'service_id': self.attrs['service_id'], 'version': self.attrs['number'], # New instance params ...
[ "def", "vcl", "(", "self", ",", "name", ",", "content", ")", ":", "vcl", "=", "VCL", "(", ")", "vcl", ".", "conn", "=", "self", ".", "conn", "vcl", ".", "attrs", "=", "{", "# Parent params", "'service_id'", ":", "self", ".", "attrs", "[", "'service...
22.5
19.833333
def element_should_not_exist(self, json_string, expr): """ Check that one or more elements, matching [ http://jsonselect.org/ | JSONSelect] expression, don't exist. *DEPRECATED* JSON Select query language is outdated and not supported any more. Use other keywords of this library to quer...
[ "def", "element_should_not_exist", "(", "self", ",", "json_string", ",", "expr", ")", ":", "value", "=", "self", ".", "select_elements", "(", "json_string", ",", "expr", ")", "if", "value", "is", "not", "None", ":", "raise", "JsonValidatorError", "(", "'Elem...
37.470588
23.352941
def get_class_from_settings(settings_key): """Gets a class from a setting key. This will first check loaded models, then look in installed apps, then fallback to import from lib. :param settings_key: the key defined in settings to the value for """ cls_path = getattr(settings, settings_key, None) ...
[ "def", "get_class_from_settings", "(", "settings_key", ")", ":", "cls_path", "=", "getattr", "(", "settings", ",", "settings_key", ",", "None", ")", "if", "not", "cls_path", ":", "raise", "NotImplementedError", "(", ")", "try", ":", "# First check to see if it's a...
38.7
20.4
def write_output_files(self): """ The total hydrogen bond count per frame is provided as CSV output file. Each trajectory has a separate file. """ os.mkdir("analysis") os.chdir("analysis") os.mkdir("hydrogen_bonds") os.chdir("hydrogen_bonds") for t...
[ "def", "write_output_files", "(", "self", ")", ":", "os", ".", "mkdir", "(", "\"analysis\"", ")", "os", ".", "chdir", "(", "\"analysis\"", ")", "os", ".", "mkdir", "(", "\"hydrogen_bonds\"", ")", "os", ".", "chdir", "(", "\"hydrogen_bonds\"", ")", "for", ...
68.714286
35.142857
def calc_state_matrix(self): """ Return state matrix and store to ``self.As`` Returns ------- matrix state matrix """ system = self.system Gyx = matrix(system.dae.Gx) self.solver.linsolve(system.dae.Gy, Gyx) self.As = matrix(...
[ "def", "calc_state_matrix", "(", "self", ")", ":", "system", "=", "self", ".", "system", "Gyx", "=", "matrix", "(", "system", ".", "dae", ".", "Gx", ")", "self", ".", "solver", ".", "linsolve", "(", "system", ".", "dae", ".", "Gy", ",", "Gyx", ")",...
30.56
18
def current_transaction(self): """current tx""" try: tx, _, _, _, _ = self._callstack[-1] if tx.result is not None: #That tx finished. No current tx. return None return tx except IndexError: return None
[ "def", "current_transaction", "(", "self", ")", ":", "try", ":", "tx", ",", "_", ",", "_", ",", "_", ",", "_", "=", "self", ".", "_callstack", "[", "-", "1", "]", "if", "tx", ".", "result", "is", "not", "None", ":", "#That tx finished. No current tx....
29.7
12.1
def button_clicked(self, button): """Action when button was clicked. Parameters ---------- button : instance of QPushButton which button was pressed """ if button is self.idx_ok: #new_format = self.new_format.get_value().lower() new_f...
[ "def", "button_clicked", "(", "self", ",", "button", ")", ":", "if", "button", "is", "self", ".", "idx_ok", ":", "#new_format = self.new_format.get_value().lower()", "new_format", "=", "'edf'", "chan", "=", "None", "beg", "=", "None", "end", "=", "None", "if",...
28.433333
18.533333
def post_build(self, p, pay): """Called implicitly before a packet is sent. """ p += pay if self.auxdlen != 0: print("NOTICE: A properly formatted and complaint V3 Group Record should have an Auxiliary Data length of zero (0).") print(" Subsequent Group Records are lost!") return ...
[ "def", "post_build", "(", "self", ",", "p", ",", "pay", ")", ":", "p", "+=", "pay", "if", "self", ".", "auxdlen", "!=", "0", ":", "print", "(", "\"NOTICE: A properly formatted and complaint V3 Group Record should have an Auxiliary Data length of zero (0).\"", ")", "pr...
39.25
22.75
def main(argv: Optional[Sequence[str]] = None) -> None: """ Start the pass-git-helper script. Args: argv: If not ``None``, use the provided command line arguments for parsing. Otherwise, extract them automatically. """ args = parse_arguments(argv=argv) if args.l...
[ "def", "main", "(", "argv", ":", "Optional", "[", "Sequence", "[", "str", "]", "]", "=", "None", ")", "->", "None", ":", "args", "=", "parse_arguments", "(", "argv", "=", "argv", ")", "if", "args", ".", "logging", ":", "logging", ".", "basicConfig", ...
27.638889
20.027778
def store_and_register(self, object_id, value, depth=100): """Store an object and attempt to register its class if needed. Args: object_id: The ID of the object to store. value: The value to put in the object store. depth: The maximum number of classes to recursively...
[ "def", "store_and_register", "(", "self", ",", "object_id", ",", "value", ",", "depth", "=", "100", ")", ":", "counter", "=", "0", "while", "True", ":", "if", "counter", "==", "depth", ":", "raise", "Exception", "(", "\"Ray exceeded the maximum number of class...
54.386667
23.32
def absolute_distance(cls, q0, q1): """Quaternion absolute distance. Find the distance between two quaternions accounting for the sign ambiguity. Params: q0: the first quaternion q1: the second quaternion Returns: A positive scalar corresponding to t...
[ "def", "absolute_distance", "(", "cls", ",", "q0", ",", "q1", ")", ":", "q0_minus_q1", "=", "q0", "-", "q1", "q0_plus_q1", "=", "q0", "+", "q1", "d_minus", "=", "q0_minus_q1", ".", "norm", "d_plus", "=", "q0_plus_q1", ".", "norm", "if", "(", "d_minus",...
32.461538
21.269231
def _from_dict(cls, _dict): """Initialize a AnalysisResultsMetadata object from a json dictionary.""" args = {} if 'authors' in _dict: args['authors'] = [ Author._from_dict(x) for x in (_dict.get('authors')) ] if 'publication_date' in _dict: ...
[ "def", "_from_dict", "(", "cls", ",", "_dict", ")", ":", "args", "=", "{", "}", "if", "'authors'", "in", "_dict", ":", "args", "[", "'authors'", "]", "=", "[", "Author", ".", "_from_dict", "(", "x", ")", "for", "x", "in", "(", "_dict", ".", "get"...
40.875
14.9375
def make_list(var, num_terms=1): """ Make a variable a list if it is not already If variable is not a list it will make it a list of the correct length with all terms identical. """ if not isinstance(var, list): if isinstance(var, tuple): var = list(var) else: ...
[ "def", "make_list", "(", "var", ",", "num_terms", "=", "1", ")", ":", "if", "not", "isinstance", "(", "var", ",", "list", ")", ":", "if", "isinstance", "(", "var", ",", "tuple", ")", ":", "var", "=", "list", "(", "var", ")", "else", ":", "var", ...
28.933333
14.933333
def set_widgets(self): """Set widgets on the LayerMode tab.""" self.clear_further_steps() # Set widgets self.lblBandSelector.setText(tr( 'Please select which band that contains the data that you want to ' 'use for this layer.')) self.lstBands.clear() ...
[ "def", "set_widgets", "(", "self", ")", ":", "self", ".", "clear_further_steps", "(", ")", "# Set widgets", "self", ".", "lblBandSelector", ".", "setText", "(", "tr", "(", "'Please select which band that contains the data that you want to '", "'use for this layer.'", ")",...
39.952381
11.714286
def get_backend(alias): """ Returns ``Repository`` class identified by the given alias or raises VCSError if alias is not recognized or backend class cannot be imported. """ if alias not in settings.BACKENDS: raise VCSError("Given alias '%s' is not recognized! Allowed aliases:\n" ...
[ "def", "get_backend", "(", "alias", ")", ":", "if", "alias", "not", "in", "settings", ".", "BACKENDS", ":", "raise", "VCSError", "(", "\"Given alias '%s' is not recognized! Allowed aliases:\\n\"", "\"%s\"", "%", "(", "alias", ",", "pformat", "(", "settings", ".", ...
41.909091
16.090909
def model_segments(copy_file, work_dir, paired): """Perform segmentation on input copy number log2 ratio file. """ out_file = os.path.join(work_dir, "%s.cr.seg" % dd.get_sample_name(paired.tumor_data)) tumor_counts, normal_counts = heterogzygote_counts(paired) if not utils.file_exists(out_file): ...
[ "def", "model_segments", "(", "copy_file", ",", "work_dir", ",", "paired", ")", ":", "out_file", "=", "os", ".", "path", ".", "join", "(", "work_dir", ",", "\"%s.cr.seg\"", "%", "dd", ".", "get_sample_name", "(", "paired", ".", "tumor_data", ")", ")", "t...
63.75
25.35
def _null_ac_sia(transition, direction, alpha=0.0): """Return an |AcSystemIrreducibilityAnalysis| with zero |big_alpha| and empty accounts. """ return AcSystemIrreducibilityAnalysis( transition=transition, direction=direction, alpha=alpha, account=(), partitioned_...
[ "def", "_null_ac_sia", "(", "transition", ",", "direction", ",", "alpha", "=", "0.0", ")", ":", "return", "AcSystemIrreducibilityAnalysis", "(", "transition", "=", "transition", ",", "direction", "=", "direction", ",", "alpha", "=", "alpha", ",", "account", "=...
29.636364
12.909091
def _update_texttuple(self, x, y, s, cs, d): """Update the text tuple at `x` and `y` with the given `s` and `d`""" pos = (x, y, cs) for i, (old_x, old_y, old_s, old_cs, old_d) in enumerate(self.value): if (old_x, old_y, old_cs) == pos: self.value[i] = (old_x, old_y, s...
[ "def", "_update_texttuple", "(", "self", ",", "x", ",", "y", ",", "s", ",", "cs", ",", "d", ")", ":", "pos", "=", "(", "x", ",", "y", ",", "cs", ")", "for", "i", ",", "(", "old_x", ",", "old_y", ",", "old_s", ",", "old_cs", ",", "old_d", ")...
52
15.875
def package_config(path, template='__config__.ini.TEMPLATE', config_name='__config__.ini', **params): """configure the module at the given path with a config template and file. path = the filesystem path to the given module template = the config template filename within that path ...
[ "def", "package_config", "(", "path", ",", "template", "=", "'__config__.ini.TEMPLATE'", ",", "config_name", "=", "'__config__.ini'", ",", "*", "*", "params", ")", ":", "config_fns", "=", "[", "]", "template_fns", "=", "rglob", "(", "path", ",", "template", ...
50.777778
17.5
def eliminate_implications(s): """Change >>, <<, and <=> into &, |, and ~. That is, return an Expr that is equivalent to s, but has only &, |, and ~ as logical operators. >>> eliminate_implications(A >> (~B << C)) ((~B | ~C) | ~A) >>> eliminate_implications(A ^ B) ((A & ~B) | (~A & B)) """ ...
[ "def", "eliminate_implications", "(", "s", ")", ":", "if", "not", "s", ".", "args", "or", "is_symbol", "(", "s", ".", "op", ")", ":", "return", "s", "## (Atoms are unchanged.)", "args", "=", "map", "(", "eliminate_implications", ",", "s", ".", "args", ")...
34.913043
14.217391
def commit_account_debit(self, opcode, account_payment_info, current_block_number, current_vtxindex, current_txid): """ Given the account info set by a state-create or state-transition or a token-operation, debit the relevant account. Do not call this directly. Return T...
[ "def", "commit_account_debit", "(", "self", ",", "opcode", ",", "account_payment_info", ",", "current_block_number", ",", "current_vtxindex", ",", "current_txid", ")", ":", "account_address", "=", "account_payment_info", "[", "'address'", "]", "account_payment", "=", ...
46.914286
31.2
def get_agent(msg): """ Handy hack to handle legacy messages where 'agent' was a list. """ agent = msg['msg']['agent'] if isinstance(agent, list): agent = agent[0] return agent
[ "def", "get_agent", "(", "msg", ")", ":", "agent", "=", "msg", "[", "'msg'", "]", "[", "'agent'", "]", "if", "isinstance", "(", "agent", ",", "list", ")", ":", "agent", "=", "agent", "[", "0", "]", "return", "agent" ]
32.666667
13.166667
def start_span(self, operation_name=None, child_of=None, references=None, tags=None, start_time=None, ignore_active_span=False, ): """ Start and return a new Span represen...
[ "def", "start_span", "(", "self", ",", "operation_name", "=", "None", ",", "child_of", "=", "None", ",", "references", "=", "None", ",", "tags", "=", "None", ",", "start_time", "=", "None", ",", "ignore_active_span", "=", "False", ",", ")", ":", "parent"...
41.6875
18.208333
def write(self, buf, *, start=0, end=None): """ Write the bytes from ``buf`` to the device. If ``start`` or ``end`` is provided, then the buffer will be sliced as if ``buffer[start:end]``. This will not cause an allocation like ``buffer[start:end]`` will so it saves memory. ...
[ "def", "write", "(", "self", ",", "buf", ",", "*", ",", "start", "=", "0", ",", "end", "=", "None", ")", ":", "return", "self", ".", "_bus", ".", "write", "(", "buf", ",", "start", "=", "start", ",", "end", "=", "end", ")" ]
42.692308
19.461538