text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def sli_run(parameters=object(), fname='microcircuit.sli', verbosity='M_ERROR'): ''' Takes parameter-class and name of main sli-script as input, initiating the simulation. kwargs: :: parameters : object, parameter class instance fname : str, path to sli c...
[ "def", "sli_run", "(", "parameters", "=", "object", "(", ")", ",", "fname", "=", "'microcircuit.sli'", ",", "verbosity", "=", "'M_ERROR'", ")", ":", "# Load parameters from params file, and pass them to nest", "# Python -> SLI", "send_nest_params_to_sli", "(", "vars", "...
29.5
19.863636
def _mimetext(self, text, subtype='plain'): """Creates a MIMEText object with the given subtype (default: 'plain') If the text is unicode, the utf-8 charset is used. """ charset = self.charset or 'utf-8' return MIMEText(text, _subtype=subtype, _charset=charset)
[ "def", "_mimetext", "(", "self", ",", "text", ",", "subtype", "=", "'plain'", ")", ":", "charset", "=", "self", ".", "charset", "or", "'utf-8'", "return", "MIMEText", "(", "text", ",", "_subtype", "=", "subtype", ",", "_charset", "=", "charset", ")" ]
49.333333
7.833333
def refuse_transfer(transfer, comment=None): '''Refuse an incoming a transfer request''' TransferResponsePermission(transfer).test() transfer.responded = datetime.now() transfer.responder = current_user._get_current_object() transfer.status = 'refused' transfer.response_comment = comment tr...
[ "def", "refuse_transfer", "(", "transfer", ",", "comment", "=", "None", ")", ":", "TransferResponsePermission", "(", "transfer", ")", ".", "test", "(", ")", "transfer", ".", "responded", "=", "datetime", ".", "now", "(", ")", "transfer", ".", "responder", ...
31.272727
15.454545
def _refresh_state(self): """ Refresh the job info. """ # DataFlow's DataflowPipelineResult does not refresh state, so we have to do it ourselves # as a workaround. # TODO(Change this to use runner_results.state once it refreshes itself) dataflow_internal_job = ( self._runner_results._runne...
[ "def", "_refresh_state", "(", "self", ")", ":", "# DataFlow's DataflowPipelineResult does not refresh state, so we have to do it ourselves", "# as a workaround.", "# TODO(Change this to use runner_results.state once it refreshes itself)", "dataflow_internal_job", "=", "(", "self", ".", "...
62.625
34.3125
def _check_fill_title_column(self, column_index): ''' Same as _check_fill_title_row but for columns. ''' # Determine if the whole column is titles table_column = TableTranspose(self.table)[column_index] prior_column = TableTranspose(self.table)[column_index-1] if column_i...
[ "def", "_check_fill_title_column", "(", "self", ",", "column_index", ")", ":", "# Determine if the whole column is titles", "table_column", "=", "TableTranspose", "(", "self", ".", "table", ")", "[", "column_index", "]", "prior_column", "=", "TableTranspose", "(", "se...
51
23.666667
def get_compressed_filename(self, filename): """If the given filename should be compressed, returns the compressed filename. A file can be compressed if: - It is a whitelisted extension - The compressed file does not exist - The compressed file exists by is older than t...
[ "def", "get_compressed_filename", "(", "self", ",", "filename", ")", ":", "if", "not", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "1", "]", "[", "1", ":", "]", "in", "self", ".", "suffixes_to_compress", ":", "return", "False", "file...
33.064516
18.451613
def validiate_webhook_signature(self, webhook, signature): """Validates a webhook signature from a webhook body + client secret Parameters webhook (string) The request body of the webhook. signature (string) The webhook signature specified in X-Ub...
[ "def", "validiate_webhook_signature", "(", "self", ",", "webhook", ",", "signature", ")", ":", "digester", "=", "hmac", ".", "new", "(", "self", ".", "session", ".", "oauth2credential", ".", "client_secret", ",", "webhook", ",", "hashlib", ".", "sha256", ")"...
40.928571
14.571429
def resolve(input, representation, resolvers=None, get3d=False, **kwargs): """Resolve input to the specified output representation. :param string input: Chemical identifier to resolve :param string representation: Desired output representation :param list(string) resolvers: (Optional) Ordered list of r...
[ "def", "resolve", "(", "input", ",", "representation", ",", "resolvers", "=", "None", ",", "get3d", "=", "False", ",", "*", "*", "kwargs", ")", ":", "# Take first result from XML query", "results", "=", "query", "(", "input", ",", "representation", ",", "res...
48.875
19.5625
def load_joke(service_num=1): """Pulls the joke from the service based on the argument. It is expected that all services used will return a string when successful or None otherwise. """ result = { 1 : ronswanson.get_joke(), 2 : chucknorris.get_joke(), 3 : catfacts.get_joke(), ...
[ "def", "load_joke", "(", "service_num", "=", "1", ")", ":", "result", "=", "{", "1", ":", "ronswanson", ".", "get_joke", "(", ")", ",", "2", ":", "chucknorris", ".", "get_joke", "(", ")", ",", "3", ":", "catfacts", ".", "get_joke", "(", ")", ",", ...
27.071429
15.214286
def masked_middle_mfcc(self): """ Return the MFCC speech frames in the MIDDLE portion of the wave. :rtype: :class:`numpy.ndarray` (2D) """ begin, end = self._masked_middle_begin_end() return (self.masked_mfcc)[:, begin:end]
[ "def", "masked_middle_mfcc", "(", "self", ")", ":", "begin", ",", "end", "=", "self", ".", "_masked_middle_begin_end", "(", ")", "return", "(", "self", ".", "masked_mfcc", ")", "[", ":", ",", "begin", ":", "end", "]" ]
30.222222
8.666667
def _initialize(cls): """ Internal method to initialize the class by creating all the operator metadata to be used afterwards. """ op_symbols = """ + add radd pos - sub rsub neg * mul rmul / truediv rtruediv // floordiv rfloordiv % mod rmod ** pow rpow ...
[ "def", "_initialize", "(", "cls", ")", ":", "op_symbols", "=", "\"\"\"\n + add radd pos\n - sub rsub neg\n * mul rmul\n / truediv rtruediv\n // floordiv rfloordiv\n % mod rmod\n ** pow rpow\n >> rshift rrshift\n << lshift rlshift\n ~ invert\n & ...
21.875
17.1875
def _get_token_from_headers(self, request, refresh_token): """ Extract the token if present inside the headers of a request. """ header = request.headers.get(self.config.authorization_header(), None) if header is None: return None else: header_pr...
[ "def", "_get_token_from_headers", "(", "self", ",", "request", ",", "refresh_token", ")", ":", "header", "=", "request", ".", "headers", ".", "get", "(", "self", ".", "config", ".", "authorization_header", "(", ")", ",", "None", ")", "if", "header", "is", ...
31.464286
21.75
def attrib(self): """ An dict of XML element attributes for this MFD. """ return dict([ ('aValue', str(self.a_val)), ('bValue', str(self.b_val)), ('minMag', str(self.min_mag)), ('maxMag', str(self.max_mag)), ])
[ "def", "attrib", "(", "self", ")", ":", "return", "dict", "(", "[", "(", "'aValue'", ",", "str", "(", "self", ".", "a_val", ")", ")", ",", "(", "'bValue'", ",", "str", "(", "self", ".", "b_val", ")", ")", ",", "(", "'minMag'", ",", "str", "(", ...
28.9
9.1
def get_token(self): """sets client token from Cerberus""" auth_resp = self.get_auth() if auth_resp['status'] == 'mfa_req': token_resp = self.get_mfa(auth_resp) else: token_resp = auth_resp token = token_resp['data']['client_token']['client_token'] ...
[ "def", "get_token", "(", "self", ")", ":", "auth_resp", "=", "self", ".", "get_auth", "(", ")", "if", "auth_resp", "[", "'status'", "]", "==", "'mfa_req'", ":", "token_resp", "=", "self", ".", "get_mfa", "(", "auth_resp", ")", "else", ":", "token_resp", ...
29.545455
17.818182
def add_join_conditions(self, conditions: Dict[str, Any]) -> None: """Adds an extra condition to an existing JOIN. This allows you to for example do: INNER JOIN othertable ON (mytable.id = othertable.other_id AND [extra conditions]) This does not work if nothing else in your query...
[ "def", "add_join_conditions", "(", "self", ",", "conditions", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "None", ":", "alias", "=", "self", ".", "get_initial_alias", "(", ")", "opts", "=", "self", ".", "get_meta", "(", ")", "for", "name", "...
39.027778
21.472222
def domain(random=random, *args, **kwargs): """ Return a domain >>> mock_random.seed(0) >>> domain(random=mock_random) 'onion.net' >>> domain(random=mock_random) 'bag-of-heroic-chimps.sexy' """ words = random.choice([ noun(random=random), thing(random=random), ...
[ "def", "domain", "(", "random", "=", "random", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "words", "=", "random", ".", "choice", "(", "[", "noun", "(", "random", "=", "random", ")", ",", "thing", "(", "random", "=", "random", ")", ",", ...
23.823529
14.764706
def save(self, request, resource=None, **kwargs): """Create a resource.""" resources = resource if isinstance(resource, list) else [resource] for obj in resources: obj.save() return resource
[ "def", "save", "(", "self", ",", "request", ",", "resource", "=", "None", ",", "*", "*", "kwargs", ")", ":", "resources", "=", "resource", "if", "isinstance", "(", "resource", ",", "list", ")", "else", "[", "resource", "]", "for", "obj", "in", "resou...
38.166667
14.833333
def type(self): """The type of the functional.""" if self.xc in self.defined_aliases: return self.defined_aliases[self.xc].type xc = (self.x, self.c) if xc in self.defined_aliases: return self.defined_aliases[xc].type # If self is not in defined_aliases, use LibxcFunc family ...
[ "def", "type", "(", "self", ")", ":", "if", "self", ".", "xc", "in", "self", ".", "defined_aliases", ":", "return", "self", ".", "defined_aliases", "[", "self", ".", "xc", "]", ".", "type", "xc", "=", "(", "self", ".", "x", ",", "self", ".", "c",...
46.444444
23.222222
def _parse_doc_ref(self): """Parse the document handle. Sets the ``_series``, ``_serial``, and ``_handle`` attributes. """ command = LatexCommand( 'setDocRef', {'name': 'handle', 'required': True, 'bracket': '{'}) try: parsed = next(command.pa...
[ "def", "_parse_doc_ref", "(", "self", ")", ":", "command", "=", "LatexCommand", "(", "'setDocRef'", ",", "{", "'name'", ":", "'handle'", ",", "'required'", ":", "True", ",", "'bracket'", ":", "'{'", "}", ")", "try", ":", "parsed", "=", "next", "(", "co...
35
17.8
def file_exists_on_unit(self, sentry_unit, file_name): """Check if a file exists on a unit.""" try: sentry_unit.file_stat(file_name) return True except IOError: return False except Exception as e: msg = 'Error checking file {}: {}'.format(f...
[ "def", "file_exists_on_unit", "(", "self", ",", "sentry_unit", ",", "file_name", ")", ":", "try", ":", "sentry_unit", ".", "file_stat", "(", "file_name", ")", "return", "True", "except", "IOError", ":", "return", "False", "except", "Exception", "as", "e", ":...
37.7
14.6
def set_proxy_win(server, port, types=None, bypass_hosts=None): ''' Sets the http proxy settings, only works with Windows. server The proxy server to use password The password to use if required by the server types The types of proxy connections should be setup with this s...
[ "def", "set_proxy_win", "(", "server", ",", "port", ",", "types", "=", "None", ",", "bypass_hosts", "=", "None", ")", ":", "if", "__grains__", "[", "'os'", "]", "==", "'Windows'", ":", "return", "_set_proxy_windows", "(", "server", "=", "server", ",", "p...
26.21875
25.40625
def _validate_states(states, topology): '''Validate states to avoid ignoring states during initialization''' states = states or [] if isinstance(states, dict): for x in states: assert x in topology.node else: assert len(states) <= len(topology) return states
[ "def", "_validate_states", "(", "states", ",", "topology", ")", ":", "states", "=", "states", "or", "[", "]", "if", "isinstance", "(", "states", ",", "dict", ")", ":", "for", "x", "in", "states", ":", "assert", "x", "in", "topology", ".", "node", "el...
33.111111
14.666667
def convert_flatten(params, w_name, scope_name, inputs, layers, weights, names): """ Convert reshape(view). Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary ...
[ "def", "convert_flatten", "(", "params", ",", "w_name", ",", "scope_name", ",", "inputs", ",", "layers", ",", "weights", ",", "names", ")", ":", "print", "(", "'Converting flatten ...'", ")", "if", "names", "==", "'short'", ":", "tf_name", "=", "'R'", "+",...
30.291667
14.708333
def get_mapped_filenames(self, memoryMap = None): """ Retrieves the filenames for memory mapped files in the debugee. @type memoryMap: list( L{win32.MemoryBasicInformation} ) @param memoryMap: (Optional) Memory map returned by L{get_memory_map}. If not given, the current me...
[ "def", "get_mapped_filenames", "(", "self", ",", "memoryMap", "=", "None", ")", ":", "hProcess", "=", "self", ".", "get_handle", "(", "win32", ".", "PROCESS_VM_READ", "|", "win32", ".", "PROCESS_QUERY_INFORMATION", ")", "if", "not", "memoryMap", ":", "memoryMa...
44.864865
19.027027
def routes_register(app, handler, *paths, methods=None, router=None, name=None): """Register routes.""" if router is None: router = app.router handler = to_coroutine(handler) resources = [] for path in paths: # Register any exception to app if isinstance(path, type) and i...
[ "def", "routes_register", "(", "app", ",", "handler", ",", "*", "paths", ",", "methods", "=", "None", ",", "router", "=", "None", ",", "name", "=", "None", ")", ":", "if", "router", "is", "None", ":", "router", "=", "app", ".", "router", "handler", ...
26.578947
19.842105
def list_trials(experiment_path, sort, output, filter_op, columns, result_columns): """Lists trials in the directory subtree starting at the given path.""" if columns: columns = columns.split(",") if result_columns: result_columns = result_columns.split(",") commands.list...
[ "def", "list_trials", "(", "experiment_path", ",", "sort", ",", "output", ",", "filter_op", ",", "columns", ",", "result_columns", ")", ":", "if", "columns", ":", "columns", "=", "columns", ".", "split", "(", "\",\"", ")", "if", "result_columns", ":", "res...
45.666667
14
def element_scroll_behavior(self, value): """ Sets the options Element Scroll Behavior :Args: - value: 0 - Top, 1 - Bottom """ if value not in [ElementScrollBehavior.TOP, ElementScrollBehavior.BOTTOM]: raise ValueError('Element Scroll Behavior out of range....
[ "def", "element_scroll_behavior", "(", "self", ",", "value", ")", ":", "if", "value", "not", "in", "[", "ElementScrollBehavior", ".", "TOP", ",", "ElementScrollBehavior", ".", "BOTTOM", "]", ":", "raise", "ValueError", "(", "'Element Scroll Behavior out of range.'",...
33.818182
18.909091
def csvd(A): """SVD decomposition using numpy.linalg.svd :param A: a M by N matrix :return: * U, a M by M matrix * S the N eigen values * V a N by N matrix See :func:`numpy.linalg.svd` for a detailed documentation. Should return the same as in [Marple]_ , CSVD routine. ...
[ "def", "csvd", "(", "A", ")", ":", "U", ",", "S", ",", "V", "=", "numpy", ".", "linalg", ".", "svd", "(", "A", ")", "return", "U", ",", "S", ",", "V" ]
19.590909
22.863636
def obfn_dfd(self): r"""Compute data fidelity term :math:`(1/2) \| \sum_m \mathbf{d}_m * \mathbf{x}_m - \mathbf{s} \|_2^2`. """ Ef = self.eval_Rf(self.Xf) return sl.rfl2norm2(Ef, self.S.shape, axis=self.cri.axisN) / 2.0
[ "def", "obfn_dfd", "(", "self", ")", ":", "Ef", "=", "self", ".", "eval_Rf", "(", "self", ".", "Xf", ")", "return", "sl", ".", "rfl2norm2", "(", "Ef", ",", "self", ".", "S", ".", "shape", ",", "axis", "=", "self", ".", "cri", ".", "axisN", ")",...
36.285714
16.571429
def cli(env, network, quantity, vlan_id, ipv6, test): """Add a new subnet to your account. Valid quantities vary by type. \b Type - Valid Quantities (IPv4) public - 4, 8, 16, 32 private - 4, 8, 16, 32, 64 \b Type - Valid Quantities (IPv6) public - 64 """ mgr = SoftLayer.Ne...
[ "def", "cli", "(", "env", ",", "network", ",", "quantity", ",", "vlan_id", ",", "ipv6", ",", "test", ")", ":", "mgr", "=", "SoftLayer", ".", "NetworkManager", "(", "env", ".", "client", ")", "if", "not", "(", "test", "or", "env", ".", "skip_confirmat...
30.488372
23.790698
def _date_to_json(value): """Coerce 'value' to an JSON-compatible representation.""" if isinstance(value, datetime.date): value = value.isoformat() return value
[ "def", "_date_to_json", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "datetime", ".", "date", ")", ":", "value", "=", "value", ".", "isoformat", "(", ")", "return", "value" ]
35.2
9.2
def cmd_usercheck(username, no_cache, verbose, wopen): """Check if the given username exists on various social networks and other popular sites. \b $ habu.usercheck portantier { "aboutme": "https://about.me/portantier", "disqus": "https://disqus.com/by/portantier/", "github": "h...
[ "def", "cmd_usercheck", "(", "username", ",", "no_cache", ",", "verbose", ",", "wopen", ")", ":", "habucfg", "=", "loadcfg", "(", ")", "if", "verbose", ":", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "INFO", ",", "format", "=", "...
35.489362
21.617021
def reserved(self, value): """Reserved setter.""" self.bytearray[self._get_slicers(2)] = bytearray(c_uint16(value or 0))
[ "def", "reserved", "(", "self", ",", "value", ")", ":", "self", ".", "bytearray", "[", "self", ".", "_get_slicers", "(", "2", ")", "]", "=", "bytearray", "(", "c_uint16", "(", "value", "or", "0", ")", ")" ]
44.666667
17.333333
def flatten_dict_vals(dict_): """ Flattens only values in a heirarchical dictionary, keys are nested. """ if isinstance(dict_, dict): return dict([ ((key, augkey), augval) for key, val in dict_.items() for augkey, augval in flatten_dict_vals(val).items() ...
[ "def", "flatten_dict_vals", "(", "dict_", ")", ":", "if", "isinstance", "(", "dict_", ",", "dict", ")", ":", "return", "dict", "(", "[", "(", "(", "key", ",", "augkey", ")", ",", "augval", ")", "for", "key", ",", "val", "in", "dict_", ".", "items",...
29.416667
14.416667
def on_message(self, message): """Listens for a "websocket client ready" message. Once that message is received an asynchronous job is stated that yields messages to the client. These messages make up salt's "real time" event stream. """ log.debug('Got websocket m...
[ "def", "on_message", "(", "self", ",", "message", ")", ":", "log", ".", "debug", "(", "'Got websocket message %s'", ",", "message", ")", "if", "message", "==", "'websocket client ready'", ":", "if", "self", ".", "connected", ":", "# TBD: Add ability to run command...
40.205128
19.205128
def cat_files(infiles, outfile): '''Cats all files in list infiles into outfile''' f_out = pyfastaq.utils.open_file_write(outfile) for filename in infiles: if os.path.exists(filename): f_in = pyfastaq.utils.open_file_read(filename) for line in f_in: print(lin...
[ "def", "cat_files", "(", "infiles", ",", "outfile", ")", ":", "f_out", "=", "pyfastaq", ".", "utils", ".", "open_file_write", "(", "outfile", ")", "for", "filename", "in", "infiles", ":", "if", "os", ".", "path", ".", "exists", "(", "filename", ")", ":...
33.583333
14.583333
def compact(self, include=None): """ Return compact views - See: Zendesk API `Reference <https://developer.zendesk.com/rest_api/docs/core/views#list-views---compact>`__ """ return self._get(self._build_url(self.endpoint.compact(include=include)))
[ "def", "compact", "(", "self", ",", "include", "=", "None", ")", ":", "return", "self", ".", "_get", "(", "self", ".", "_build_url", "(", "self", ".", "endpoint", ".", "compact", "(", "include", "=", "include", ")", ")", ")" ]
46.833333
19.166667
def as_value(ele): """ convert the specified element as a python value """ dtype = ele.datatype() # print '%s = %s' % (ele.name(), dtype) if dtype in (1, 2, 3, 4, 5, 6, 7, 9, 12): # BOOL, CHAR, BYTE, INT32, INT64, FLOAT32, FLOAT64, BYTEARRAY, DECIMAL) return ele.g...
[ "def", "as_value", "(", "ele", ")", ":", "dtype", "=", "ele", ".", "datatype", "(", ")", "# print '%s = %s' % (ele.name(), dtype)", "if", "dtype", "in", "(", "1", ",", "2", ",", "3", ",", "4", ",", "5", ",", "6", ",", "7", ",", "9", ",", "12", ")...
40.395349
16.046512
def ltcube_moon(self, **kwargs): """ return the name of a livetime cube file """ kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) kwargs_copy['dataset'] = kwargs.get('dataset', self.dataset(**kwargs)) self._replace_none(kwargs_copy) localpa...
[ "def", "ltcube_moon", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs_copy", "=", "self", ".", "base_dict", ".", "copy", "(", ")", "kwargs_copy", ".", "update", "(", "*", "*", "kwargs", ")", "kwargs_copy", "[", "'dataset'", "]", "=", "kwargs", ...
44.272727
11
def stop(self, now=False): """Stop the server gracefully. Do not take any new transfers, but complete the existing ones. If force is True, drop everything and stop. Note, immediately will not interrupt the select loop, it will happen when the server returns on ready data, or a timeout. ...
[ "def", "stop", "(", "self", ",", "now", "=", "False", ")", ":", "if", "now", ":", "self", ".", "shutdown_immediately", "=", "True", "else", ":", "self", ".", "shutdown_gracefully", "=", "True" ]
45.6
17.2
def persist_upstream_structure(self): """Persist json file with the upstream steps structure, that is step names and their connections.""" persist_dir = os.path.join(self.experiment_directory, '{}_upstream_structure.json'.format(self.name)) logger.info('Step {}, saving upstream pipeline structur...
[ "def", "persist_upstream_structure", "(", "self", ")", ":", "persist_dir", "=", "os", ".", "path", ".", "join", "(", "self", ".", "experiment_directory", ",", "'{}_upstream_structure.json'", ".", "format", "(", "self", ".", "name", ")", ")", "logger", ".", "...
82.8
30.4
def K(self, X, X2=None): # model : -a d^2y/dx^2 + b dy/dt + c * y = U # kernel Kyy rbf spatiol temporal # vyt Y temporal variance vyx Y spatiol variance lyt Y temporal lengthscale lyx Y spatiol lengthscale # kernel Kuu doper( doper(Kyy)) # a b c lyt lyx vyx*vyt "...
[ "def", "K", "(", "self", ",", "X", ",", "X2", "=", "None", ")", ":", "# model : -a d^2y/dx^2 + b dy/dt + c * y = U", "# kernel Kyy rbf spatiol temporal", "# vyt Y temporal variance vyx Y spatiol variance lyt Y temporal lengthscale lyx Y spatiol lengthscale", "# kernel Kuu doper...
45.786885
28.229508
def determine_opening_indent(indent_texts): '''Determine the opening indent level for a docstring. The opening indent level is the indent level is the first non-zero indent level of a non-empty line in the docstring. Args: indent_texts: The lines of the docstring as an iterable over 2-tuples ...
[ "def", "determine_opening_indent", "(", "indent_texts", ")", ":", "num_lines", "=", "len", "(", "indent_texts", ")", "if", "num_lines", "<", "1", ":", "return", "0", "assert", "num_lines", ">=", "1", "first_line_indent", "=", "indent_texts", "[", "0", "]", "...
25.542857
23.428571
def run(command): ''' Run command in shell, accepts command construction from list Return (return_code, stdout, stderr) stdout and stderr - as list of strings ''' if isinstance(command, list): command = ' '.join(command) out = subprocess.run(command, shell=True, stdout=subprocess.PIP...
[ "def", "run", "(", "command", ")", ":", "if", "isinstance", "(", "command", ",", "list", ")", ":", "command", "=", "' '", ".", "join", "(", "command", ")", "out", "=", "subprocess", ".", "run", "(", "command", ",", "shell", "=", "True", ",", "stdou...
40.9
21.1
def _run_pants_with_retry(self, pantsd_handle, retries=3): """Runs pants remotely with retry and recovery for nascent executions. :param PantsDaemon.Handle pantsd_handle: A Handle for the daemon to connect to. """ attempt = 1 while 1: logger.debug( 'connecting to pantsd on port {} (at...
[ "def", "_run_pants_with_retry", "(", "self", ",", "pantsd_handle", ",", "retries", "=", "3", ")", ":", "attempt", "=", "1", "while", "1", ":", "logger", ".", "debug", "(", "'connecting to pantsd on port {} (attempt {}/{})'", ".", "format", "(", "pantsd_handle", ...
39.676471
23.352941
def get_dependency_element(self, symbol): """Checks if the specified symbol is the name of one of the methods that this module depends on. If it is, search for the actual code element and return it.""" for depend in self.dependencies: if "." in depend: #We kno...
[ "def", "get_dependency_element", "(", "self", ",", "symbol", ")", ":", "for", "depend", "in", "self", ".", "dependencies", ":", "if", "\".\"", "in", "depend", ":", "#We know the module name and the executable name, easy", "if", "depend", ".", "split", "(", "\".\""...
45.208333
19.291667
def setTargets(self, value): """ Sets all targets the the value of the argument. This value must be in the range [min,max]. """ # Removed this because both propagate and backprop (via compute_error) set targets #if self.verify and not self.targetSet == 0: # if not self...
[ "def", "setTargets", "(", "self", ",", "value", ")", ":", "# Removed this because both propagate and backprop (via compute_error) set targets", "#if self.verify and not self.targetSet == 0:", "# if not self.warningIssued:", "# print 'Warning! Targets have already been set and no inte...
57.2
24.8
def open(self, vendor_id: int = 0x16c0, product_id: int = 0x5dc, bus: int = None, address: int = None) -> bool: """ Open the first device that matches the search criteria. Th default parameters are set up for the likely most common case of a single uDMX interface. However, for the case o...
[ "def", "open", "(", "self", ",", "vendor_id", ":", "int", "=", "0x16c0", ",", "product_id", ":", "int", "=", "0x5dc", ",", "bus", ":", "int", "=", "None", ",", "address", ":", "int", "=", "None", ")", "->", "bool", ":", "kwargs", "=", "{", "}", ...
41.64
17.96
def list(self): """Lists the jobs on the server. """ queue = self._get_queue() if queue is None: raise QueueDoesntExist output = self.check_output('%s' % shell_escape(queue / 'commands/list')) job_id, info = None, None ...
[ "def", "list", "(", "self", ")", ":", "queue", "=", "self", ".", "_get_queue", "(", ")", "if", "queue", "is", "None", ":", "raise", "QueueDoesntExist", "output", "=", "self", ".", "check_output", "(", "'%s'", "%", "shell_escape", "(", "queue", "/", "'c...
31.086957
11.652174
def _translate(self): """ Convert the DataFrame in `self.data` and the attrs from `_build_styles` into a dictionary of {head, body, uuid, cellstyle}. """ table_styles = self.table_styles or [] caption = self.caption ctx = self.ctx precision = self.precisio...
[ "def", "_translate", "(", "self", ")", ":", "table_styles", "=", "self", ".", "table_styles", "or", "[", "]", "caption", "=", "self", ".", "caption", "ctx", "=", "self", ".", "ctx", "precision", "=", "self", ".", "precision", "hidden_index", "=", "self",...
39.927711
15.39759
def crypto_hash_sha512(message): """ Hashes and returns the message ``message``. :param message: bytes :rtype: bytes """ digest = ffi.new("unsigned char[]", crypto_hash_sha512_BYTES) rc = lib.crypto_hash_sha512(digest, message, len(message)) ensure(rc == 0, 'Unexpected librar...
[ "def", "crypto_hash_sha512", "(", "message", ")", ":", "digest", "=", "ffi", ".", "new", "(", "\"unsigned char[]\"", ",", "crypto_hash_sha512_BYTES", ")", "rc", "=", "lib", ".", "crypto_hash_sha512", "(", "digest", ",", "message", ",", "len", "(", "message", ...
31.769231
14.230769
def process_item(self, item, spider): # pylint: disable=unused-argument "Check for DRF urls." url = URLObject(item["url"]) if url.path.startswith("/api/"): raise DropItem(u"Dropping DRF url {url}".format(url=url)) else: return item
[ "def", "process_item", "(", "self", ",", "item", ",", "spider", ")", ":", "# pylint: disable=unused-argument", "url", "=", "URLObject", "(", "item", "[", "\"url\"", "]", ")", "if", "url", ".", "path", ".", "startswith", "(", "\"/api/\"", ")", ":", "raise",...
40.285714
17.142857
def _process_service_check(self, name, nb_procs, bounds, tags): """ Report a service check, for each process in search_string. Report as OK if the process is in the warning thresholds CRITICAL out of the critical thresholds WARNING o...
[ "def", "_process_service_check", "(", "self", ",", "name", ",", "nb_procs", ",", "bounds", ",", "tags", ")", ":", "# FIXME 8.x remove the `process:name` tag", "service_check_tags", "=", "tags", "+", "[", "\"process:{}\"", ".", "format", "(", "name", ")", "]", "s...
43.344828
21.551724
def get_docs(self, arg=None): ''' Return a dictionary of functions and the inline documentation for each ''' if arg: if '*' in arg: target_mod = arg _use_fnmatch = True else: target_mod = arg + '.' if not arg.endswit...
[ "def", "get_docs", "(", "self", ",", "arg", "=", "None", ")", ":", "if", "arg", ":", "if", "'*'", "in", "arg", ":", "target_mod", "=", "arg", "_use_fnmatch", "=", "True", "else", ":", "target_mod", "=", "arg", "+", "'.'", "if", "not", "arg", ".", ...
39.869565
19.434783
def create_zones(self, add_zones): """Create instances of additional zones for the receiver.""" for zone, zname in add_zones.items(): # Name either set explicitly or name of Main Zone with suffix zonename = "{} {}".format(self._name, zone) if ( zname is None) else...
[ "def", "create_zones", "(", "self", ",", "add_zones", ")", ":", "for", "zone", ",", "zname", "in", "add_zones", ".", "items", "(", ")", ":", "# Name either set explicitly or name of Main Zone with suffix", "zonename", "=", "\"{} {}\"", ".", "format", "(", "self", ...
52.625
10.625
def find_bridges(prior_bridges=None): """ Confirm or locate IP addresses of Philips Hue bridges. `prior_bridges` -- optional list of bridge serial numbers * omitted - all discovered bridges returned as dictionary * single string - returns IP as string or None * dictionary - validate provided ip's b...
[ "def", "find_bridges", "(", "prior_bridges", "=", "None", ")", ":", "found_bridges", "=", "{", "}", "# Validate caller's provided list", "try", ":", "prior_bridges_list", "=", "prior_bridges", ".", "items", "(", ")", "except", "AttributeError", ":", "# if caller did...
39.691489
19.297872
def buff(self, target, buff, **kwargs): """ Summon \a buff and apply it to \a target If keyword arguments are given, attempt to set the given values to the buff. Example: player.buff(target, health=random.randint(1, 5)) NOTE: Any Card can buff any other Card. The controller of the Card that buffs the targ...
[ "def", "buff", "(", "self", ",", "target", ",", "buff", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "self", ".", "controller", ".", "card", "(", "buff", ",", "self", ")", "ret", ".", "source", "=", "self", "ret", ".", "apply", "(", "target", ...
33.066667
12.533333
def _get_more_compressed(collection_name, num_to_return, cursor_id, ctx): """Internal compressed getMore message helper.""" return _compress( 2005, _get_more(collection_name, num_to_return, cursor_id), ctx)
[ "def", "_get_more_compressed", "(", "collection_name", ",", "num_to_return", ",", "cursor_id", ",", "ctx", ")", ":", "return", "_compress", "(", "2005", ",", "_get_more", "(", "collection_name", ",", "num_to_return", ",", "cursor_id", ")", ",", "ctx", ")" ]
54.75
21
def mask_roi_unique(self): """ Assemble a set of unique magnitude tuples for the ROI """ # There is no good inherent way in numpy to do this... # http://stackoverflow.com/q/16970982/ # Also possible and simple: #return np.unique(zip(self.mask_1.mask_roi_sparse,se...
[ "def", "mask_roi_unique", "(", "self", ")", ":", "# There is no good inherent way in numpy to do this...", "# http://stackoverflow.com/q/16970982/", "# Also possible and simple:", "#return np.unique(zip(self.mask_1.mask_roi_sparse,self.mask_2.mask_roi_sparse))", "A", "=", "np", ".", "vst...
40.615385
20.923077
def is_transcript_available(video_id, language_code=None): """ Returns whether the transcripts are available for a video. Arguments: video_id: it can be an edx_video_id or an external_id extracted from external sources in a video component. language_code: it will the language code of the re...
[ "def", "is_transcript_available", "(", "video_id", ",", "language_code", "=", "None", ")", ":", "filter_attrs", "=", "{", "'video__edx_video_id'", ":", "video_id", "}", "if", "language_code", ":", "filter_attrs", "[", "'language_code'", "]", "=", "language_code", ...
40.5
23.928571
def get_default_cache(): """Get the default cache location. Adheres to the XDG Base Directory specification, as described in https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html :return: the default cache directory absolute path """ xdg_cache_home = os.environ.get('XDG_CACH...
[ "def", "get_default_cache", "(", ")", ":", "xdg_cache_home", "=", "os", ".", "environ", ".", "get", "(", "'XDG_CACHE_HOME'", ")", "or", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "expanduser", "(", "'~'", ")", ",", "'.cache'", ")", ...
33.076923
22.846154
def insert_cluster(self, cluster): """! @brief Insert cluster that is represented as list of points where each point is represented by list of coordinates. @details Clustering feature is created for that cluster and inserted to the tree. @param[in] cluster (list): Cluster t...
[ "def", "insert_cluster", "(", "self", ",", "cluster", ")", ":", "entry", "=", "cfentry", "(", "len", "(", "cluster", ")", ",", "linear_sum", "(", "cluster", ")", ",", "square_sum", "(", "cluster", ")", ")", "self", ".", "insert", "(", "entry", ")" ]
47.909091
33.090909
def joint_plot(x, y, marginalBins=50, gridsize=50, plotlimits=None, logscale_cmap=False, logscale_marginals=False, alpha_hexbin=0.75, alpha_marginals=0.75, cmap="inferno_r", marginalCol=None, figsize=(8, 8), fontsize=8, *args, **kwargs): """ Plots some x and y data using hexbins along with a colorbar and ma...
[ "def", "joint_plot", "(", "x", ",", "y", ",", "marginalBins", "=", "50", ",", "gridsize", "=", "50", ",", "plotlimits", "=", "None", ",", "logscale_cmap", "=", "False", ",", "logscale_marginals", "=", "False", ",", "alpha_hexbin", "=", "0.75", ",", "alph...
39.993243
18.912162
def factory(cfg, login, pswd, request_type): """ Instantiate ExportRequest :param cfg: request configuration, should consist of request description (url and optional parameters) :param login: :param pswd: :param request_type: TYPE_SET_FIELD_VALUE || TYPE_CREATE_ENTITY || ...
[ "def", "factory", "(", "cfg", ",", "login", ",", "pswd", ",", "request_type", ")", ":", "if", "request_type", "==", "ExportRequest", ".", "TYPE_SET_FIELD_VALUE", ":", "return", "SetFieldValueRequest", "(", "cfg", ",", "login", ",", "pswd", ")", "elif", "requ...
52.052632
22.894737
def calculate_chunks(self): """ Work out the number of chunks the data is in, for cases where the meta data doesn't change at all so there is no lead in. Also increments the number of values for objects in this segment, based on the number of chunks. """ ...
[ "def", "calculate_chunks", "(", "self", ")", ":", "if", "self", ".", "toc", "[", "'kTocDAQmxRawData'", "]", ":", "# chunks defined differently for DAQmxRawData format", "try", ":", "data_size", "=", "next", "(", "o", ".", "number_values", "*", "o", ".", "raw_dat...
40.360656
18.819672
def forward(self, to_recipients, forward_comment=None): # type: (Union[List[Contact], List[str]], str) -> None """Forward Message to recipients with an optional comment. Args: to_recipients: A list of :class:`Contacts <pyOutlook.core.contact.Contact>` to send the email to. ...
[ "def", "forward", "(", "self", ",", "to_recipients", ",", "forward_comment", "=", "None", ")", ":", "# type: (Union[List[Contact], List[str]], str) -> None", "payload", "=", "dict", "(", ")", "if", "forward_comment", "is", "not", "None", ":", "payload", ".", "upda...
44.25
28.96875
def append_string(t, string): """Append a string to a node, as text or tail of last child.""" node = t.tree if string: if len(node) == 0: if node.text is not None: node.text += string else: node.text = string else: # Get last child ...
[ "def", "append_string", "(", "t", ",", "string", ")", ":", "node", "=", "t", ".", "tree", "if", "string", ":", "if", "len", "(", "node", ")", "==", "0", ":", "if", "node", ".", "text", "is", "not", "None", ":", "node", ".", "text", "+=", "strin...
31.133333
10.666667
def image_mutual_information(image1, image2): """ Compute mutual information between two ANTsImage types ANTsR function: `antsImageMutualInformation` Arguments --------- image1 : ANTsImage image 1 image2 : ANTsImage image 2 Returns ------- scalar Exam...
[ "def", "image_mutual_information", "(", "image1", ",", "image2", ")", ":", "if", "(", "image1", ".", "pixeltype", "!=", "'float'", ")", "or", "(", "image2", ".", "pixeltype", "!=", "'float'", ")", ":", "raise", "ValueError", "(", "'Both images must have float ...
27.969697
25.30303
async def close(self): '''Close the listening socket. This does not close any ServerSession objects created to handle incoming connections. ''' if self.server: self.server.close() await self.server.wait_closed() self.server = None
[ "async", "def", "close", "(", "self", ")", ":", "if", "self", ".", "server", ":", "self", ".", "server", ".", "close", "(", ")", "await", "self", ".", "server", ".", "wait_closed", "(", ")", "self", ".", "server", "=", "None" ]
36.5
17.25
def create_new_migration_record(self): """ Create a new migration record for this migration set """ migration_record = self.migration_model( name=self.name, version=self.latest_migration) self.session.add(migration_record) self.session.commit()
[ "def", "create_new_migration_record", "(", "self", ")", ":", "migration_record", "=", "self", ".", "migration_model", "(", "name", "=", "self", ".", "name", ",", "version", "=", "self", ".", "latest_migration", ")", "self", ".", "session", ".", "add", "(", ...
34.222222
6.444444
def list_default_storage_policy_of_datastore(datastore, service_instance=None): ''' Returns a list of datastores assign the the storage policies. datastore Name of the datastore to assign. The datastore needs to be visible to the VMware entity the proxy points to. service_insta...
[ "def", "list_default_storage_policy_of_datastore", "(", "datastore", ",", "service_instance", "=", "None", ")", ":", "log", ".", "trace", "(", "'Listing the default storage policy of datastore \\'%s\\''", ",", "datastore", ")", "# Find datastore", "target_ref", "=", "_get_p...
40.793103
26.793103
def toListString(value): """ Convert a value to list of strings, if possible. """ if TypeConverters._can_convert_to_list(value): value = TypeConverters.toList(value) if all(map(lambda v: TypeConverters._can_convert_to_string(v), value)): return [Ty...
[ "def", "toListString", "(", "value", ")", ":", "if", "TypeConverters", ".", "_can_convert_to_list", "(", "value", ")", ":", "value", "=", "TypeConverters", ".", "toList", "(", "value", ")", "if", "all", "(", "map", "(", "lambda", "v", ":", "TypeConverters"...
47.444444
17.444444
def orbit_fit_residuals(discoveries, blockID='O13AE'): """Brett: What are relevant and stunning are the actual orbit fit residuals for orbits with d(a)/a<1%. I would be happy with a simple histogram of all those numbers, although the 'tail' (probably blended and not yet completely flagged) should perhap...
[ "def", "orbit_fit_residuals", "(", "discoveries", ",", "blockID", "=", "'O13AE'", ")", ":", "ra_residuals", "=", "[", "]", "dec_residuals", "=", "[", "]", "ressum", "=", "[", "]", "for", "i", ",", "orbit", "in", "enumerate", "(", "discoveries", ")", ":",...
51.075
24.675
def process(self, instance, force=False): """Processing is triggered by field's pre_save method. It will be executed if field's value has been changed (known through descriptor and stashing logic) or if model instance has never been saved before, i.e. no pk set, because there is a chance...
[ "def", "process", "(", "self", ",", "instance", ",", "force", "=", "False", ")", ":", "if", "self", ".", "should_process", "and", "(", "force", "or", "self", ".", "has_stashed_value", ")", ":", "self", ".", "set_status", "(", "instance", ",", "{", "'st...
50.333333
19.066667
def findReference(self, name, cls=QtGui.QWidget): """ Looks up a reference from the widget based on its object name. :param name | <str> cls | <subclass of QtGui.QObject> :return <QtGui.QObject> || None """ ref_widg...
[ "def", "findReference", "(", "self", ",", "name", ",", "cls", "=", "QtGui", ".", "QWidget", ")", ":", "ref_widget", "=", "self", ".", "_referenceWidget", "if", "not", "ref_widget", ":", "return", "None", "if", "ref_widget", ".", "objectName", "(", ")", "...
32.375
13.25
def createproject(): """ compile for the platform we are running on """ os.chdir(build_dir) if windows_build: command = 'cmake -A {} -DPYTHON_EXECUTABLE:FILEPATH="{}" ../..'.format("win32" if bitness==32 else "x64", sys.executable) os.system(command) if bitness==64: for l...
[ "def", "createproject", "(", ")", ":", "os", ".", "chdir", "(", "build_dir", ")", "if", "windows_build", ":", "command", "=", "'cmake -A {} -DPYTHON_EXECUTABLE:FILEPATH=\"{}\" ../..'", ".", "format", "(", "\"win32\"", "if", "bitness", "==", "32", "else", "\"x64\""...
51.066667
26.533333
def _umis_cmd(data): """Return umis command line argument, with correct python and locale. """ return "%s %s %s" % (utils.locale_export(), utils.get_program_python("umis"), config_utils.get_program("umis", data["config"], default="umis"))
[ "def", "_umis_cmd", "(", "data", ")", ":", "return", "\"%s %s %s\"", "%", "(", "utils", ".", "locale_export", "(", ")", ",", "utils", ".", "get_program_python", "(", "\"umis\"", ")", ",", "config_utils", ".", "get_program", "(", "\"umis\"", ",", "data", "[...
49.166667
15.833333
def if_none_match(self): """ Get the if-none-match option of a request. :return: True, if if-none-match is present :rtype : bool """ for option in self.options: if option.number == defines.OptionRegistry.IF_NONE_MATCH.number: return True ...
[ "def", "if_none_match", "(", "self", ")", ":", "for", "option", "in", "self", ".", "options", ":", "if", "option", ".", "number", "==", "defines", ".", "OptionRegistry", ".", "IF_NONE_MATCH", ".", "number", ":", "return", "True", "return", "False" ]
29.545455
15.363636
def saveCertPem(self, cert, path): ''' Save a certificate in PEM format to a file outside the certdir. ''' with s_common.genfile(path) as fd: fd.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
[ "def", "saveCertPem", "(", "self", ",", "cert", ",", "path", ")", ":", "with", "s_common", ".", "genfile", "(", "path", ")", "as", "fd", ":", "fd", ".", "write", "(", "crypto", ".", "dump_certificate", "(", "crypto", ".", "FILETYPE_PEM", ",", "cert", ...
40.166667
21.5
def _in_class(self, node): """Find if callable is function or method.""" # Move left one indentation level and check if that callable is a class indent = self._get_indent(node) for indent_dict in reversed(self._indent_stack): # pragma: no branch if (indent_dict["level"] < in...
[ "def", "_in_class", "(", "self", ",", "node", ")", ":", "# Move left one indentation level and check if that callable is a class", "indent", "=", "self", ".", "_get_indent", "(", "node", ")", "for", "indent_dict", "in", "reversed", "(", "self", ".", "_indent_stack", ...
58.714286
21.142857
def upload_theme(): """ upload and/or update the theme with the current git state""" get_vars() with fab.settings(): local_theme_path = path.abspath( path.join(fab.env['config_base'], fab.env.instance.config['local_theme_path'])) rsync( '-av', ...
[ "def", "upload_theme", "(", ")", ":", "get_vars", "(", ")", "with", "fab", ".", "settings", "(", ")", ":", "local_theme_path", "=", "path", ".", "abspath", "(", "path", ".", "join", "(", "fab", ".", "env", "[", "'config_base'", "]", ",", "fab", ".", ...
34.214286
16.214286
def _get_base_command(self): """Returns the base command plus command-line options. Does not include input file, output file, and training set. """ cd_command = ''.join(['cd ', str(self.WorkingDir), ';']) jvm_command = "java" jvm_arguments = self._commandline_join( ...
[ "def", "_get_base_command", "(", "self", ")", ":", "cd_command", "=", "''", ".", "join", "(", "[", "'cd '", ",", "str", "(", "self", ".", "WorkingDir", ")", ",", "';'", "]", ")", "jvm_command", "=", "\"java\"", "jvm_arguments", "=", "self", ".", "_comm...
41.882353
17.235294
def _soup_strings(soup): """Return text strings in soup.""" paragraph_tags = set([ "caption", "details", "h1", "h2", "h3", "h4", "h5", "h6", "li", "p", "td", "div", "span" ]) skip_children = None for descendant in soup.descendants: # If we've treated a tag as a contiguous paragraph, don't re-...
[ "def", "_soup_strings", "(", "soup", ")", ":", "paragraph_tags", "=", "set", "(", "[", "\"caption\"", ",", "\"details\"", ",", "\"h1\"", ",", "\"h2\"", ",", "\"h3\"", ",", "\"h4\"", ",", "\"h5\"", ",", "\"h6\"", ",", "\"li\"", ",", "\"p\"", ",", "\"td\""...
33.636364
21.863636
def find_split_node(mst_wood, i): """ Parameters ---------- mst_wood : list of dictionarys i : int Number of the stroke where one mst gets split Returns ------- tuple : (mst index, node index) """ for mst_index, mst in enumerate(mst_wood): if i in mst['st...
[ "def", "find_split_node", "(", "mst_wood", ",", "i", ")", ":", "for", "mst_index", ",", "mst", "in", "enumerate", "(", "mst_wood", ")", ":", "if", "i", "in", "mst", "[", "'strokes'", "]", ":", "return", "(", "mst_index", ",", "mst", "[", "'strokes'", ...
25.294118
17.294118
def _match_vcs_scheme(url): # type: (str) -> Optional[str] """Look for VCS schemes in the URL. Returns the matched VCS scheme, or None if there's no match. """ from pipenv.patched.notpip._internal.vcs import VcsSupport for scheme in VcsSupport.schemes: if url.lower().startswith(scheme) ...
[ "def", "_match_vcs_scheme", "(", "url", ")", ":", "# type: (str) -> Optional[str]", "from", "pipenv", ".", "patched", ".", "notpip", ".", "_internal", ".", "vcs", "import", "VcsSupport", "for", "scheme", "in", "VcsSupport", ".", "schemes", ":", "if", "url", "....
34.636364
16.272727
def compress_pdf(filepath, output_path, ghostscript_binary): """Compress a single PDF file. Args: filepath (str): Path to the PDF file. output_path (str): Output path. ghostscript_binary (str): Name/alias of the Ghostscript binary. Raises: ValueError FileNotFoundErr...
[ "def", "compress_pdf", "(", "filepath", ",", "output_path", ",", "ghostscript_binary", ")", ":", "if", "not", "filepath", ".", "endswith", "(", "PDF_EXTENSION", ")", ":", "raise", "ValueError", "(", "\"Filename must end with .pdf!\\n%s does not.\"", "%", "filepath", ...
39.125
18.53125
def add_attachment(message, attachment, rfc2231=True): '''Attach an attachment to a message as a side effect. Arguments: message: MIMEMultipart instance. attachment: Attachment instance. ''' data = attachment.read() part = MIMEBase('application', 'octet-stream') part.set_payloa...
[ "def", "add_attachment", "(", "message", ",", "attachment", ",", "rfc2231", "=", "True", ")", ":", "data", "=", "attachment", ".", "read", "(", ")", "part", "=", "MIMEBase", "(", "'application'", ",", "'octet-stream'", ")", "part", ".", "set_payload", "(",...
32.117647
19.294118
def get(company='', company_uri=''): """Performs a HTTP GET for a glassdoor page and returns json""" if not company and not company_uri: raise Exception("glassdoor.gd.get(company='', company_uri=''): "\ " company or company_uri required") payload = {} if not company_u...
[ "def", "get", "(", "company", "=", "''", ",", "company_uri", "=", "''", ")", ":", "if", "not", "company", "and", "not", "company_uri", ":", "raise", "Exception", "(", "\"glassdoor.gd.get(company='', company_uri=''): \"", "\" company or company_uri required\"", ")", ...
39.411765
13.470588
def _read_py(self, fin_py, get_goids_only, exclude_ungrouped): """Read Python sections file. Store: section2goids sections_seen. Return goids_fin.""" goids_sec = [] with open(fin_py) as istrm: section_name = None for line in istrm: mgo = self.srch_py_goids...
[ "def", "_read_py", "(", "self", ",", "fin_py", ",", "get_goids_only", ",", "exclude_ungrouped", ")", ":", "goids_sec", "=", "[", "]", "with", "open", "(", "fin_py", ")", "as", "istrm", ":", "section_name", "=", "None", "for", "line", "in", "istrm", ":", ...
51.416667
17.5
def add_clause(self, clause, no_return=True): """ Add a new clause to solver's internal formula. """ if self.lingeling: pysolvers.lingeling_add_cl(self.lingeling, clause)
[ "def", "add_clause", "(", "self", ",", "clause", ",", "no_return", "=", "True", ")", ":", "if", "self", ".", "lingeling", ":", "pysolvers", ".", "lingeling_add_cl", "(", "self", ".", "lingeling", ",", "clause", ")" ]
30.428571
14.142857
def MergeAttributeContainers( self, callback=None, maximum_number_of_containers=0): """Reads attribute containers from a task storage file into the writer. Args: callback (function[StorageWriter, AttributeContainer]): function to call after each attribute container is deserialized. ...
[ "def", "MergeAttributeContainers", "(", "self", ",", "callback", "=", "None", ",", "maximum_number_of_containers", "=", "0", ")", ":", "if", "maximum_number_of_containers", "<", "0", ":", "raise", "ValueError", "(", "'Invalid maximum number of containers'", ")", "if",...
33.443038
23.265823
def markers(): ''' Prints a list of valid marker types for scatter() Returns: None ''' print("Available markers: \n\n - " + "\n - ".join(list(MarkerType))) print() print("Shortcuts: \n\n" + "\n".join(" %r: %s" % item for item in _MARKER_SHORTCUTS.items()))
[ "def", "markers", "(", ")", ":", "print", "(", "\"Available markers: \\n\\n - \"", "+", "\"\\n - \"", ".", "join", "(", "list", "(", "MarkerType", ")", ")", ")", "print", "(", ")", "print", "(", "\"Shortcuts: \\n\\n\"", "+", "\"\\n\"", ".", "join", "(", "\...
31.222222
32.111111
def clear_reply_handlers_by_message_id(self, message_id): """ Clears all callback functions registered by register_for_reply() and register_for_reply_by_message_id(). :param message_id: The message id for which we want to clear reply handlers """ self.reply_handlers[message_id] ...
[ "def", "clear_reply_handlers_by_message_id", "(", "self", ",", "message_id", ")", ":", "self", ".", "reply_handlers", "[", "message_id", "]", "=", "[", "]", "if", "self", ".", "reply_saver", "is", "not", "None", ":", "self", ".", "reply_saver", ".", "start_s...
40.5
22.3
def setvcpus(vm_, vcpus): ''' Changes the amount of vcpus allocated to VM. vcpus is an int representing the number to be assigned CLI Example: .. code-block:: bash salt '*' virt.setvcpus myvm 2 ''' with _get_xapi_session() as xapi: vm_uuid = _get_label_uuid(xapi, 'VM', vm...
[ "def", "setvcpus", "(", "vm_", ",", "vcpus", ")", ":", "with", "_get_xapi_session", "(", ")", "as", "xapi", ":", "vm_uuid", "=", "_get_label_uuid", "(", "xapi", ",", "'VM'", ",", "vm_", ")", "if", "vm_uuid", "is", "False", ":", "return", "False", "try"...
23.904762
21.142857
def build_docx(path_jinja2, template_name, path_outfile, template_kwargs=None): '''Helper function for building a docx file from a latex jinja2 template :param path_jinja2: the root directory for latex jinja2 templates :param template_name: the relative path, to path_jinja2, to the desired jinja2 L...
[ "def", "build_docx", "(", "path_jinja2", ",", "template_name", ",", "path_outfile", ",", "template_kwargs", "=", "None", ")", ":", "latex_template_object", "=", "LatexBuild", "(", "path_jinja2", ",", "template_name", ",", "template_kwargs", ",", ")", "return", "la...
46.352941
24.470588
def SearchFileNameTable(self, fileName): """ Search FileName table. Find the show id for a given file name. Parameters ---------- fileName : string File name to look up in table. Returns ---------- int or None If a match is found in the database table the show ...
[ "def", "SearchFileNameTable", "(", "self", ",", "fileName", ")", ":", "goodlogging", ".", "Log", ".", "Info", "(", "\"DB\"", ",", "\"Looking up filename string '{0}' in database\"", ".", "format", "(", "fileName", ")", ",", "verbosity", "=", "self", ".", "logVer...
34.5
27.970588
def _validate_non_edges_do_not_have_edge_like_properties(class_name, properties): """Validate that non-edges do not have the in/out properties defined.""" has_source = EDGE_SOURCE_PROPERTY_NAME in properties has_destination = EDGE_DESTINATION_PROPERTY_NAME in properties if has_source or has_destination...
[ "def", "_validate_non_edges_do_not_have_edge_like_properties", "(", "class_name", ",", "properties", ")", ":", "has_source", "=", "EDGE_SOURCE_PROPERTY_NAME", "in", "properties", "has_destination", "=", "EDGE_DESTINATION_PROPERTY_NAME", "in", "properties", "if", "has_source", ...
64.615385
34.615385
def remove_part_images(filename): """Remove PART(#)_files directory containing images from disk.""" dirname = '{0}_files'.format(os.path.splitext(filename)[0]) if os.path.exists(dirname): shutil.rmtree(dirname)
[ "def", "remove_part_images", "(", "filename", ")", ":", "dirname", "=", "'{0}_files'", ".", "format", "(", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "0", "]", ")", "if", "os", ".", "path", ".", "exists", "(", "dirname", ")", ":",...
45.2
9.8
def download_file_insecure(url, target): """Use Python to download the file, without connection authentication.""" src = urlopen(url) try: # Read all the data in one block. data = src.read() finally: src.close() # Write all the data in one block to avoid creating a partial f...
[ "def", "download_file_insecure", "(", "url", ",", "target", ")", ":", "src", "=", "urlopen", "(", "url", ")", "try", ":", "# Read all the data in one block.", "data", "=", "src", ".", "read", "(", ")", "finally", ":", "src", ".", "close", "(", ")", "# Wr...
31.083333
17.333333
def gen_params(raw_params): u""" Generator that yields tuples of (name, default_value) for each parameter in the list If no default is given, then it is default_value is None (not Leaf(token.NAME, 'None')) """ assert raw_params[0].type == token.STAR and len(raw_params) > 2 curr_idx = 2 # the fir...
[ "def", "gen_params", "(", "raw_params", ")", ":", "assert", "raw_params", "[", "0", "]", ".", "type", "==", "token", ".", "STAR", "and", "len", "(", "raw_params", ")", ">", "2", "curr_idx", "=", "2", "# the first place a keyword-only parameter name can be is ind...
39
16.08