text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def selection(self): """ Selection property. :return: None if no font is selected and font family name if one is selected. :rtype: None or str """ if self._font.get() is "" or self._font.get() not in self._fonts: return None else: ...
[ "def", "selection", "(", "self", ")", ":", "if", "self", ".", "_font", ".", "get", "(", ")", "is", "\"\"", "or", "self", ".", "_font", ".", "get", "(", ")", "not", "in", "self", ".", "_fonts", ":", "return", "None", "else", ":", "return", "self",...
30.272727
18.636364
def validate(self): """ Execute the code once to get it's results (to be used in function validation). Compare the result to the first function in the group. """ validation_code = self.setup_src + '\nvalidation_result = ' + self.stmt validation_scope = {} exec(val...
[ "def", "validate", "(", "self", ")", ":", "validation_code", "=", "self", ".", "setup_src", "+", "'\\nvalidation_result = '", "+", "self", ".", "stmt", "validation_scope", "=", "{", "}", "exec", "(", "validation_code", ",", "validation_scope", ")", "# Store the ...
60.068966
31.103448
def Load(self): """Loads all new events from disk as raw serialized proto bytestrings. Calling Load multiple times in a row will not 'drop' events as long as the return value is not iterated over. Yields: All event proto bytestrings in the file that have not been yielded yet. """ logger....
[ "def", "Load", "(", "self", ")", ":", "logger", ".", "debug", "(", "'Loading events from %s'", ",", "self", ".", "_file_path", ")", "# GetNext() expects a status argument on TF <= 1.7.", "get_next_args", "=", "inspect", ".", "getargspec", "(", "self", ".", "_reader"...
39.225806
23.83871
def _diff_image(slice1, slice2, abs_value=True, cmap='gray', **kwargs): """Computes the difference image""" diff = slice1 - slice2 if abs_value: diff = np.abs(diff) return diff, cmap
[ "def", "_diff_image", "(", "slice1", ",", "slice2", ",", "abs_value", "=", "True", ",", "cmap", "=", "'gray'", ",", "*", "*", "kwargs", ")", ":", "diff", "=", "slice1", "-", "slice2", "if", "abs_value", ":", "diff", "=", "np", ".", "abs", "(", "dif...
20.5
19.416667
def get_trust_id(self): """Gets the ``Trust`` ``Id`` for this authorization. return: (osid.id.Id) - the trust ``Id`` raise: IllegalState - ``has_trust()`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid...
[ "def", "get_trust_id", "(", "self", ")", ":", "# Implemented from template for osid.resource.Resource.get_avatar_id_template", "if", "not", "bool", "(", "self", ".", "_my_map", "[", "'trustId'", "]", ")", ":", "raise", "errors", ".", "IllegalState", "(", "'this Author...
40.692308
20.384615
def _validate_device(device): ''' Ensure the device name supplied is valid in a manner similar to the `exists` function, but raise errors on invalid input rather than return False. This function only validates a block device, it does not check if the block device is a drive or a partition or a ...
[ "def", "_validate_device", "(", "device", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "device", ")", ":", "dev", "=", "os", ".", "stat", "(", "device", ")", ".", "st_mode", "if", "stat", ".", "S_ISBLK", "(", "dev", ")", ":", "return", ...
29.944444
25.055556
def paste(self): """Reimplement Qt method""" if self.has_selected_text(): self.remove_selected_text() self.insert_text(QApplication.clipboard().text())
[ "def", "paste", "(", "self", ")", ":", "if", "self", ".", "has_selected_text", "(", ")", ":", "self", ".", "remove_selected_text", "(", ")", "self", ".", "insert_text", "(", "QApplication", ".", "clipboard", "(", ")", ".", "text", "(", ")", ")" ]
36.6
9.2
def opsview_info(self, verbose=False): ''' Get information about the current opsview instance http://docs.opsview.com/doku.php?id=opsview4.6:restapi#opsview_information ''' url = '{}/{}'.format(self.rest_url, 'info') return self.__auth_req_get(url, verbose=verbose)
[ "def", "opsview_info", "(", "self", ",", "verbose", "=", "False", ")", ":", "url", "=", "'{}/{}'", ".", "format", "(", "self", ".", "rest_url", ",", "'info'", ")", "return", "self", ".", "__auth_req_get", "(", "url", ",", "verbose", "=", "verbose", ")"...
43.857143
21
def clone(git_uri): """ Clone a remote git repository to a local path. :param git_uri: the URI to the git repository to be cloned :return: the generated local path where the repository has been cloned to """ hash_digest = sha256_hash(git_uri) local_path = home_directory_path(FOLDER, hash_di...
[ "def", "clone", "(", "git_uri", ")", ":", "hash_digest", "=", "sha256_hash", "(", "git_uri", ")", "local_path", "=", "home_directory_path", "(", "FOLDER", ",", "hash_digest", ")", "exists_locally", "=", "path_exists", "(", "local_path", ")", "if", "not", "exis...
31.722222
18.388889
def set_image_options(self, args=None, figsize="6x6", dpi=300, format="pdf", font="Helvetica", palette="deep", style="darkgrid", cmap="jet"): """ Add image format options for given command line programs. """ from jcvi.graphics.base impo...
[ "def", "set_image_options", "(", "self", ",", "args", "=", "None", ",", "figsize", "=", "\"6x6\"", ",", "dpi", "=", "300", ",", "format", "=", "\"pdf\"", ",", "font", "=", "\"Helvetica\"", ",", "palette", "=", "\"deep\"", ",", "style", "=", "\"darkgrid\"...
45.6
23.688889
def execute_runner_async(runner, workunit_factory=None, workunit_name=None, workunit_labels=None, workunit_log_config=None): """Executes the given java runner asynchronously. We can't use 'with' here because the workunit_generator's __exit__ function must be called after the process exit...
[ "def", "execute_runner_async", "(", "runner", ",", "workunit_factory", "=", "None", ",", "workunit_name", "=", "None", ",", "workunit_labels", "=", "None", ",", "workunit_log_config", "=", "None", ")", ":", "if", "not", "isinstance", "(", "runner", ",", "Execu...
41.467742
27.5
def _infer_from_metaclass_constructor(cls, func): """Try to infer what the given *func* constructor is building :param astroid.FunctionDef func: A metaclass constructor. Metaclass definitions can be functions, which should accept three arguments, the name of the class, the bases of the ...
[ "def", "_infer_from_metaclass_constructor", "(", "cls", ",", "func", ")", ":", "context", "=", "astroid", ".", "context", ".", "InferenceContext", "(", ")", "class_bases", "=", "astroid", ".", "List", "(", ")", "class_bases", ".", "postinit", "(", "elts", "=...
35.714286
18.685714
def decode(text): """ Function to decode a text. @param text text to decode (string) @return decoded text and encoding """ try: if text.startswith(BOM_UTF8): # UTF-8 with BOM return to_text_string(text[len(BOM_UTF8):], 'utf-8'), 'utf-8-bom' elif ...
[ "def", "decode", "(", "text", ")", ":", "try", ":", "if", "text", ".", "startswith", "(", "BOM_UTF8", ")", ":", "# UTF-8 with BOM\r", "return", "to_text_string", "(", "text", "[", "len", "(", "BOM_UTF8", ")", ":", "]", ",", "'utf-8'", ")", ",", "'utf-8...
35.892857
14.607143
def delete(self, force=False): """Delete a record and also remove the RecordsBuckets if necessary. :param force: True to remove also the :class:`~invenio_records_files.models.RecordsBuckets` object. :returns: Deleted record. """ if force: RecordsBuckets.q...
[ "def", "delete", "(", "self", ",", "force", "=", "False", ")", ":", "if", "force", ":", "RecordsBuckets", ".", "query", ".", "filter_by", "(", "record", "=", "self", ".", "model", ",", "bucket", "=", "self", ".", "files", ".", "bucket", ")", ".", "...
36.230769
11.769231
def _sign(self, data: bytes) -> bytes: """ Use eth_sign compatible hasher to sign matrix data """ assert self._raiden_service is not None return self._raiden_service.signer.sign(data=data)
[ "def", "_sign", "(", "self", ",", "data", ":", "bytes", ")", "->", "bytes", ":", "assert", "self", ".", "_raiden_service", "is", "not", "None", "return", "self", ".", "_raiden_service", ".", "signer", ".", "sign", "(", "data", "=", "data", ")" ]
52.25
6.75
def add_simple_rnn(self,name, W_h, W_x, b, hidden_size, input_size, activation, input_names, output_names, output_all = False, reverse_input = False): """ Add a simple recurrent layer to the model. Parameters ---------- name: str The name of this layer. W_h: ...
[ "def", "add_simple_rnn", "(", "self", ",", "name", ",", "W_h", ",", "W_x", ",", "b", ",", "hidden_size", ",", "input_size", ",", "activation", ",", "input_names", ",", "output_names", ",", "output_all", "=", "False", ",", "reverse_input", "=", "False", ")"...
42.957746
25.915493
def cli(env, ip_version): """List all global IPs.""" mgr = SoftLayer.NetworkManager(env.client) table = formatting.Table(['id', 'ip', 'assigned', 'target']) version = None if ip_version == 'v4': version = 4 elif ip_version == 'v6': version = 6 ips = mgr.list_global_ips(ve...
[ "def", "cli", "(", "env", ",", "ip_version", ")", ":", "mgr", "=", "SoftLayer", ".", "NetworkManager", "(", "env", ".", "client", ")", "table", "=", "formatting", ".", "Table", "(", "[", "'id'", ",", "'ip'", ",", "'assigned'", ",", "'target'", "]", "...
31.6
18.628571
def get_blockdata(self, x, z): """ Return the decompressed binary data representing a chunk. May raise a RegionFileFormatError(). If decompression of the data succeeds, all available data is returned, even if it is shorter than what is specified in the header (e.g. in c...
[ "def", "get_blockdata", "(", "self", ",", "x", ",", "z", ")", ":", "# read metadata block", "m", "=", "self", ".", "metadata", "[", "x", ",", "z", "]", "if", "m", ".", "status", "==", "STATUS_CHUNK_NOT_CREATED", ":", "raise", "InconceivedChunk", "(", "\"...
53.373134
26.328358
def stop(self): """Stops the external measurement program and returns the measurement result, if the measurement was running.""" consumed_energy = collections.defaultdict(dict) if not self.is_running(): return None # cpu-energy-meter expects SIGINT to stop and report ...
[ "def", "stop", "(", "self", ")", ":", "consumed_energy", "=", "collections", ".", "defaultdict", "(", "dict", ")", "if", "not", "self", ".", "is_running", "(", ")", ":", "return", "None", "# cpu-energy-meter expects SIGINT to stop and report its result", "self", "...
43.2
15.566667
def timeseries_reactive(self): """ Reactive power time series in kvar. Parameters ------- :pandas:`pandas.Series<series>` Series containing reactive power time series in kvar. Returns ---------- :pandas:`pandas.DataFrame<dataframe>` or None ...
[ "def", "timeseries_reactive", "(", "self", ")", ":", "if", "self", ".", "_timeseries_reactive", "is", "None", ":", "# try to get time series for reactive power depending on if they", "# are differentiated by weather cell ID or not", "# raise warning if no time series for generator type...
49.485294
22.897059
def create(entropy_coefficient, value_coefficient, max_grad_norm, discount_factor, gae_lambda=1.0): """ Vel factory function """ return A2CPolicyGradient( entropy_coefficient, value_coefficient, max_grad_norm, discount_factor, gae_lambda )
[ "def", "create", "(", "entropy_coefficient", ",", "value_coefficient", ",", "max_grad_norm", ",", "discount_factor", ",", "gae_lambda", "=", "1.0", ")", ":", "return", "A2CPolicyGradient", "(", "entropy_coefficient", ",", "value_coefficient", ",", "max_grad_norm", ","...
31.444444
20.777778
def isomap(self, num_dims=None, directed=None): '''Isomap embedding. num_dims : dimension of embedded coordinates, defaults to input dimension directed : used for .shortest_path() calculation ''' W = -0.5 * self.shortest_path(directed=directed) ** 2 kpca = KernelPCA(n_components=num_dims, kerne...
[ "def", "isomap", "(", "self", ",", "num_dims", "=", "None", ",", "directed", "=", "None", ")", ":", "W", "=", "-", "0.5", "*", "self", ".", "shortest_path", "(", "directed", "=", "directed", ")", "**", "2", "kpca", "=", "KernelPCA", "(", "n_component...
40.111111
21.666667
def cmd(send, msg, args): """Pesters somebody. Syntax: {command} <nick> <message> """ if not msg or len(msg.split()) < 2: send("Pester needs at least two arguments.") return match = re.match('(%s+) (.*)' % args['config']['core']['nickregex'], msg) if match: message = ma...
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "if", "not", "msg", "or", "len", "(", "msg", ".", "split", "(", ")", ")", "<", "2", ":", "send", "(", "\"Pester needs at least two arguments.\"", ")", "return", "match", "=", "re", ".", ...
28.066667
17.066667
def set_model_internal_data(model, original_data, modified_data, deleted_data): """ Set internal data to model. """ model.__original_data__ = original_data list(map(model._prepare_child, model.__original_data__)) model.__modified_data__ = modified_data list(map(model._prepare_child, model._...
[ "def", "set_model_internal_data", "(", "model", ",", "original_data", ",", "modified_data", ",", "deleted_data", ")", ":", "model", ".", "__original_data__", "=", "original_data", "list", "(", "map", "(", "model", ".", "_prepare_child", ",", "model", ".", "__ori...
29.923077
18.538462
def insert_into_range(self, operations: ops.OP_TREE, start: int, end: int) -> int: """Writes operations inline into an area of the circuit. Args: start: The start of the range (inclusive) to write the ...
[ "def", "insert_into_range", "(", "self", ",", "operations", ":", "ops", ".", "OP_TREE", ",", "start", ":", "int", ",", "end", ":", "int", ")", "->", "int", ":", "if", "not", "0", "<=", "start", "<=", "end", "<=", "len", "(", "self", ")", ":", "ra...
35.711111
19.377778
def add_s(self, s, obj, priority= 0 ): """ Adds a target 'string' for dispatching """ chain = self.strs.get(s, CommandChainDispatcher()) chain.add(obj,priority) self.strs[s] = chain
[ "def", "add_s", "(", "self", ",", "s", ",", "obj", ",", "priority", "=", "0", ")", ":", "chain", "=", "self", ".", "strs", ".", "get", "(", "s", ",", "CommandChainDispatcher", "(", ")", ")", "chain", ".", "add", "(", "obj", ",", "priority", ")", ...
34.833333
13.5
def _remove_vlan_from_all_sp_templates(self, handle, vlan_id, ucsm_ip): """Deletes VLAN config from all SP Templates that have it.""" sp_template_info_list = ( CONF.ml2_cisco_ucsm.ucsms[ucsm_ip].sp_template_list.values()) vlan_name = self.make_vlan_name(vlan_id) virtio_port_...
[ "def", "_remove_vlan_from_all_sp_templates", "(", "self", ",", "handle", ",", "vlan_id", ",", "ucsm_ip", ")", ":", "sp_template_info_list", "=", "(", "CONF", ".", "ml2_cisco_ucsm", ".", "ucsms", "[", "ucsm_ip", "]", ".", "sp_template_list", ".", "values", "(", ...
45.396226
19.679245
def team(self, team, simple=False): """ Get data on a single specified team. :param team: Team to get data for. :param simple: Get only vital data. :return: Team object with data on specified team. """ return Team(self._get('team/%s%s' % (self.team_key(team), '/s...
[ "def", "team", "(", "self", ",", "team", ",", "simple", "=", "False", ")", ":", "return", "Team", "(", "self", ".", "_get", "(", "'team/%s%s'", "%", "(", "self", ".", "team_key", "(", "team", ")", ",", "'/simple'", "if", "simple", "else", "''", ")"...
37.666667
14.111111
def _validate_timeout(cls, value, name): """ Check that a timeout attribute is valid. :param value: The timeout value to validate :param name: The name of the timeout attribute to validate. This is used to specify in error messages. :return: The validated and casted version ...
[ "def", "_validate_timeout", "(", "cls", ",", "value", ",", "name", ")", ":", "if", "value", "is", "_Default", ":", "return", "cls", ".", "DEFAULT_TIMEOUT", "if", "value", "is", "None", "or", "value", "is", "cls", ".", "DEFAULT_TIMEOUT", ":", "return", "v...
42
22.142857
def determine_signs(nodes, edges, cutoff=1e-10): """ Construct the orientation matrix for the pairs on N molecules. >>> determine_signs([0, 1, 2], [(0, 1, 1), (0, 2, -1), (1, 2, -1)]) array([ 1, 1, -1]) """ N = len(nodes) M = np.zeros((N, N), dtype=float) for a, b, w in edges: ...
[ "def", "determine_signs", "(", "nodes", ",", "edges", ",", "cutoff", "=", "1e-10", ")", ":", "N", "=", "len", "(", "nodes", ")", "M", "=", "np", ".", "zeros", "(", "(", "N", ",", "N", ")", ",", "dtype", "=", "float", ")", "for", "a", ",", "b"...
28.357143
18.214286
def __parse_names(): '''Gets and parses file''' filename = get_file('names.tsv.gz') with io.open(filename, 'r', encoding='cp1252') as textfile: next(textfile) for line in textfile: tokens = line.strip().split('\t') chebi_id = int(tokens[1]) if chebi_id ...
[ "def", "__parse_names", "(", ")", ":", "filename", "=", "get_file", "(", "'names.tsv.gz'", ")", "with", "io", ".", "open", "(", "filename", ",", "'r'", ",", "encoding", "=", "'cp1252'", ")", "as", "textfile", ":", "next", "(", "textfile", ")", "for", "...
27.863636
15.590909
def lookup(self, nick): """Looks for the most recent paste by a given nick. Returns the uid or None""" query = dict(nick=nick) order = [('time', pymongo.DESCENDING)] recs = self.db.pastes.find(query).sort(order).limit(1) try: return next(recs)['uid'] e...
[ "def", "lookup", "(", "self", ",", "nick", ")", ":", "query", "=", "dict", "(", "nick", "=", "nick", ")", "order", "=", "[", "(", "'time'", ",", "pymongo", ".", "DESCENDING", ")", "]", "recs", "=", "self", ".", "db", ".", "pastes", ".", "find", ...
34.8
12.1
def serialize(self, pid, record, links_factory=None): """Serialize a single record and persistent identifier. :param pid: Persistent identifier instance. :param record: Record instance. :param links_factory: Factory function for record links. """ return self.schema.tostr...
[ "def", "serialize", "(", "self", ",", "pid", ",", "record", ",", "links_factory", "=", "None", ")", ":", "return", "self", ".", "schema", ".", "tostring", "(", "self", ".", "transform_record", "(", "pid", ",", "record", ",", "links_factory", ")", ")" ]
42.111111
12.777778
def wait(self, timeout=None): """ Waits for the client to stop its loop """ self.__stopped.wait(timeout) return self.__stopped.is_set()
[ "def", "wait", "(", "self", ",", "timeout", "=", "None", ")", ":", "self", ".", "__stopped", ".", "wait", "(", "timeout", ")", "return", "self", ".", "__stopped", ".", "is_set", "(", ")" ]
28.333333
3.666667
def iterparse_elements(element_function, file_or_path, **kwargs): """ Applies element_function to each of the sub-elements in the XML file. The passed in function must take at least one element, and an optional list of **kwarg which are relevant to each of the elements in the list: def elem_func...
[ "def", "iterparse_elements", "(", "element_function", ",", "file_or_path", ",", "*", "*", "kwargs", ")", ":", "if", "not", "hasattr", "(", "element_function", ",", "'__call__'", ")", ":", "return", "file_path", "=", "getattr", "(", "file_or_path", ",", "'name'...
39.153846
23.384615
def deserialize_namespace(data): ''' Deserialize a Namespace object. :param data: bytes or str :return: namespace ''' if isinstance(data, bytes): data = data.decode('utf-8') kvs = data.split() uri_to_prefix = {} for kv in kvs: i = kv.rfind(':') if i == -1: ...
[ "def", "deserialize_namespace", "(", "data", ")", ":", "if", "isinstance", "(", "data", ",", "bytes", ")", ":", "data", "=", "data", ".", "decode", "(", "'utf-8'", ")", "kvs", "=", "data", ".", "split", "(", ")", "uri_to_prefix", "=", "{", "}", "for"...
35.71875
12.78125
def json_repr(self, minimal=False): """Construct a JSON-friendly representation of the object. :param bool minimal: [ignored] :rtype: list """ if self.value: return [self.field, self.operator, self.value] else: return [self.field, self.operator]
[ "def", "json_repr", "(", "self", ",", "minimal", "=", "False", ")", ":", "if", "self", ".", "value", ":", "return", "[", "self", ".", "field", ",", "self", ".", "operator", ",", "self", ".", "value", "]", "else", ":", "return", "[", "self", ".", ...
28.090909
16
def CopyFromDateTimeString(self, time_string): """Copies a SleuthKit timestamp from a date and time string. Args: time_string (str): date and time value formatted as: YYYY-MM-DD hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction...
[ "def", "CopyFromDateTimeString", "(", "self", ",", "time_string", ")", ":", "date_time_values", "=", "self", ".", "_CopyDateTimeFromString", "(", "time_string", ")", "year", "=", "date_time_values", ".", "get", "(", "'year'", ",", "0", ")", "month", "=", "date...
37.060606
18.30303
def rms(self, stride=1): """Calculate the root-mean-square value of this `TimeSeries` once per stride. Parameters ---------- stride : `float` stride (seconds) between RMS calculations Returns ------- rms : `TimeSeries` a new `Time...
[ "def", "rms", "(", "self", ",", "stride", "=", "1", ")", ":", "stridesamp", "=", "int", "(", "stride", "*", "self", ".", "sample_rate", ".", "value", ")", "nsteps", "=", "int", "(", "self", ".", "size", "//", "stridesamp", ")", "# stride through TimeSe...
37.107143
16.214286
def _start_docker_vm(): """Start the Dusty VM if it is not already running.""" is_running = docker_vm_is_running() if not is_running: log_to_client('Starting docker-machine VM {}'.format(constants.VM_MACHINE_NAME)) _apply_nat_dns_host_resolver() _apply_nat_net_less_greedy_subnet() ...
[ "def", "_start_docker_vm", "(", ")", ":", "is_running", "=", "docker_vm_is_running", "(", ")", "if", "not", "is_running", ":", "log_to_client", "(", "'Starting docker-machine VM {}'", ".", "format", "(", "constants", ".", "VM_MACHINE_NAME", ")", ")", "_apply_nat_dns...
50.777778
21.444444
def _read_bim(self): """Reads the BIM file.""" # Reading the BIM file and setting the values bim = pd.read_csv(self.bim_filename, delim_whitespace=True, names=["chrom", "snp", "cm", "pos", "a1", "a2"], dtype=dict(snp=str, a1=str, a2=str)) ...
[ "def", "_read_bim", "(", "self", ")", ":", "# Reading the BIM file and setting the values", "bim", "=", "pd", ".", "read_csv", "(", "self", ".", "bim_filename", ",", "delim_whitespace", "=", "True", ",", "names", "=", "[", "\"chrom\"", ",", "\"snp\"", ",", "\"...
39.307692
19.938462
def make_payload(base, method, params): """Build Betfair JSON-RPC payload. :param str base: Betfair base ("Sports" or "Account") :param str method: Betfair endpoint :param dict params: Request parameters """ payload = { 'jsonrpc': '2.0', 'method': '{base}APING/v1.0/{method}'.for...
[ "def", "make_payload", "(", "base", ",", "method", ",", "params", ")", ":", "payload", "=", "{", "'jsonrpc'", ":", "'2.0'", ",", "'method'", ":", "'{base}APING/v1.0/{method}'", ".", "format", "(", "*", "*", "locals", "(", ")", ")", ",", "'params'", ":", ...
29.5
15.285714
def create_win32tz_map(windows_zones_xml): """Creates a map between Windows and Olson timezone names. Args: windows_zones_xml: The CLDR XML mapping. Yields: (win32_name, olson_name, comment) """ coming_comment = None win32_name = None territory = None parser = genshi.input.XMLParser(StringIO(w...
[ "def", "create_win32tz_map", "(", "windows_zones_xml", ")", ":", "coming_comment", "=", "None", "win32_name", "=", "None", "territory", "=", "None", "parser", "=", "genshi", ".", "input", ".", "XMLParser", "(", "StringIO", "(", "windows_zones_xml", ")", ")", "...
34
20.25
def docstring_to_markdown(docstring): """Convert a Python object's docstring to markdown Parameters ---------- docstring : str The docstring body. Returns ---------- clean_lst : list The markdown formatted docstring as lines (str) in a Python list. """ new_docstrin...
[ "def", "docstring_to_markdown", "(", "docstring", ")", ":", "new_docstring_lst", "=", "[", "]", "for", "idx", ",", "line", "in", "enumerate", "(", "docstring", ".", "split", "(", "'\\n'", ")", ")", ":", "line", "=", "line", ".", "strip", "(", ")", "if"...
33.714286
19.738095
def save_journal(self): """Save journaled commands to file. If there is no active journal, does nothing. If saving the commands to a file fails, a message will be printed to STDERR but the failure will be swallowed so that the extension can be built successfully. """ ...
[ "def", "save_journal", "(", "self", ")", ":", "if", "self", ".", "journal_file", "is", "None", ":", "return", "try", ":", "as_text", "=", "self", ".", "_commands_to_text", "(", ")", "with", "open", "(", "self", ".", "journal_file", ",", "\"w\"", ")", "...
33.210526
16.684211
def gql(query_string, *args, **kwds): """Parse a GQL query string. Args: query_string: Full GQL query, e.g. 'SELECT * FROM Kind WHERE prop = 1'. *args, **kwds: If present, used to call bind(). Returns: An instance of query_class. """ qry = _gql(query_string) if args or kwds: qry = qry._bin...
[ "def", "gql", "(", "query_string", ",", "*", "args", ",", "*", "*", "kwds", ")", ":", "qry", "=", "_gql", "(", "query_string", ")", "if", "args", "or", "kwds", ":", "qry", "=", "qry", ".", "_bind", "(", "args", ",", "kwds", ")", "return", "qry" ]
23.785714
19.571429
def zoom_bbox(self, bbox): """Zoom map to geometry extent. Arguments: bbox -- OGRGeometry polygon to zoom map extent """ try: bbox.transform(self.map.srs) except gdal.GDALException: pass else: self.map.zoom_to_box(mapnik.Box2d(...
[ "def", "zoom_bbox", "(", "self", ",", "bbox", ")", ":", "try", ":", "bbox", ".", "transform", "(", "self", ".", "map", ".", "srs", ")", "except", "gdal", ".", "GDALException", ":", "pass", "else", ":", "self", ".", "map", ".", "zoom_to_box", "(", "...
26.916667
16.25
def socketBinaryStream(self, hostname, port, length): """Create a TCP socket server for binary input. .. warning:: This is not part of the PySpark API. :param string hostname: Hostname of TCP server. :param int port: Port of TCP server. :param length: Me...
[ "def", "socketBinaryStream", "(", "self", ",", "hostname", ",", "port", ",", "length", ")", ":", "deserializer", "=", "TCPDeserializer", "(", "self", ".", "_context", ")", "tcp_binary_stream", "=", "TCPBinaryStream", "(", "length", ")", "tcp_binary_stream", ".",...
42.166667
18
def fields(self): """Returns the list of field names of the model.""" return (self.attributes.values() + self.lists.values() + self.references.values())
[ "def", "fields", "(", "self", ")", ":", "return", "(", "self", ".", "attributes", ".", "values", "(", ")", "+", "self", ".", "lists", ".", "values", "(", ")", "+", "self", ".", "references", ".", "values", "(", ")", ")" ]
45.25
12
def foldl1(f: Callable[[T, T], T], xs: Iterable[T]) -> T: """ Returns the accumulated result of a binary function applied to elements of an iterable. .. math:: foldl1(f, [x_0, x_1, x_2, x_3]) = f(f(f(f(x_0, x_1), x_2), x_3) Examples -------- >>> from delphi.utils.fp import foldl1 ...
[ "def", "foldl1", "(", "f", ":", "Callable", "[", "[", "T", ",", "T", "]", ",", "T", "]", ",", "xs", ":", "Iterable", "[", "T", "]", ")", "->", "T", ":", "return", "reduce", "(", "f", ",", "xs", ")" ]
24.125
23
def make_device_class(spark_cloud, entries, timeout=30): """Returns a dynamic Device class based on what a GET device list from the Spark Cloud returns. spark_cloud parameter should be the caller instance of SparkCloud. entries parameter should be the list of fields the...
[ "def", "make_device_class", "(", "spark_cloud", ",", "entries", ",", "timeout", "=", "30", ")", ":", "attrs", "=", "list", "(", "set", "(", "list", "(", "entries", ")", "+", "[", "'requires_deep_update'", ",", "'functions'", ",", "'variables'", ",", "'api'...
33.954545
23.272727
def disk(self): """ Display percent of disk usage. """ r = self.local_renderer r.run(r.env.disk_usage_command)
[ "def", "disk", "(", "self", ")", ":", "r", "=", "self", ".", "local_renderer", "r", ".", "run", "(", "r", ".", "env", ".", "disk_usage_command", ")" ]
24.166667
6.166667
def publish(self,message,message_type,topic=''): """ Publish the message on the PUB socket with the given topic name. Args: - message: the message to publish - message_type: the type of message being sent - topic: the topic on which to send the messag...
[ "def", "publish", "(", "self", ",", "message", ",", "message_type", ",", "topic", "=", "''", ")", ":", "if", "message_type", "==", "MULTIPART", ":", "raise", "Exception", "(", "\"Unsupported request type\"", ")", "super", "(", "Publisher", ",", "self", ")", ...
38.153846
18.307692
def _f_gene(sid, prefix="G_"): """Clips gene prefix from id.""" sid = sid.replace(SBML_DOT, ".") return _clip(sid, prefix)
[ "def", "_f_gene", "(", "sid", ",", "prefix", "=", "\"G_\"", ")", ":", "sid", "=", "sid", ".", "replace", "(", "SBML_DOT", ",", "\".\"", ")", "return", "_clip", "(", "sid", ",", "prefix", ")" ]
32.75
6.25
def clean_up(self):#, grid): """ de-select grid cols, refresh grid """ if self.selected_col: col_label_value = self.grid.GetColLabelValue(self.selected_col) col_label_value = col_label_value.strip('\nEDIT ALL') self.grid.SetColLabelValue(self.selected_...
[ "def", "clean_up", "(", "self", ")", ":", "#, grid):", "if", "self", ".", "selected_col", ":", "col_label_value", "=", "self", ".", "grid", ".", "GetColLabelValue", "(", "self", ".", "selected_col", ")", "col_label_value", "=", "col_label_value", ".", "strip",...
45.818182
16.727273
def iter_comments(self, number=-1, etag=None): """Iterate over the comments on this pull request. :param int number: (optional), number of comments to return. Default: -1 returns all available comments. :param str etag: (optional), ETag from a previous request to the same ...
[ "def", "iter_comments", "(", "self", ",", "number", "=", "-", "1", ",", "etag", "=", "None", ")", ":", "url", "=", "self", ".", "_build_url", "(", "'comments'", ",", "base_url", "=", "self", ".", "_api", ")", "return", "self", ".", "_iter", "(", "i...
48.818182
20.727273
def _split_path_by_reserved_name(self, path): """Return: object_tree_path, resolver, controlled_path.""" for i, e in enumerate(path): if e in self._resolvers or e == self._get_readme_filename(): return path[:i], path[i], path[i + 1 :] raise d1_onedrive.impl.onedrive_e...
[ "def", "_split_path_by_reserved_name", "(", "self", ",", "path", ")", ":", "for", "i", ",", "e", "in", "enumerate", "(", "path", ")", ":", "if", "e", "in", "self", ".", "_resolvers", "or", "e", "==", "self", ".", "_get_readme_filename", "(", ")", ":", ...
49
14.5
def _remove_files(files): """ Remove all given files. Args: files (list): List of filenames, which will be removed. """ logger.debug("Request for file removal (_remove_files()).") for fn in files: if os.path.exists(fn): logger.debug("Removing '%s'." % fn) ...
[ "def", "_remove_files", "(", "files", ")", ":", "logger", ".", "debug", "(", "\"Request for file removal (_remove_files()).\"", ")", "for", "fn", "in", "files", ":", "if", "os", ".", "path", ".", "exists", "(", "fn", ")", ":", "logger", ".", "debug", "(", ...
24.846154
18.230769
def find_location(self, root, path, prefix=None): """ Finds a requested media file in a location, returning the found absolute path (or ``None`` if no match). """ if prefix: prefix = '%s%s' % (prefix, os.sep) if not path.startswith(prefix): ...
[ "def", "find_location", "(", "self", ",", "root", ",", "path", ",", "prefix", "=", "None", ")", ":", "if", "prefix", ":", "prefix", "=", "'%s%s'", "%", "(", "prefix", ",", "os", ".", "sep", ")", "if", "not", "path", ".", "startswith", "(", "prefix"...
34.769231
9.538462
def next_interval(self, interval): """ Given a value of an interval, this function returns the next interval value """ index = np.where(self.intervals == interval) if index[0][0] + 1 < len(self.intervals): return self.intervals[index[0][0] + 1] else: ...
[ "def", "next_interval", "(", "self", ",", "interval", ")", ":", "index", "=", "np", ".", "where", "(", "self", ".", "intervals", "==", "interval", ")", "if", "index", "[", "0", "]", "[", "0", "]", "+", "1", "<", "len", "(", "self", ".", "interval...
36.4
11.4
def _check_out_arg(func): """Check if ``func`` has an (optional) ``out`` argument. Also verify that the signature of ``func`` has no ``*args`` since they make argument propagation a hassle. Parameters ---------- func : callable Object that should be inspected. Returns ------- ...
[ "def", "_check_out_arg", "(", "func", ")", ":", "if", "sys", ".", "version_info", ".", "major", ">", "2", ":", "spec", "=", "inspect", ".", "getfullargspec", "(", "func", ")", "kw_only", "=", "spec", ".", "kwonlyargs", "else", ":", "spec", "=", "inspec...
27.183673
20.428571
def process_result_value(self, value: Optional[str], dialect: Dialect) -> List[str]: """Convert things on the way from the database to Python.""" retval = self._dbstr_to_strlist(value) return retval
[ "def", "process_result_value", "(", "self", ",", "value", ":", "Optional", "[", "str", "]", ",", "dialect", ":", "Dialect", ")", "->", "List", "[", "str", "]", ":", "retval", "=", "self", ".", "_dbstr_to_strlist", "(", "value", ")", "return", "retval" ]
49.4
11.4
def validate(config): """Validate a configuration file.""" with open(config) as fh: data = utils.yaml_load(fh.read()) jsonschema.validate(data, CONFIG_SCHEMA)
[ "def", "validate", "(", "config", ")", ":", "with", "open", "(", "config", ")", "as", "fh", ":", "data", "=", "utils", ".", "yaml_load", "(", "fh", ".", "read", "(", ")", ")", "jsonschema", ".", "validate", "(", "data", ",", "CONFIG_SCHEMA", ")" ]
35.6
8
def cmd_link(self, args): '''handle link commands''' if len(args) < 1: self.show_link() elif args[0] == "list": self.cmd_link_list() elif args[0] == "add": if len(args) != 2: print("Usage: link add LINK") return ...
[ "def", "cmd_link", "(", "self", ",", "args", ")", ":", "if", "len", "(", "args", ")", "<", "1", ":", "self", ".", "show_link", "(", ")", "elif", "args", "[", "0", "]", "==", "\"list\"", ":", "self", ".", "cmd_link_list", "(", ")", "elif", "args",...
32.2
10.3
def recommend(self, userid, user_items, N=10, filter_already_liked_items=True, filter_items=None, recalculate_user=False): """ Recommends items for a user Calculates the N best recommendations for a user, and returns a list of itemids, score. Parameters ------...
[ "def", "recommend", "(", "self", ",", "userid", ",", "user_items", ",", "N", "=", "10", ",", "filter_already_liked_items", "=", "True", ",", "filter_items", "=", "None", ",", "recalculate_user", "=", "False", ")", ":", "pass" ]
39.366667
23.166667
def df(self): """Return dict with size of Ya.Disk. Keys: 'available', 'used'.""" def parseContent(content): root = ET.fromstring(content) return { 'available': root.find(".//d:quota-available-bytes", namespaces=self.namespaces).text, 'used': root...
[ "def", "df", "(", "self", ")", ":", "def", "parseContent", "(", "content", ")", ":", "root", "=", "ET", ".", "fromstring", "(", "content", ")", "return", "{", "'available'", ":", "root", ".", "find", "(", "\".//d:quota-available-bytes\"", ",", "namespaces"...
33.173913
21.391304
def __get_chunk_dimensions(self): """ Sets the chunking dimmentions depending on the file type. """ #Usually '.0000.' is in self.filename if np.abs(self.header[b'foff']) < 1e-5: logger.info('Detecting high frequency resolution data.') chunk_dim = (1,1,1048576) #1...
[ "def", "__get_chunk_dimensions", "(", "self", ")", ":", "#Usually '.0000.' is in self.filename", "if", "np", ".", "abs", "(", "self", ".", "header", "[", "b'foff'", "]", ")", "<", "1e-5", ":", "logger", ".", "info", "(", "'Detecting high frequency resolution data....
51.583333
22.5
def rgb_to_rgb_percent(rgb_triplet): """ Convert a 3-tuple of integers, suitable for use in an ``rgb()`` color triplet, to a 3-tuple of percentages suitable for use in representing that color. This function makes some trade-offs in terms of the accuracy of the final representation; for some com...
[ "def", "rgb_to_rgb_percent", "(", "rgb_triplet", ")", ":", "# In order to maintain precision for common values,", "# special-case them.", "specials", "=", "{", "255", ":", "u'100%'", ",", "128", ":", "u'50%'", ",", "64", ":", "u'25%'", ",", "32", ":", "u'12.5%'", ...
42.956522
19.652174
def loadmask(self, filename: str) -> np.ndarray: """Load a mask file.""" mask = scipy.io.loadmat(self.find_file(filename, what='mask')) maskkey = [k for k in mask.keys() if not (k.startswith('_') or k.endswith('_'))][0] return mask[maskkey].astype(np.bool)
[ "def", "loadmask", "(", "self", ",", "filename", ":", "str", ")", "->", "np", ".", "ndarray", ":", "mask", "=", "scipy", ".", "io", ".", "loadmat", "(", "self", ".", "find_file", "(", "filename", ",", "what", "=", "'mask'", ")", ")", "maskkey", "="...
56.8
18.6
def contrib_phone(contrib_tag): """ Given a contrib tag, look for an phone tag """ phone = None if raw_parser.phone(contrib_tag): phone = first(raw_parser.phone(contrib_tag)).text return phone
[ "def", "contrib_phone", "(", "contrib_tag", ")", ":", "phone", "=", "None", "if", "raw_parser", ".", "phone", "(", "contrib_tag", ")", ":", "phone", "=", "first", "(", "raw_parser", ".", "phone", "(", "contrib_tag", ")", ")", ".", "text", "return", "phon...
27.125
10.375
def GlorotUniformInitializer(out_dim=0, in_dim=1): """An initializer function for random uniform Glorot-scaled coefficients.""" def init(shape, rng): fan_in, fan_out = shape[in_dim], shape[out_dim] std = np.sqrt(2.0 / (fan_in + fan_out)) a = np.sqrt(3.0) * std return backend.random.uniform(rng, shap...
[ "def", "GlorotUniformInitializer", "(", "out_dim", "=", "0", ",", "in_dim", "=", "1", ")", ":", "def", "init", "(", "shape", ",", "rng", ")", ":", "fan_in", ",", "fan_out", "=", "shape", "[", "in_dim", "]", ",", "shape", "[", "out_dim", "]", "std", ...
43.75
13.5
def k_depth(d, depth, _counter=1): """Iterate keys on specific depth. depth has to be greater equal than 0. Usage reference see :meth:`DictTree.kv_depth()<DictTree.kv_depth>` """ if depth == 0: yield d[_meta]["_rootname"] else: if _counter == dept...
[ "def", "k_depth", "(", "d", ",", "depth", ",", "_counter", "=", "1", ")", ":", "if", "depth", "==", "0", ":", "yield", "d", "[", "_meta", "]", "[", "\"_rootname\"", "]", "else", ":", "if", "_counter", "==", "depth", ":", "for", "key", "in", "Dict...
36
11.5625
def read(filename='cache'): """ parameter: file_path - path to cache file return: data after parsing json file""" cache_path = get_cache_path(filename) if not os.path.exists(cache_path) or os.stat(cache_path).st_size == 0: return None with open(cache_path, 'r') as file: return json.load(file)
[ "def", "read", "(", "filename", "=", "'cache'", ")", ":", "cache_path", "=", "get_cache_path", "(", "filename", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "cache_path", ")", "or", "os", ".", "stat", "(", "cache_path", ")", ".", "st_size",...
32.777778
10.555556
def _get_path_pattern_tornado4(self): """Return the path pattern used when routing a request. (Tornado<4.5) :rtype: str """ for host, handlers in self.application.handlers: if host.match(self.request.host): for handler in handlers: if hand...
[ "def", "_get_path_pattern_tornado4", "(", "self", ")", ":", "for", "host", ",", "handlers", "in", "self", ".", "application", ".", "handlers", ":", "if", "host", ".", "match", "(", "self", ".", "request", ".", "host", ")", ":", "for", "handler", "in", ...
39.9
11.9
def allowance (self, filename): """Preconditions: - our agent applies to this entry - filename is URL decoded Check if given filename is allowed to acces this entry. @return: True if allowed, else False @rtype: bool """ for line in self.rulelines: ...
[ "def", "allowance", "(", "self", ",", "filename", ")", ":", "for", "line", "in", "self", ".", "rulelines", ":", "log", ".", "debug", "(", "LOG_CHECK", ",", "\"%s %s %s\"", ",", "filename", ",", "str", "(", "line", ")", ",", "line", ".", "allowance", ...
38.294118
17.941176
def import_trade(self, trade): """ trade是一个可迭代的list/generator """ for item in trade: self.make_deal(item.code, item.datetime, item.amount, item.towards, item.price.item.order_model, item.amount_model)
[ "def", "import_trade", "(", "self", ",", "trade", ")", ":", "for", "item", "in", "trade", ":", "self", ".", "make_deal", "(", "item", ".", "code", ",", "item", ".", "datetime", ",", "item", ".", "amount", ",", "item", ".", "towards", ",", "item", "...
37.857143
14.714286
def __make_response(self, data, default_renderer=None): """ Creates a Flask response object from the specified data. The appropriated encoder is taken based on the request header Accept. If there is not data to be serialized the response status code is 204. :param data: The Pyth...
[ "def", "__make_response", "(", "self", ",", "data", ",", "default_renderer", "=", "None", ")", ":", "status", "=", "headers", "=", "None", "if", "isinstance", "(", "data", ",", "tuple", ")", ":", "data", ",", "status", ",", "headers", "=", "unpack", "(...
34.416667
21.416667
def fetch_twitter_lists_for_user_ids_generator(twitter_app_key, twitter_app_secret, user_id_list): """ Collects at most 500 Twitter lists for each user from an input list of Twitter user ids. Inputs: - twitter_app...
[ "def", "fetch_twitter_lists_for_user_ids_generator", "(", "twitter_app_key", ",", "twitter_app_secret", ",", "user_id_list", ")", ":", "####################################################################################################################", "# Log into my application.", "######...
57.770833
27.6875
def recCopyElement(oldelement): """Generates a copy of an xml element and recursively of all child elements. :param oldelement: an instance of lxml.etree._Element :returns: a copy of the "oldelement" .. warning:: doesn't copy ``.text`` or ``.tail`` of xml elements """ newelement =...
[ "def", "recCopyElement", "(", "oldelement", ")", ":", "newelement", "=", "ETREE", ".", "Element", "(", "oldelement", ".", "tag", ",", "oldelement", ".", "attrib", ")", "if", "len", "(", "oldelement", ".", "getchildren", "(", ")", ")", ">", "0", ":", "f...
33.25
17.9375
def do_stop_alerts(self, _): """ Stops the alerter thread """ self._stop_thread = True if self._alerter_thread.is_alive(): self._alerter_thread.join() else: print("The alert thread is already stopped")
[ "def", "do_stop_alerts", "(", "self", ",", "_", ")", ":", "self", ".", "_stop_thread", "=", "True", "if", "self", ".", "_alerter_thread", ".", "is_alive", "(", ")", ":", "self", ".", "_alerter_thread", ".", "join", "(", ")", "else", ":", "print", "(", ...
35.857143
9.571429
def flick_element(self, on_element, xoffset, yoffset, speed): """ Flick starting at on_element, and moving by the xoffset and yoffset with specified speed. :Args: - on_element: Flick will start at center of element. - xoffset: X offset to flick to. - yoffset: ...
[ "def", "flick_element", "(", "self", ",", "on_element", ",", "xoffset", ",", "yoffset", ",", "speed", ")", ":", "self", ".", "_actions", ".", "append", "(", "lambda", ":", "self", ".", "_driver", ".", "execute", "(", "Command", ".", "FLICK", ",", "{", ...
36.277778
11.944444
def from_file(cls, image_file): """ Return a new |Image| object loaded from *image_file*, which can be either a path (string) or a file-like object. """ if is_string(image_file): # treat image_file as a path with open(image_file, 'rb') as f: ...
[ "def", "from_file", "(", "cls", ",", "image_file", ")", ":", "if", "is_string", "(", "image_file", ")", ":", "# treat image_file as a path", "with", "open", "(", "image_file", ",", "'rb'", ")", "as", "f", ":", "blob", "=", "f", ".", "read", "(", ")", "...
36.631579
11.789474
def init_remote(self): ''' Initialize/attach to a remote using pygit2. Return a boolean which will let the calling function know whether or not a new repo was initialized by this function. ''' # https://github.com/libgit2/pygit2/issues/339 # https://github.com/lib...
[ "def", "init_remote", "(", "self", ")", ":", "# https://github.com/libgit2/pygit2/issues/339", "# https://github.com/libgit2/libgit2/issues/2122", "home", "=", "os", ".", "path", ".", "expanduser", "(", "'~'", ")", "pygit2", ".", "settings", ".", "search_path", "[", "...
38.703704
21.37037
def init(): """Initialise and configure the app, database, scheduler, etc. This should be called once at application startup or at tests startup (and not e.g. called once for each test case). """ global _users, _names _configure_app(app) _users, _names = _init_login_manager(app) _confi...
[ "def", "init", "(", ")", ":", "global", "_users", ",", "_names", "_configure_app", "(", "app", ")", "_users", ",", "_names", "=", "_init_login_manager", "(", "app", ")", "_configure_logger", "(", ")", "init_scheduler", "(", "app", ".", "config", ".", "get"...
33.692308
18.538462
def clear_matplotlib_ticks(self, axis="both"): """Clears the default matplotlib ticks.""" ax = self.get_axes() plotting.clear_matplotlib_ticks(ax=ax, axis=axis)
[ "def", "clear_matplotlib_ticks", "(", "self", ",", "axis", "=", "\"both\"", ")", ":", "ax", "=", "self", ".", "get_axes", "(", ")", "plotting", ".", "clear_matplotlib_ticks", "(", "ax", "=", "ax", ",", "axis", "=", "axis", ")" ]
45.25
8.75
def graph_loads(graph_json): ''' Load graph ''' layers = [] for layer in graph_json['layers']: layer_info = Layer(layer['graph_type'], layer['input'], layer['output'], layer['size'], layer['hash_id']) layer_info.is_delete = layer['is_delete'] _logger.debug('append layer {}'.f...
[ "def", "graph_loads", "(", "graph_json", ")", ":", "layers", "=", "[", "]", "for", "layer", "in", "graph_json", "[", "'layers'", "]", ":", "layer_info", "=", "Layer", "(", "layer", "[", "'graph_type'", "]", ",", "layer", "[", "'input'", "]", ",", "laye...
38.642857
23.928571
def google_analytics(parser, token): """ Google Analytics tracking template tag. Renders Javascript code to track page visits. You must supply your website property ID (as a string) in the ``GOOGLE_ANALYTICS_PROPERTY_ID`` setting. """ bits = token.split_contents() if len(bits) > 1: ...
[ "def", "google_analytics", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "bits", ")", ">", "1", ":", "raise", "TemplateSyntaxError", "(", "\"'%s' takes no arguments\"", "%", "bits", "[", "0"...
34.083333
12.583333
def assign_to_a_queue(self, action): """Take an action and put it to a worker actions queue :param action: action to put :type action: alignak.action.Action :return: None """ (worker_id, queue) = self._get_queue_for_the_action(action) if not worker_id: ...
[ "def", "assign_to_a_queue", "(", "self", ",", "action", ")", ":", "(", "worker_id", ",", "queue", ")", "=", "self", ".", "_get_queue_for_the_action", "(", "action", ")", "if", "not", "worker_id", ":", "return", "# Tag the action as \"in the worker i\"", "action", ...
32.210526
14.578947
def path_safe_spec(self): """ :API: public """ return ('{safe_spec_path}.{target_name}' .format(safe_spec_path=self._spec_path.replace(os.sep, '.'), target_name=self._target_name.replace(os.sep, '.')))
[ "def", "path_safe_spec", "(", "self", ")", ":", "return", "(", "'{safe_spec_path}.{target_name}'", ".", "format", "(", "safe_spec_path", "=", "self", ".", "_spec_path", ".", "replace", "(", "os", ".", "sep", ",", "'.'", ")", ",", "target_name", "=", "self", ...
34.714286
15.285714
def total_charges(self): """ Represents the 'goods' acquired in the invoice. """ selected_charges = Charge.objects \ .filter(invoice=self) \ .charges() \ .exclude(product_code=CARRIED_FORWARD) return total_amount(selected_charges)
[ "def", "total_charges", "(", "self", ")", ":", "selected_charges", "=", "Charge", ".", "objects", ".", "filter", "(", "invoice", "=", "self", ")", ".", "charges", "(", ")", ".", "exclude", "(", "product_code", "=", "CARRIED_FORWARD", ")", "return", "total_...
33.111111
7.777778
def currentValue(self): """ Returns the current value for the widget. If this widget is checkable then the bitor value for all checked items is returned, otherwise, the selected value is returned. :return <int> """ enum = self.enum() ...
[ "def", "currentValue", "(", "self", ")", ":", "enum", "=", "self", ".", "enum", "(", ")", "if", "(", "self", ".", "isCheckable", "(", ")", ")", ":", "value", "=", "0", "for", "i", "in", "self", ".", "checkedIndexes", "(", ")", ":", "value", "|=",...
34.473684
17.526316
def portable_hash(x): """ This function returns consistent hash code for builtin types, especially for None and tuple with None. The algorithm is similar to that one used by CPython 2.7 >>> portable_hash(None) 0 >>> portable_hash((None, 1)) & 0xffffffff 219750521 """ if sys.ve...
[ "def", "portable_hash", "(", "x", ")", ":", "if", "sys", ".", "version_info", ">=", "(", "3", ",", "2", ",", "3", ")", "and", "'PYTHONHASHSEED'", "not", "in", "os", ".", "environ", ":", "raise", "Exception", "(", "\"Randomness of hash of string should be dis...
25.62069
22.448276
def get_shared(func): """ return shared. """ shared = [] if not hasattr(func, '__cls__'): return shared if not hasattr(func.__cls__, '__shared_arguments__'): return shared if hasattr(func, '__no_share__'): if func.__no_share__ is True: return shared ...
[ "def", "get_shared", "(", "func", ")", ":", "shared", "=", "[", "]", "if", "not", "hasattr", "(", "func", ",", "'__cls__'", ")", ":", "return", "shared", "if", "not", "hasattr", "(", "func", ".", "__cls__", ",", "'__shared_arguments__'", ")", ":", "ret...
29
15
def _getmember(self, name, tarinfo=None, normalize=False): """Find an archive member by name from bottom to top. If tarinfo is given, it is used as the starting point. """ # Ensure that all members have been loaded. members = self.getmembers() # Limit the member searc...
[ "def", "_getmember", "(", "self", ",", "name", ",", "tarinfo", "=", "None", ",", "normalize", "=", "False", ")", ":", "# Ensure that all members have been loaded.", "members", "=", "self", ".", "getmembers", "(", ")", "# Limit the member search list up to tarinfo.", ...
33.045455
15.863636
def kubesync(): """Communicate with kubernetes deployment via kubectl and save image names/IDs to local files""" ecode = 0 try: images = anchore_utils.get_images_from_kubectl() if images: anchore_print("Writing image IDs to ./anchore_imageIds.kube") with open("ancho...
[ "def", "kubesync", "(", ")", ":", "ecode", "=", "0", "try", ":", "images", "=", "anchore_utils", ".", "get_images_from_kubectl", "(", ")", "if", "images", ":", "anchore_print", "(", "\"Writing image IDs to ./anchore_imageIds.kube\"", ")", "with", "open", "(", "\...
36.181818
21.272727
def get_straat_by_id(self, id): ''' Retrieve a `straat` by the Id. :param integer id: The id of the `straat`. :rtype: :class:`Straat` ''' def creator(): res = crab_gateway_request( self.client, 'GetStraatnaamWithStatusByStraatnaamId', id ...
[ "def", "get_straat_by_id", "(", "self", ",", "id", ")", ":", "def", "creator", "(", ")", ":", "res", "=", "crab_gateway_request", "(", "self", ".", "client", ",", "'GetStraatnaamWithStatusByStraatnaamId'", ",", "id", ")", "if", "res", "==", "None", ":", "r...
33.135135
15.567568
def get_path_for_termid(self,termid): """ This function returns the path (in terms of phrase types) from one term the root @type termid: string @param termid: one term id @rtype: list @return: the path, list of phrase types """ terminal_id = self.term...
[ "def", "get_path_for_termid", "(", "self", ",", "termid", ")", ":", "terminal_id", "=", "self", ".", "terminal_for_term", ".", "get", "(", "termid", ")", "paths", "=", "self", ".", "paths_for_terminal", "[", "terminal_id", "]", "labels", "=", "[", "self", ...
40.083333
14.916667
def set_mypy_path(mypy_path): """Prepend to MYPYPATH.""" original = os.environ.get(mypy_path_env_var) if original is None: new_mypy_path = mypy_path elif not original.startswith(mypy_path): new_mypy_path = mypy_path + os.pathsep + original else: new_mypy_path = None if ne...
[ "def", "set_mypy_path", "(", "mypy_path", ")", ":", "original", "=", "os", ".", "environ", ".", "get", "(", "mypy_path_env_var", ")", "if", "original", "is", "None", ":", "new_mypy_path", "=", "mypy_path", "elif", "not", "original", ".", "startswith", "(", ...
37.166667
12
def fail_on_template_errors(f, *args, **kwargs): """ Decorator that causes templates to fail on template errors. """ decorators = [ _fail_template_string_if_invalid, _always_strict_resolve, _disallow_catching_UnicodeDecodeError, ] if django.VERSION < (1, 8): decor...
[ "def", "fail_on_template_errors", "(", "f", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "decorators", "=", "[", "_fail_template_string_if_invalid", ",", "_always_strict_resolve", ",", "_disallow_catching_UnicodeDecodeError", ",", "]", "if", "django", ".", ...
31.846154
14.615385
def is_definition(cursor): """Test if a cursor refers to a definition This occurs when the cursor has a definition, and shares the location of that definiton """ defn = cursor.get_definition() return (defn is not None) and (cursor.location == defn.location)
[ "def", "is_definition", "(", "cursor", ")", ":", "defn", "=", "cursor", ".", "get_definition", "(", ")", "return", "(", "defn", "is", "not", "None", ")", "and", "(", "cursor", ".", "location", "==", "defn", ".", "location", ")" ]
38.857143
19.857143