text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def floats(s): """Convert string to float. Handles more string formats that the standard python conversion.""" try: return float(s) except ValueError: s = re.sub(r'(\d)\s*\(\d+(\.\d+)?\)', r'\1', s) # Remove bracketed numbers from end s = re.sub(r'(\d)\s*±\s*\d+(\.\d+)?', r'\1...
[ "def", "floats", "(", "s", ")", ":", "try", ":", "return", "float", "(", "s", ")", "except", "ValueError", ":", "s", "=", "re", ".", "sub", "(", "r'(\\d)\\s*\\(\\d+(\\.\\d+)?\\)'", ",", "r'\\1'", ",", "s", ")", "# Remove bracketed numbers from end", "s", "...
62.923077
35.307692
def support_support_param_username(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") support = ET.SubElement(config, "support", xmlns="urn:brocade.com:mgmt:brocade-ras") support_param = ET.SubElement(support, "support-param") username = ET.SubEleme...
[ "def", "support_support_param_username", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "support", "=", "ET", ".", "SubElement", "(", "config", ",", "\"support\"", ",", "xmlns", "=", "\"urn:broc...
43.363636
16.363636
def reset_parameters(self, init_weight): """ Sets initial random values for trainable parameters. """ stdv = 1. / math.sqrt(self.num_units) self.linear_att.data.uniform_(-init_weight, init_weight) if self.normalize: self.normalize_scalar.data.fill_(stdv) ...
[ "def", "reset_parameters", "(", "self", ",", "init_weight", ")", ":", "stdv", "=", "1.", "/", "math", ".", "sqrt", "(", "self", ".", "num_units", ")", "self", ".", "linear_att", ".", "data", ".", "uniform_", "(", "-", "init_weight", ",", "init_weight", ...
35.1
11.7
def get_SAM(self,min_intron_size=68): """Get a SAM object representation of the alignment. :returns: SAM representation :rtype: SAM """ from seqtools.format.sam import SAM #ar is target then query qname = self.alignment_ranges[0][1].chr flag = 0 if self.strand == '-': flag = 16 ...
[ "def", "get_SAM", "(", "self", ",", "min_intron_size", "=", "68", ")", ":", "from", "seqtools", ".", "format", ".", "sam", "import", "SAM", "#ar is target then query", "qname", "=", "self", ".", "alignment_ranges", "[", "0", "]", "[", "1", "]", ".", "chr...
31.222222
14.75
def _process_queue_tasks(self, queue, queue_lock, task_ids, now, log): """Process tasks in queue.""" processed_count = 0 # Get all tasks serialized_tasks = self.connection.mget([ self._key('task', task_id) for task_id in task_ids ]) # Parse tasks ta...
[ "def", "_process_queue_tasks", "(", "self", ",", "queue", ",", "queue_lock", ",", "task_ids", ",", "now", ",", "log", ")", ":", "processed_count", "=", "0", "# Get all tasks", "serialized_tasks", "=", "self", ".", "connection", ".", "mget", "(", "[", "self",...
37.683333
19.2
def do_intersect(bb1, bb2): """ Helper function that returns True if two bounding boxes overlap. """ if bb1[0] + bb1[2] < bb2[0] or bb2[0] + bb2[2] < bb1[0]: return False if bb1[1] + bb1[3] < bb2[1] or bb2[1] + bb2[3] < bb1[1]: return False return True
[ "def", "do_intersect", "(", "bb1", ",", "bb2", ")", ":", "if", "bb1", "[", "0", "]", "+", "bb1", "[", "2", "]", "<", "bb2", "[", "0", "]", "or", "bb2", "[", "0", "]", "+", "bb2", "[", "2", "]", "<", "bb1", "[", "0", "]", ":", "return", ...
31.555556
16.222222
def pre_render(self): """Last things to do before rendering""" self.add_styles() self.add_scripts() self.root.set( 'viewBox', '0 0 %d %d' % (self.graph.width, self.graph.height) ) if self.graph.explicit_size: self.root.set('width', str(self.graph.w...
[ "def", "pre_render", "(", "self", ")", ":", "self", ".", "add_styles", "(", ")", "self", ".", "add_scripts", "(", ")", "self", ".", "root", ".", "set", "(", "'viewBox'", ",", "'0 0 %d %d'", "%", "(", "self", ".", "graph", ".", "width", ",", "self", ...
37.7
17.1
def volumes_maximum_size_bytes(self): """Gets the biggest logical drive :returns the size in MiB. """ return utils.max_safe([member.volumes.maximum_size_bytes for member in self.get_members()])
[ "def", "volumes_maximum_size_bytes", "(", "self", ")", ":", "return", "utils", ".", "max_safe", "(", "[", "member", ".", "volumes", ".", "maximum_size_bytes", "for", "member", "in", "self", ".", "get_members", "(", ")", "]", ")" ]
35.857143
14.142857
def send_callback_json_message(value, *args, **kwargs): """ useful for sending messages from callbacks as it puts the result of the callback in the dict for serialization """ if value: kwargs['result'] = value send_json_message(args[0], args[1], **kwargs) return value
[ "def", "send_callback_json_message", "(", "value", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "value", ":", "kwargs", "[", "'result'", "]", "=", "value", "send_json_message", "(", "args", "[", "0", "]", ",", "args", "[", "1", "]", ","...
25.333333
20.666667
def wildcard_import_names(self): """The list of imported names when this module is 'wildcard imported'. It doesn't include the '__builtins__' name which is added by the current CPython implementation of wildcard imports. :returns: The list of imported names. :rtype: list(str) ...
[ "def", "wildcard_import_names", "(", "self", ")", ":", "# We separate the different steps of lookup in try/excepts", "# to avoid catching too many Exceptions", "default", "=", "[", "name", "for", "name", "in", "self", ".", "keys", "(", ")", "if", "not", "name", ".", "...
34.387755
17.306122
def _GetDecodedStreamSize(self): """Retrieves the decoded stream size. Returns: int: decoded stream size. """ self._file_object.seek(0, os.SEEK_SET) self._decoder = self._GetDecoder() self._decoded_data = b'' encoded_data_offset = 0 encoded_data_size = self._file_object.get_size...
[ "def", "_GetDecodedStreamSize", "(", "self", ")", ":", "self", ".", "_file_object", ".", "seek", "(", "0", ",", "os", ".", "SEEK_SET", ")", "self", ".", "_decoder", "=", "self", ".", "_GetDecoder", "(", ")", "self", ".", "_decoded_data", "=", "b''", "e...
25.75
18.583333
def write_file(self, target_path, html): """ Writes out the provided HTML to the provided path. """ logger.debug("Building to {}{}".format(self.fs_name, target_path)) with self.fs.open(smart_text(target_path), 'wb') as outfile: outfile.write(six.binary_type(html)) ...
[ "def", "write_file", "(", "self", ",", "target_path", ",", "html", ")", ":", "logger", ".", "debug", "(", "\"Building to {}{}\"", ".", "format", "(", "self", ".", "fs_name", ",", "target_path", ")", ")", "with", "self", ".", "fs", ".", "open", "(", "sm...
42.125
12.625
def set_nearest_border(self): """Snaps the port to the correct side upon state size change """ px, py = self._point nw_x, nw_y, se_x, se_y = self.get_adjusted_border_positions() if self._port.side == SnappedSide.RIGHT: _update(px, se_x) elif self._port.side =...
[ "def", "set_nearest_border", "(", "self", ")", ":", "px", ",", "py", "=", "self", ".", "_point", "nw_x", ",", "nw_y", ",", "se_x", ",", "se_y", "=", "self", ".", "get_adjusted_border_positions", "(", ")", "if", "self", ".", "_port", ".", "side", "==", ...
36.928571
12.285714
def _logpdf(self, **kwargs): """Returns the log of the pdf at the given values. The keyword arguments must contain all of parameters in self's params. Unrecognized arguments are ignored. """ if kwargs in self: return sum([self._lognorm[p] + sel...
[ "def", "_logpdf", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", "in", "self", ":", "return", "sum", "(", "[", "self", ".", "_lognorm", "[", "p", "]", "+", "self", ".", "_expnorm", "[", "p", "]", "*", "(", "kwargs", "[", "p", ...
40.454545
13.818182
def deserialize_duration(attr): """Deserialize ISO-8601 formatted string into TimeDelta object. :param str attr: response string to be deserialized. :rtype: TimeDelta :raises: DeserializationError if string format invalid. """ if isinstance(attr, ET.Element): ...
[ "def", "deserialize_duration", "(", "attr", ")", ":", "if", "isinstance", "(", "attr", ",", "ET", ".", "Element", ")", ":", "attr", "=", "attr", ".", "text", "try", ":", "duration", "=", "isodate", ".", "parse_duration", "(", "attr", ")", "except", "("...
38.5
16.375
def _create_pattern_set(self, pattern, values): """Create a new pattern set.""" type_ = self._get_type(values) version = self._get_version(values) comment = values.get(COMMENT) self._pattern_set = self._spec.new_pattern_set( type_, version, pattern, self, comment ...
[ "def", "_create_pattern_set", "(", "self", ",", "pattern", ",", "values", ")", ":", "type_", "=", "self", ".", "_get_type", "(", "values", ")", "version", "=", "self", ".", "_get_version", "(", "values", ")", "comment", "=", "values", ".", "get", "(", ...
39.75
8.875
def transform_properties(properties, schema): """Transform properties types according to a schema. Parameters ---------- properties : dict Properties to transform. schema : dict Fiona schema containing the types. """ new_properties = properties.copy() for prop_value, (p...
[ "def", "transform_properties", "(", "properties", ",", "schema", ")", ":", "new_properties", "=", "properties", ".", "copy", "(", ")", "for", "prop_value", ",", "(", "prop_name", ",", "prop_type", ")", "in", "zip", "(", "new_properties", ".", "values", "(", ...
33.434783
19.043478
def list_passwords(kwargs=None, call=None): ''' List all password on the account .. versionadded:: 2015.8.0 ''' response = _query('support', 'password/list') ret = {} for item in response['list']: if 'server' in item: server = item['server']['name'] if serve...
[ "def", "list_passwords", "(", "kwargs", "=", "None", ",", "call", "=", "None", ")", ":", "response", "=", "_query", "(", "'support'", ",", "'password/list'", ")", "ret", "=", "{", "}", "for", "item", "in", "response", "[", "'list'", "]", ":", "if", "...
23.705882
18.058824
def HA2(credentials, request, algorithm): """Create HA2 md5 hash If the qop directive's value is "auth" or is unspecified, then HA2: HA2 = md5(A2) = MD5(method:digestURI) If the qop directive's value is "auth-int" , then HA2 is HA2 = md5(A2) = MD5(method:digestURI:MD5(entityBody)) """ ...
[ "def", "HA2", "(", "credentials", ",", "request", ",", "algorithm", ")", ":", "if", "credentials", ".", "get", "(", "\"qop\"", ")", "==", "\"auth\"", "or", "credentials", ".", "get", "(", "'qop'", ")", "is", "None", ":", "return", "H", "(", "b\":\"", ...
47.210526
17.789474
def check_auth(self): """Check authentication/authorization of client""" # access permissions if self.auth is not None: return self.auth(self.request) return self.public_readble, self.public_writable
[ "def", "check_auth", "(", "self", ")", ":", "# access permissions", "if", "self", ".", "auth", "is", "not", "None", ":", "return", "self", ".", "auth", "(", "self", ".", "request", ")", "return", "self", ".", "public_readble", ",", "self", ".", "public_w...
34
13.714286
def get_digests(self): '''return a list of layers from a manifest. The function is intended to work with both version 1 and 2 of the schema. All layers (including redundant) are returned. By default, we try version 2 first, then fall back to version 1. For version 1 manifests: ex...
[ "def", "get_digests", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'manifests'", ")", ":", "bot", ".", "error", "(", "'Please retrieve manifests for an image first.'", ")", "sys", ".", "exit", "(", "1", ")", "digests", "=", "[", "]", ...
29
19.818182
def render_template_with_args_in_file(file, template_file_name, **kwargs): """ Get a file and render the content of the template_file_name with kwargs in a file :param file: A File Stream to write :param template_file_name: path to route with template name :param **kwargs: Args to be rendered in tem...
[ "def", "render_template_with_args_in_file", "(", "file", ",", "template_file_name", ",", "*", "*", "kwargs", ")", ":", "template_file_content", "=", "\"\"", ".", "join", "(", "codecs", ".", "open", "(", "template_file_name", ",", "encoding", "=", "'UTF-8'", ")",...
39.266667
17.933333
def first(pipe, items=1): ''' first is essentially the next() function except it's second argument determines how many of the first items you want. If items is more than 1 the output is an islice of the generator. If items is 1, the first item is returned ''' pipe = iter(pipe) re...
[ "def", "first", "(", "pipe", ",", "items", "=", "1", ")", ":", "pipe", "=", "iter", "(", "pipe", ")", "return", "next", "(", "pipe", ")", "if", "items", "==", "1", "else", "islice", "(", "pipe", ",", "0", ",", "items", ")" ]
46.25
27
def connect(*, dsn, autocommit=False, ansi=False, timeout=0, loop=None, executor=None, echo=False, after_created=None, **kwargs): """Accepts an ODBC connection string and returns a new Connection object. The connection string can be passed as the string `str`, as a list of keywords,or a combina...
[ "def", "connect", "(", "*", ",", "dsn", ",", "autocommit", "=", "False", ",", "ansi", "=", "False", ",", "timeout", "=", "0", ",", "loop", "=", "None", ",", "executor", "=", "None", ",", "echo", "=", "False", ",", "after_created", "=", "None", ",",...
57.653846
27.884615
def u16le_list_to_byte_list(data): """! @brief Convert a halfword array into a byte array""" byteData = [] for h in data: byteData.extend([h & 0xff, (h >> 8) & 0xff]) return byteData
[ "def", "u16le_list_to_byte_list", "(", "data", ")", ":", "byteData", "=", "[", "]", "for", "h", "in", "data", ":", "byteData", ".", "extend", "(", "[", "h", "&", "0xff", ",", "(", "h", ">>", "8", ")", "&", "0xff", "]", ")", "return", "byteData" ]
33.5
14
def next(self, acceleration=0.0): """Continue rotation in direction of last drag.""" q = quaternion_slerp(self._qpre, self._qnow, 2.0 + acceleration, False) self._qpre, self._qnow = self._qnow, q
[ "def", "next", "(", "self", ",", "acceleration", "=", "0.0", ")", ":", "q", "=", "quaternion_slerp", "(", "self", ".", "_qpre", ",", "self", ".", "_qnow", ",", "2.0", "+", "acceleration", ",", "False", ")", "self", ".", "_qpre", ",", "self", ".", "...
54
13
def create(self): """ Creates the node. """ log.info("{module}: {name} [{id}] created".format(module=self.manager.module_name, name=self.name, id=self.id))
[ "def", "create", "(", "self", ")", ":", "log", ".", "info", "(", "\"{module}: {name} [{id}] created\"", ".", "format", "(", "module", "=", "self", ".", "manager", ".", "module_name", ",", "name", "=", "self", ".", "name", ",", "id", "=", "self", ".", "...
37.125
23.875
def upscale(file_name, scale=1.5, margin_x=0, margin_y=0, suffix='scaled', tempdir=None): """Upscale a PDF to a large size.""" # Set output file name if tempdir: output = NamedTemporaryFile(suffix='.pdf', dir=tempdir, delete=False).name elif suffix: output = os.path.join(os.path.dirname(...
[ "def", "upscale", "(", "file_name", ",", "scale", "=", "1.5", ",", "margin_x", "=", "0", ",", "margin_y", "=", "0", ",", "suffix", "=", "'scaled'", ",", "tempdir", "=", "None", ")", ":", "# Set output file name", "if", "tempdir", ":", "output", "=", "N...
33.733333
21.6
def copy_file(stream, target, maxread=-1, buffer_size=2*16): ''' Read from :stream and write to :target until :maxread or EOF. ''' size, read = 0, stream.read while 1: to_read = buffer_size if maxread < 0 else min(buffer_size, maxread-size) part = read(to_read) if not part: ...
[ "def", "copy_file", "(", "stream", ",", "target", ",", "maxread", "=", "-", "1", ",", "buffer_size", "=", "2", "*", "16", ")", ":", "size", ",", "read", "=", "0", ",", "stream", ".", "read", "while", "1", ":", "to_read", "=", "buffer_size", "if", ...
37.8
20.8
def propertySearch(self, pid, getall=0): """ Searches this 'GameTree' for nodes containing matching properties. Returns a 'GameTree' containing the matched node(s). Arguments: - pid : string -- ID of properties to search for. - getall : boolean -- Set to true (1) to return all 'Node''s that match, or...
[ "def", "propertySearch", "(", "self", ",", "pid", ",", "getall", "=", "0", ")", ":", "matches", "=", "[", "]", "for", "n", "in", "self", ":", "if", "n", ".", "has_key", "(", "pid", ")", ":", "matches", ".", "append", "(", "n", ")", "if", "not",...
33.736842
16.947368
def generate_nonce_timestamp(): """ Generate unique nonce with counter, uuid and rng.""" global count rng = botan.rng().get(30) uuid4 = uuid.uuid4().bytes # 16 byte tmpnonce = (bytes(str(count).encode('utf-8'))) + uuid4 + rng nonce = tmpnonce[:41] # 41 byte (328 bit) count += 1 return ...
[ "def", "generate_nonce_timestamp", "(", ")", ":", "global", "count", "rng", "=", "botan", ".", "rng", "(", ")", ".", "get", "(", "30", ")", "uuid4", "=", "uuid", ".", "uuid4", "(", ")", ".", "bytes", "# 16 byte", "tmpnonce", "=", "(", "bytes", "(", ...
35.222222
13.888889
def _update_record(self, identifier, rtype=None, name=None, content=None): """Updates the specified record in a new Gandi zone 'content' should be a string or a list of strings """ if self.protocol == 'rpc': return self.rpc_helper.update_record(identifier, rtype, name, conte...
[ "def", "_update_record", "(", "self", ",", "identifier", ",", "rtype", "=", "None", ",", "name", "=", "None", ",", "content", "=", "None", ")", ":", "if", "self", ".", "protocol", "==", "'rpc'", ":", "return", "self", ".", "rpc_helper", ".", "update_re...
43.5625
20.6875
def create_config_file(filename): """ Create main configuration file if it doesn't exist. """ import textwrap from six.moves.urllib import parse if not os.path.exists(filename): old_default_config_file = os.path.join(os.path.dirname(filename), ...
[ "def", "create_config_file", "(", "filename", ")", ":", "import", "textwrap", "from", "six", ".", "moves", ".", "urllib", "import", "parse", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "old_default_config_file", "=", "os", "."...
36.788889
19.988889
def association_pivot(self, association_resource): """Pivot point on association for this resource. This method will return all *resources* (group, indicators, task, victims, etc) for this resource that are associated with the provided resource. **Example Endpoints URI's** +--...
[ "def", "association_pivot", "(", "self", ",", "association_resource", ")", ":", "resource", "=", "self", ".", "copy", "(", ")", "resource", ".", "_request_uri", "=", "'{}/{}'", ".", "format", "(", "association_resource", ".", "request_uri", ",", "resource", "....
65.46875
41.5
def _retrieve_page(self, page_index): """Returns the node of matches to be processed""" params = self._get_params() params["page"] = str(page_index) doc = self._request(self._ws_prefix + ".search", True, params) return doc.getElementsByTagName(self._ws_prefix + "matches")[0]
[ "def", "_retrieve_page", "(", "self", ",", "page_index", ")", ":", "params", "=", "self", ".", "_get_params", "(", ")", "params", "[", "\"page\"", "]", "=", "str", "(", "page_index", ")", "doc", "=", "self", ".", "_request", "(", "self", ".", "_ws_pref...
38.75
18.625
def constant(interval=1): """Generator for constant intervals. Args: interval: A constant value to yield or an iterable of such values. """ try: itr = iter(interval) except TypeError: itr = itertools.repeat(interval) for val in itr: yield val
[ "def", "constant", "(", "interval", "=", "1", ")", ":", "try", ":", "itr", "=", "iter", "(", "interval", ")", "except", "TypeError", ":", "itr", "=", "itertools", ".", "repeat", "(", "interval", ")", "for", "val", "in", "itr", ":", "yield", "val" ]
22.153846
20.538462
def get_missing_params_message(self, parameter_state): """ Get a user-friendly message indicating a missing parameter for the API endpoint. """ params = ', '.join(name for name, present in parameter_state if not present) return self.MISSING_REQUIRED_PARAMS_MSG.format(params)
[ "def", "get_missing_params_message", "(", "self", ",", "parameter_state", ")", ":", "params", "=", "', '", ".", "join", "(", "name", "for", "name", ",", "present", "in", "parameter_state", "if", "not", "present", ")", "return", "self", ".", "MISSING_REQUIRED_P...
51.666667
21.333333
def create(self, using=None, **kwargs): """ Creates the index in elasticsearch. Any additional keyword arguments will be passed to ``Elasticsearch.indices.create`` unchanged. """ self._get_connection(using).indices.create(index=self._name, body=self.to_dict(), **kwargs)
[ "def", "create", "(", "self", ",", "using", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_get_connection", "(", "using", ")", ".", "indices", ".", "create", "(", "index", "=", "self", ".", "_name", ",", "body", "=", "self", ".", ...
39
16.5
def request(req=None, method=None, requires_response=True): """Call function req and then emit its results to the LSP server.""" if req is None: return functools.partial(request, method=method, requires_response=requires_response) @functools.wraps(req) def wrapp...
[ "def", "request", "(", "req", "=", "None", ",", "method", "=", "None", ",", "requires_response", "=", "True", ")", ":", "if", "req", "is", "None", ":", "return", "functools", ".", "partial", "(", "request", ",", "method", "=", "method", ",", "requires_...
40.923077
16.769231
def _populate_cmd_lists(self): """ Populate self.lists and hashes: self.commands, and self.aliases, self.category """ self.commands = {} self.aliases = {} self.category = {} # self.short_help = {} for cmd_instance in self.cmd_instances: if not hasattr(...
[ "def", "_populate_cmd_lists", "(", "self", ")", ":", "self", ".", "commands", "=", "{", "}", "self", ".", "aliases", "=", "{", "}", "self", ".", "category", "=", "{", "}", "# self.short_help = {}", "for", "cmd_instance", "in", "self", ".", "cmd_ins...
36.096774
13.677419
def get_shutit_pexpect_session_from_child(self, shutit_pexpect_child): """Given a pexpect/child object, return the shutit_pexpect_session object. """ shutit_global.shutit_global_object.yield_to_draw() if not isinstance(shutit_pexpect_child, pexpect.pty_spawn.spawn): self.fail('Wrong type in get_shutit_pexpec...
[ "def", "get_shutit_pexpect_session_from_child", "(", "self", ",", "shutit_pexpect_child", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "if", "not", "isinstance", "(", "shutit_pexpect_child", ",", "pexpect", ".", "pty_spawn", ...
66.4
26.3
def check_submission_successful(self, submission_id=None): """Check if the last submission passes submission criteria. Args: submission_id (str, optional): submission of interest, defaults to the last submission done with the account Return: bool: True i...
[ "def", "check_submission_successful", "(", "self", ",", "submission_id", "=", "None", ")", ":", "status", "=", "self", ".", "submission_status", "(", "submission_id", ")", "# need to cast to bool to not return None in some cases.", "success", "=", "bool", "(", "status",...
38.5
22.4
def parse_end_date(self, request, start_date): """ Return period in days after the start date to show event occurrences, which is one of the following in order of priority: - `end_date` GET parameter value, if given and valid. The filtering will be *inclusive* of the end date...
[ "def", "parse_end_date", "(", "self", ",", "request", ",", "start_date", ")", ":", "if", "request", ".", "GET", ".", "get", "(", "'end_date'", ")", ":", "try", ":", "return", "djtz", ".", "parse", "(", "'%s 00:00'", "%", "request", ".", "GET", ".", "...
45.130435
17.130435
def main(): """ upload a package to pypi or gemfury :return: """ setup_main() config = ConfigData(clean=True) try: config.upload() finally: config.clean_after_if_needed()
[ "def", "main", "(", ")", ":", "setup_main", "(", ")", "config", "=", "ConfigData", "(", "clean", "=", "True", ")", "try", ":", "config", ".", "upload", "(", ")", "finally", ":", "config", ".", "clean_after_if_needed", "(", ")" ]
18.909091
15.090909
def paste( self ): """ Pastes text from the clipboard. """ text = nativestring(QApplication.clipboard().text()) for tag in text.split(','): tag = tag.strip() if ( self.isTagValid(tag) ): self.addTag(tag)
[ "def", "paste", "(", "self", ")", ":", "text", "=", "nativestring", "(", "QApplication", ".", "clipboard", "(", ")", ".", "text", "(", ")", ")", "for", "tag", "in", "text", ".", "split", "(", "','", ")", ":", "tag", "=", "tag", ".", "strip", "(",...
30.555556
7.444444
def get_git_remote_url(path='.', remote='origin'): """ Get git remote url :param path: path to repo :param remote: :return: remote url or exception """ return dulwich.repo.Repo.discover(path).get_config()\ .get((b'remote', remote.encode('utf-8')), b'url').decode('utf-8')
[ "def", "get_git_remote_url", "(", "path", "=", "'.'", ",", "remote", "=", "'origin'", ")", ":", "return", "dulwich", ".", "repo", ".", "Repo", ".", "discover", "(", "path", ")", ".", "get_config", "(", ")", ".", "get", "(", "(", "b'remote'", ",", "re...
33.222222
12.777778
def cli(verbose): """ Floyd CLI interacts with FloydHub server and executes your commands. More help is available under each command listed below. """ floyd.floyd_host = floyd.floyd_web_host = "https://dev.floydhub.com" floyd.tus_server_endpoint = "https://upload-v2-dev.floydhub.com/api/v1/uploa...
[ "def", "cli", "(", "verbose", ")", ":", "floyd", ".", "floyd_host", "=", "floyd", ".", "floyd_web_host", "=", "\"https://dev.floydhub.com\"", "floyd", ".", "tus_server_endpoint", "=", "\"https://upload-v2-dev.floydhub.com/api/v1/upload/\"", "configure_logger", "(", "verbo...
41
19.666667
def _rdheader(fp): """ Read header info of the windaq file """ tag = None # The '2' tag indicates the end of tags. while tag != 2: # For each header element, there is a tag indicating data type, # followed by the data size, followed by the data itself. 0's # pad the conte...
[ "def", "_rdheader", "(", "fp", ")", ":", "tag", "=", "None", "# The '2' tag indicates the end of tags.", "while", "tag", "!=", "2", ":", "# For each header element, there is a tag indicating data type,", "# followed by the data size, followed by the data itself. 0's", "# pad the co...
44.1875
15.5875
def _get_major_minor_revision(self, version_string): """Split a version string into major, minor and (optionally) revision parts. This is complicated by the fact that a version string can be something like 3.2b1.""" version = version_string.split(' ')[0].split('.') v_maj...
[ "def", "_get_major_minor_revision", "(", "self", ",", "version_string", ")", ":", "version", "=", "version_string", ".", "split", "(", "' '", ")", "[", "0", "]", ".", "split", "(", "'.'", ")", "v_major", "=", "int", "(", "version", "[", "0", "]", ")", ...
40.5
15.642857
def estimate_hmm(observations, nstates, lag=1, initial_model=None, output=None, reversible=True, stationary=False, p=None, accuracy=1e-3, maxit=1000, maxit_P=100000, mincount_connectivity=1e-2): r""" Estimate maximum-likelihood HMM Generic maximum-likelihood estimation of HMMs...
[ "def", "estimate_hmm", "(", "observations", ",", "nstates", ",", "lag", "=", "1", ",", "initial_model", "=", "None", ",", "output", "=", "None", ",", "reversible", "=", "True", ",", "stationary", "=", "False", ",", "p", "=", "None", ",", "accuracy", "=...
49.78125
31.046875
def make_python_patterns(additional_keywords=[], additional_builtins=[]): """Strongly inspired from idlelib.ColorDelegator.make_pat""" kw = r"\b" + any("keyword", kwlist + additional_keywords) + r"\b" kw_namespace = r"\b" + any("namespace", kw_namespace_list) + r"\b" word_operators = r"\b" + any("operat...
[ "def", "make_python_patterns", "(", "additional_keywords", "=", "[", "]", ",", "additional_builtins", "=", "[", "]", ")", ":", "kw", "=", "r\"\\b\"", "+", "any", "(", "\"keyword\"", ",", "kwlist", "+", "additional_keywords", ")", "+", "r\"\\b\"", "kw_namespace...
58.864865
17.783784
def save(self, *args, **kwargs): """ Before saving, execute 'perform_bulk_pubmed_query()'. """ self.perform_bulk_pubmed_query() super().save(*args, **kwargs)
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "perform_bulk_pubmed_query", "(", ")", "super", "(", ")", ".", "save", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
32
5.333333
def _round(self, number): """ Helper function for rounding-as-taught-in-school (X.5 rounds to X+1 if positive). Python 3 now rounds 0.5 to whichever side is even (i.e. 2.5 rounds to 2). :param int number: a float to round. :return: closest integer to number, rounding tie...
[ "def", "_round", "(", "self", ",", "number", ")", ":", "sign", "=", "1", "if", "number", ">=", "0", "else", "-", "1", "rounded", "=", "int", "(", "round", "(", "number", ")", ")", "nextRounded", "=", "int", "(", "round", "(", "number", "+", "1", ...
39.148148
17.222222
def imshow(self, key): """Show item's image""" data = self.model.get_data() import spyder.pyplot as plt plt.figure() plt.imshow(data[key]) plt.show()
[ "def", "imshow", "(", "self", ",", "key", ")", ":", "data", "=", "self", ".", "model", ".", "get_data", "(", ")", "import", "spyder", ".", "pyplot", "as", "plt", "plt", ".", "figure", "(", ")", "plt", ".", "imshow", "(", "data", "[", "key", "]", ...
28.142857
10.714286
def add(self, isoel, col1, col2, channel_width, flow_rate, viscosity, method): """Add isoelastics Parameters ---------- isoel: list of ndarrays Each list item resembles one isoelastic line stored as an array of shape (N,3). The last column contains ...
[ "def", "add", "(", "self", ",", "isoel", ",", "col1", ",", "col2", ",", "channel_width", ",", "flow_rate", ",", "viscosity", ",", "method", ")", ":", "if", "method", "not", "in", "VALID_METHODS", ":", "validstr", "=", "\",\"", ".", "join", "(", "VALID_...
34.866667
15.716667
def request(self, url, method = u"get", data = None, headers = None, **kwargs): """ public method for doing the live request """ url, method, data, headers, kwargs = self._pre_request(url, method=method, ...
[ "def", "request", "(", "self", ",", "url", ",", "method", "=", "u\"get\"", ",", "data", "=", "None", ",", "headers", "=", "None", ",", "*", "*", "kwargs", ")", ":", "url", ",", "method", ",", "data", ",", "headers", ",", "kwargs", "=", "self", "....
46.764706
24.411765
def _authorization_headers_valid(self, token_type, token): """Verify authorization headers for a request. Parameters token_type (str) Type of token to access resources. token (str) Server Token or OAuth 2.0 Access Token. Returns ...
[ "def", "_authorization_headers_valid", "(", "self", ",", "token_type", ",", "token", ")", ":", "if", "token_type", "not", "in", "http", ".", "VALID_TOKEN_TYPES", ":", "return", "False", "allowed_chars", "=", "ascii_letters", "+", "digits", "+", "'_'", "+", "'-...
36.666667
19.055556
def order_verification(self, institute, case, user, link, variant): """Create an event for a variant verification for a variant and an event for a variant verification for a case Arguments: institute (dict): A Institute object case (dict): Case object user (d...
[ "def", "order_verification", "(", "self", ",", "institute", ",", "case", ",", "user", ",", "link", ",", "variant", ")", ":", "LOG", ".", "info", "(", "\"Creating event for ordering validation for variant\"", "\" {0}\"", ".", "format", "(", "variant", "[", "'disp...
31.458333
17.791667
def dump(self, itemkey, filename=None, path=None): """ Dump a file attachment to disk, with optional filename and path """ if not filename: filename = self.item(itemkey)["data"]["filename"] if path: pth = os.path.join(path, filename) else: ...
[ "def", "dump", "(", "self", ",", "itemkey", ",", "filename", "=", "None", ",", "path", "=", "None", ")", ":", "if", "not", "filename", ":", "filename", "=", "self", ".", "item", "(", "itemkey", ")", "[", "\"data\"", "]", "[", "\"filename\"", "]", "...
31.8125
13.0625
def is_compatible(self, obj): """Check if characters can be combined into a textline We consider characters compatible if: - the Unicode mapping is known, and both have the same render mode - the Unicode mapping is unknown but both are part of the same font """ b...
[ "def", "is_compatible", "(", "self", ",", "obj", ")", ":", "both_unicode_mapped", "=", "isinstance", "(", "self", ".", "_text", ",", "str", ")", "and", "isinstance", "(", "obj", ".", "_text", ",", "str", ")", "try", ":", "if", "both_unicode_mapped", ":",...
43.6875
18.5
def env(): """Verify PCI variables and construct exported variables""" if cij.ssh.env(): cij.err("cij.pci.env: invalid SSH environment") return 1 pci = cij.env_to_dict(PREFIX, REQUIRED) pci["BUS_PATH"] = "/sys/bus/pci" pci["DEV_PATH"] = os.sep.join([pci["BUS_PATH"], "devices", pci...
[ "def", "env", "(", ")", ":", "if", "cij", ".", "ssh", ".", "env", "(", ")", ":", "cij", ".", "err", "(", "\"cij.pci.env: invalid SSH environment\"", ")", "return", "1", "pci", "=", "cij", ".", "env_to_dict", "(", "PREFIX", ",", "REQUIRED", ")", "pci", ...
25.133333
24.266667
def create_node(self, config_file=None, seed=None, tags=None): """ Set up a CondorDagmanNode class to run ``pycbc_create_injections``. Parameters ---------- config_file : pycbc.workflow.core.File A ``pycbc.workflow.core.File`` for inference configuration file to ...
[ "def", "create_node", "(", "self", ",", "config_file", "=", "None", ",", "seed", "=", "None", ",", "tags", "=", "None", ")", ":", "# default for tags is empty list", "tags", "=", "[", "]", "if", "tags", "is", "None", "else", "tags", "# get analysis start and...
35.864865
18.567568
def fasta_files_equal(seq_file1, seq_file2): """Check equality of a FASTA file to another FASTA file Args: seq_file1: Path to a FASTA file seq_file2: Path to another FASTA file Returns: bool: If the sequences are the same """ # Load already set representative sequence ...
[ "def", "fasta_files_equal", "(", "seq_file1", ",", "seq_file2", ")", ":", "# Load already set representative sequence", "seq1", "=", "SeqIO", ".", "read", "(", "open", "(", "seq_file1", ")", ",", "'fasta'", ")", "# Load kegg sequence", "seq2", "=", "SeqIO", ".", ...
22.913043
19.26087
def get_temp_filename(suffix=None): """ return a string in the form of temp_X, where X is a large integer """ file = tempfile.mkstemp(suffix=suffix or "", prefix="temp_", dir=os.getcwd()) # or "" for Python 2 compatibility os.close(file[0]) return file[1]
[ "def", "get_temp_filename", "(", "suffix", "=", "None", ")", ":", "file", "=", "tempfile", ".", "mkstemp", "(", "suffix", "=", "suffix", "or", "\"\"", ",", "prefix", "=", "\"temp_\"", ",", "dir", "=", "os", ".", "getcwd", "(", ")", ")", "# or \"\" for ...
53.4
24.4
def openssh_tunnel(lport, rport, server, remoteip='127.0.0.1', keyfile=None, password=None, timeout=60): """Create an ssh tunnel using command-line ssh that connects port lport on this machine to localhost:rport on server. The tunnel will automatically close when not in use, remaining open for a minimu...
[ "def", "openssh_tunnel", "(", "lport", ",", "rport", ",", "server", ",", "remoteip", "=", "'127.0.0.1'", ",", "keyfile", "=", "None", ",", "password", "=", "None", ",", "timeout", "=", "60", ")", ":", "if", "pexpect", "is", "None", ":", "raise", "Impor...
39.901408
22.098592
def pre_fork(self, process_manager): ''' Pre-fork we need to create the zmq router device ''' salt.transport.mixins.auth.AESReqServerMixin.pre_fork(self, process_manager) if USE_LOAD_BALANCER: self.socket_queue = multiprocessing.Queue() process_manager.add...
[ "def", "pre_fork", "(", "self", ",", "process_manager", ")", ":", "salt", ".", "transport", ".", "mixins", ".", "auth", ".", "AESReqServerMixin", ".", "pre_fork", "(", "self", ",", "process_manager", ")", "if", "USE_LOAD_BALANCER", ":", "self", ".", "socket_...
49.1875
21.8125
def gen_filter(name, op, value, is_or=False): """Generates a single filter expression for ``filter[]``.""" if op not in OPERATORS: raise ValueError('Unknown operator {}'.format(op)) result = u'{} {} {}'.format(name, op, escape_filter(value)) if is_or: result = u'or ' + result return ...
[ "def", "gen_filter", "(", "name", ",", "op", ",", "value", ",", "is_or", "=", "False", ")", ":", "if", "op", "not", "in", "OPERATORS", ":", "raise", "ValueError", "(", "'Unknown operator {}'", ".", "format", "(", "op", ")", ")", "result", "=", "u'{} {}...
39.875
14.625
def get_entity_from_dimensions(dimensions, text): """ Infer the underlying entity of a unit (e.g. "volume" for "m^3"). Just based on the unit's dimensionality if the classifier is disabled. """ new_dimensions = [{'base': l.NAMES[i['base']].entity.name, 'power': i['power']} fo...
[ "def", "get_entity_from_dimensions", "(", "dimensions", ",", "text", ")", ":", "new_dimensions", "=", "[", "{", "'base'", ":", "l", ".", "NAMES", "[", "i", "[", "'base'", "]", "]", ".", "entity", ".", "name", ",", "'power'", ":", "i", "[", "'power'", ...
34.181818
22.727273
def from_dict(data, ctx): """ Instantiate a new AccountSummary from a dict (generally from loading a JSON response). The data used to instantiate the AccountSummary is a shallow copy of the dict passed in, with any complex child types instantiated appropriately. """ ...
[ "def", "from_dict", "(", "data", ",", "ctx", ")", ":", "data", "=", "data", ".", "copy", "(", ")", "if", "data", ".", "get", "(", "'balance'", ")", "is", "not", "None", ":", "data", "[", "'balance'", "]", "=", "ctx", ".", "convert_decimal_number", ...
34.144144
21.567568
def overlap(self, other): """ Returns True if both ranges share any points. >>> intrange(1, 10).overlap(intrange(5, 15)) True >>> intrange(1, 5).overlap(intrange(5, 10)) False This is the same as the ``&&`` operator for two ranges in PostgreSQL. ...
[ "def", "overlap", "(", "self", ",", "other", ")", ":", "# Special case for empty ranges", "if", "not", "self", "or", "not", "other", ":", "return", "False", "if", "self", "<", "other", ":", "a", ",", "b", "=", "self", ",", "other", "else", ":", "a", ...
33.382353
22.617647
def maybe_base_expanded_node_name(self, node_name): """Expand the base name if there are node names nested under the node. For example, if there are two nodes in the graph, "a" and "a/read", then calling this function on "a" will give "a/(a)", a form that points at a leaf node in the nested TensorBoard...
[ "def", "maybe_base_expanded_node_name", "(", "self", ",", "node_name", ")", ":", "with", "self", ".", "_node_name_lock", ":", "# Lazily populate the map from original node name to base-expanded ones.", "if", "self", ".", "_maybe_base_expanded_node_names", "is", "None", ":", ...
41.484848
22.545455
def _get_groups(self): """ Returns an _LDAPUserGroups object, which can determine group membership. """ if self._groups is None: self._groups = _LDAPUserGroups(self) return self._groups
[ "def", "_get_groups", "(", "self", ")", ":", "if", "self", ".", "_groups", "is", "None", ":", "self", ".", "_groups", "=", "_LDAPUserGroups", "(", "self", ")", "return", "self", ".", "_groups" ]
26.444444
15.111111
def register_warning_code(code, exception_type, domain='core'): """Register a new warning code""" Logger._warning_code_to_exception[code] = (exception_type, domain) Logger._domain_codes[domain].add(code)
[ "def", "register_warning_code", "(", "code", ",", "exception_type", ",", "domain", "=", "'core'", ")", ":", "Logger", ".", "_warning_code_to_exception", "[", "code", "]", "=", "(", "exception_type", ",", "domain", ")", "Logger", ".", "_domain_codes", "[", "dom...
56
15.75
def filedet(name, fobj=None, suffix=None): """ Detect file type by filename. :param name: file name :param fobj: file object :param suffix: file suffix like ``py``, ``.py`` :return: file type full name, such as ``python``, ``bash`` """ name = name or (fobj and fobj.name) or suffix s...
[ "def", "filedet", "(", "name", ",", "fobj", "=", "None", ",", "suffix", "=", "None", ")", ":", "name", "=", "name", "or", "(", "fobj", "and", "fobj", ".", "name", ")", "or", "suffix", "separated", "=", "name", ".", "split", "(", "'.'", ")", "if",...
29.75
12.875
def basis_comparison_report(bs1, bs2, uncontract_general=False): ''' Compares two basis set dictionaries and prints a report about their differences ''' all_bs1 = list(bs1['elements'].keys()) if uncontract_general: bs1 = manip.uncontract_general(bs1) bs2 = manip.uncontract_general(...
[ "def", "basis_comparison_report", "(", "bs1", ",", "bs2", ",", "uncontract_general", "=", "False", ")", ":", "all_bs1", "=", "list", "(", "bs1", "[", "'elements'", "]", ".", "keys", "(", ")", ")", "if", "uncontract_general", ":", "bs1", "=", "manip", "."...
39.532468
22.519481
def convert_to_cluster_template(self, plugin_name, hadoop_version, template_name, filecontent): """Convert to cluster template Create Cluster Template directly, avoiding Cluster Template mechanism. """ resp = self.api.post('/plugins/%s/%s/conv...
[ "def", "convert_to_cluster_template", "(", "self", ",", "plugin_name", ",", "hadoop_version", ",", "template_name", ",", "filecontent", ")", ":", "resp", "=", "self", ".", "api", ".", "post", "(", "'/plugins/%s/%s/convert-config/%s'", "%", "(", "plugin_name", ",",...
45.611111
17.777778
def is_empty(self): """ Test interval emptiness. :return: True if interval is empty, False otherwise. """ return ( self._lower > self._upper or (self._lower == self._upper and (self._left == OPEN or self._right == OPEN)) )
[ "def", "is_empty", "(", "self", ")", ":", "return", "(", "self", ".", "_lower", ">", "self", ".", "_upper", "or", "(", "self", ".", "_lower", "==", "self", ".", "_upper", "and", "(", "self", ".", "_left", "==", "OPEN", "or", "self", ".", "_right", ...
28.6
19.2
def json(self, **kwargs): """Returns the json-encoded content of a response, if any. :param \*\*kwargs: Optional arguments that ``json.loads`` takes. """ if not self.encoding and len(self.content) > 3: # No encoding set. JSON RFC 4627 section 3 states we should expect ...
[ "def", "json", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "encoding", "and", "len", "(", "self", ".", "content", ")", ">", "3", ":", "# No encoding set. JSON RFC 4627 section 3 states we should expect", "# UTF-8, -16 or -32. Detect w...
47.5
22.181818
def get_type_name(self): """ Returns the type name of the PKCS7 structure :return: A string with the typename """ nid = _lib.OBJ_obj2nid(self._pkcs7.type) string_type = _lib.OBJ_nid2sn(nid) return _ffi.string(string_type)
[ "def", "get_type_name", "(", "self", ")", ":", "nid", "=", "_lib", ".", "OBJ_obj2nid", "(", "self", ".", "_pkcs7", ".", "type", ")", "string_type", "=", "_lib", ".", "OBJ_nid2sn", "(", "nid", ")", "return", "_ffi", ".", "string", "(", "string_type", ")...
30
9.111111
def add_file(self, path, parent=None, tree=TreeType.SOURCE_ROOT, target_name=None, force=True, file_options=FileOptions()): """ Adds a file to the project, taking care of the type of the file and creating additional structures depending on the file type. For instance, frameworks will be linked, ...
[ "def", "add_file", "(", "self", ",", "path", ",", "parent", "=", "None", ",", "tree", "=", "TreeType", ".", "SOURCE_ROOT", ",", "target_name", "=", "None", ",", "force", "=", "True", ",", "file_options", "=", "FileOptions", "(", ")", ")", ":", "results...
56.847826
35.065217
def ToDeltas(self): """Convert the sequence to the sequence of differences between points. The value of each point v[i] is replaced by v[i+1] - v[i], except for the last point which is dropped. """ if len(self.data) < 2: self.data = [] return for i in range(0, len(self.data) - 1): ...
[ "def", "ToDeltas", "(", "self", ")", ":", "if", "len", "(", "self", ".", "data", ")", "<", "2", ":", "self", ".", "data", "=", "[", "]", "return", "for", "i", "in", "range", "(", "0", ",", "len", "(", "self", ".", "data", ")", "-", "1", ")"...
33.2
18.333333
def _offset(value): """Parse timezone to offset in seconds. Args: value: A timezone in the '+0000' format. An integer would also work. Returns: The timezone offset from GMT in seconds as an integer. """ o = int(value) if o == 0: return 0 a = abs(o) s = a*36+(a%1...
[ "def", "_offset", "(", "value", ")", ":", "o", "=", "int", "(", "value", ")", "if", "o", "==", "0", ":", "return", "0", "a", "=", "abs", "(", "o", ")", "s", "=", "a", "*", "36", "+", "(", "a", "%", "100", ")", "*", "24", "return", "(", ...
22.133333
23.6
def value_loss_given_predictions(value_prediction, rewards, reward_mask, gamma=0.99): """Computes the value loss given the prediction of the value function. Args: value_prediction: np.ndarray of shape (B, T+1, 1)...
[ "def", "value_loss_given_predictions", "(", "value_prediction", ",", "rewards", ",", "reward_mask", ",", "gamma", "=", "0.99", ")", ":", "B", ",", "T", "=", "rewards", ".", "shape", "# pylint: disable=invalid-name", "assert", "(", "B", ",", "T", ")", "==", "...
38.296296
18.925926
def update(self): """ Update this `~photutils.isophote.EllipseSample` instance. This method calls the :meth:`~photutils.isophote.EllipseSample.extract` method to get the values that match the current ``geometry`` attribute, and then computes the the mean intensity, local...
[ "def", "update", "(", "self", ")", ":", "step", "=", "self", ".", "geometry", ".", "astep", "# Update the mean value first, using extraction from main sample.", "s", "=", "self", ".", "extract", "(", ")", "self", ".", "mean", "=", "np", ".", "mean", "(", "s"...
42.040816
22.77551
def map_azure_exceptions(key=None, exc_pass=()): """Map Azure-specific exceptions to the simplekv-API.""" from azure.common import AzureMissingResourceHttpError, AzureHttpError,\ AzureException try: yield except AzureMissingResourceHttpError as ex: if ex.__class__.__name__ not in...
[ "def", "map_azure_exceptions", "(", "key", "=", "None", ",", "exc_pass", "=", "(", ")", ")", ":", "from", "azure", ".", "common", "import", "AzureMissingResourceHttpError", ",", "AzureHttpError", ",", "AzureException", "try", ":", "yield", "except", "AzureMissin...
39.5
13.833333
def get_otp(hsm, args): """ Get OTP from YubiKey. """ if args.no_otp: return None if hsm.version.have_unlock(): if args.stdin: otp = sys.stdin.readline() while otp and otp[-1] == '\n': otp = otp[:-1] else: otp = raw_input('Enter adm...
[ "def", "get_otp", "(", "hsm", ",", "args", ")", ":", "if", "args", ".", "no_otp", ":", "return", "None", "if", "hsm", ".", "version", ".", "have_unlock", "(", ")", ":", "if", "args", ".", "stdin", ":", "otp", "=", "sys", ".", "stdin", ".", "readl...
33.176471
17.705882
def netloc(self): """Network location including host and port""" if self.port: return '%s:%d' % (self.host, self.port) return self.host
[ "def", "netloc", "(", "self", ")", ":", "if", "self", ".", "port", ":", "return", "'%s:%d'", "%", "(", "self", ".", "host", ",", "self", ".", "port", ")", "return", "self", ".", "host" ]
33.4
13.8
def create_default_file(cls, data=None, mode=None): """Create a config file and override data if specified.""" filepath = cls.get_default_filepath() if not filepath: return False filename = os.path.basename(filepath) config = read_file(get_data_path(), filename) ...
[ "def", "create_default_file", "(", "cls", ",", "data", "=", "None", ",", "mode", "=", "None", ")", ":", "filepath", "=", "cls", ".", "get_default_filepath", "(", ")", "if", "not", "filepath", ":", "return", "False", "filename", "=", "os", ".", "path", ...
31.033333
15.766667
def iconcat(a, b): "Same as a += b, for a and b sequences." if not hasattr(a, '__getitem__'): msg = "'%s' object can't be concatenated" % type(a).__name__ raise TypeError(msg) a += b return a
[ "def", "iconcat", "(", "a", ",", "b", ")", ":", "if", "not", "hasattr", "(", "a", ",", "'__getitem__'", ")", ":", "msg", "=", "\"'%s' object can't be concatenated\"", "%", "type", "(", "a", ")", ".", "__name__", "raise", "TypeError", "(", "msg", ")", "...
31
18.142857
def _fix_reindent(self, result): """Fix a badly indented line. This is done by adding or removing from its initial indent only. """ num_indent_spaces = int(result['info'].split()[1]) line_index = result['line'] - 1 target = self.source[line_index] self.source[l...
[ "def", "_fix_reindent", "(", "self", ",", "result", ")", ":", "num_indent_spaces", "=", "int", "(", "result", "[", "'info'", "]", ".", "split", "(", ")", "[", "1", "]", ")", "line_index", "=", "result", "[", "'line'", "]", "-", "1", "target", "=", ...
33.090909
19.454545
def save_task_info(self, res, mem_gb=0): """ :param self: an object with attributes .hdf5, .argnames, .sent :parent res: a :class:`Result` object :param mem_gb: memory consumption at the saving time (optional) """ mon = res.mon name = mon.operation[6:] # strip 'total ' if self.hdf5: ...
[ "def", "save_task_info", "(", "self", ",", "res", ",", "mem_gb", "=", "0", ")", ":", "mon", "=", "res", ".", "mon", "name", "=", "mon", ".", "operation", "[", "6", ":", "]", "# strip 'total '", "if", "self", ".", "hdf5", ":", "mon", ".", "hdf5", ...
41.733333
15.6
def get_choices(self): """stub""" # ideally would return a displayText object in text ... except for legacy # use cases like OEA, it expects a text string. choices = [] # for current_choice in self.my_osid_object.object_map['choices']: for current_choice in self.my_osid_o...
[ "def", "get_choices", "(", "self", ")", ":", "# ideally would return a displayText object in text ... except for legacy", "# use cases like OEA, it expects a text string.", "choices", "=", "[", "]", "# for current_choice in self.my_osid_object.object_map['choices']:", "for", "current_cho...
46.066667
19.8
def _calculate_price_by_slippage(self, action: str, price: float) -> float: """ 计算考虑滑点之后的价格 :param action: 交易动作, 支持 ['buy', 'sell'] :param price: 原始交易价格 :return: 考虑滑点后的交易价格 """ if action == "buy": return price * (1 + self.slippage) if action ==...
[ "def", "_calculate_price_by_slippage", "(", "self", ",", "action", ":", "str", ",", "price", ":", "float", ")", "->", "float", ":", "if", "action", "==", "\"buy\"", ":", "return", "price", "*", "(", "1", "+", "self", ".", "slippage", ")", "if", "action...
32.083333
12.083333
def loggers(self): """Return all the loggers that should be activated""" ret = [] if self.logger_name: if isinstance(self.logger_name, logging.Logger): ret.append((self.logger_name.name, self.logger_name)) else: ret.append((self.logger_name...
[ "def", "loggers", "(", "self", ")", ":", "ret", "=", "[", "]", "if", "self", ".", "logger_name", ":", "if", "isinstance", "(", "self", ".", "logger_name", ",", "logging", ".", "Logger", ")", ":", "ret", ".", "append", "(", "(", "self", ".", "logger...
38.538462
23.076923
def iscm_md_update_dict(self, keypath, data): """ Update a metadata dictionary entry """ current = self.metadata for k in string.split(keypath, "."): if not current.has_key(k): current[k] = {} current = current[k] current.update(dat...
[ "def", "iscm_md_update_dict", "(", "self", ",", "keypath", ",", "data", ")", ":", "current", "=", "self", ".", "metadata", "for", "k", "in", "string", ".", "split", "(", "keypath", ",", "\".\"", ")", ":", "if", "not", "current", ".", "has_key", "(", ...
31.3
5.1
def download(sid, credentials=None, subjects_path=None, overwrite=False, release='HCP_1200', database='hcp-openaccess', file_list=None): ''' download(sid) downloads the data for subject with the given subject id. By default, the subject will be placed in the first HCP subject directory in the...
[ "def", "download", "(", "sid", ",", "credentials", "=", "None", ",", "subjects_path", "=", "None", ",", "overwrite", "=", "False", ",", "release", "=", "'HCP_1200'", ",", "database", "=", "'hcp-openaccess'", ",", "file_list", "=", "None", ")", ":", "if", ...
60.266667
30.233333
def prepare_notebook_context(request, notebook_context): """Fill in notebook context with default values.""" if not notebook_context: notebook_context = {} # Override notebook Jinja templates if "extra_template_paths" not in notebook_context: notebook_context["extra_template_paths"] = ...
[ "def", "prepare_notebook_context", "(", "request", ",", "notebook_context", ")", ":", "if", "not", "notebook_context", ":", "notebook_context", "=", "{", "}", "# Override notebook Jinja templates", "if", "\"extra_template_paths\"", "not", "in", "notebook_context", ":", ...
46.804878
34.341463
def git_checkout(git_branch=None, locale_root=None): """ Checkouts branch to last commit :param git_branch: branch to checkout :param locale_root: locale folder path :return: tuple stdout, stderr of completed command """ if git_branch is None: git_branch = settings.GIT_BRANCH if ...
[ "def", "git_checkout", "(", "git_branch", "=", "None", ",", "locale_root", "=", "None", ")", ":", "if", "git_branch", "is", "None", ":", "git_branch", "=", "settings", ".", "GIT_BRANCH", "if", "locale_root", "is", "None", ":", "locale_root", "=", "settings",...
32.941176
11.882353
def neurite_root_section_ids(self): '''Get the section IDs of the intitial neurite sections''' sec = self.sections return [i for i, ss in enumerate(sec) if ss.pid > -1 and (sec[ss.pid].ntype == POINT_TYPE.SOMA and ss.ntype != POINT_TYPE.SOMA)]
[ "def", "neurite_root_section_ids", "(", "self", ")", ":", "sec", "=", "self", ".", "sections", "return", "[", "i", "for", "i", ",", "ss", "in", "enumerate", "(", "sec", ")", "if", "ss", ".", "pid", ">", "-", "1", "and", "(", "sec", "[", "ss", "."...
52.333333
18.333333
def recalculate_checksums(self, flags=0): """ (Re)calculates the checksum for any IPv4/ICMP/ICMPv6/TCP/UDP checksum present in the given packet. Individual checksum calculations may be disabled via the appropriate flag. Typically this function should be invoked on a modified packet befor...
[ "def", "recalculate_checksums", "(", "self", ",", "flags", "=", "0", ")", ":", "buff", ",", "buff_", "=", "self", ".", "__to_buffers", "(", ")", "num", "=", "windivert_dll", ".", "WinDivertHelperCalcChecksums", "(", "ctypes", ".", "byref", "(", "buff_", ")...
51.785714
28.357143