text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def spectral_density(self, two_pi=True, res=1200): r""" Compute the spectral density function. The spectral density is the discrete time Fourier transform of the autocovariance function. In particular, .. math:: f(w) = \sum_k \gamma(k) \exp(-ikw) where ga...
[ "def", "spectral_density", "(", "self", ",", "two_pi", "=", "True", ",", "res", "=", "1200", ")", ":", "from", "scipy", ".", "signal", "import", "freqz", "w", ",", "h", "=", "freqz", "(", "self", ".", "ma_poly", ",", "self", ".", "ar_poly", ",", "w...
34.974359
22.025641
def Spring( startPoint=(0, 0, 0), endPoint=(1, 0, 0), coils=20, r=0.1, r2=None, thickness=None, c="grey", alpha=1, ): """ Build a spring of specified nr of `coils` between `startPoint` and `endPoint`. :param int coils: number of coils :param float r: radius at start poin...
[ "def", "Spring", "(", "startPoint", "=", "(", "0", ",", "0", ",", "0", ")", ",", "endPoint", "=", "(", "1", ",", "0", ",", "0", ")", ",", "coils", "=", "20", ",", "r", "=", "0.1", ",", "r2", "=", "None", ",", "thickness", "=", "None", ",", ...
26.625
16.0625
def parse_named_unicode(self, i): """Parse named Unicode.""" value = ord(_unicodedata.lookup(self.get_named_unicode(i))) single = self.get_single_stack() if self.span_stack: text = self.convert_case(chr(value), self.span_stack[-1]) value = ord(self.convert_case(t...
[ "def", "parse_named_unicode", "(", "self", ",", "i", ")", ":", "value", "=", "ord", "(", "_unicodedata", ".", "lookup", "(", "self", ".", "get_named_unicode", "(", "i", ")", ")", ")", "single", "=", "self", ".", "get_single_stack", "(", ")", "if", "sel...
42.5
17.875
def get_hosting_devices_for_agent(self, context): """Get a list of hosting devices assigned to this agent.""" cctxt = self.client.prepare() return cctxt.call(context, 'get_hosting_devices_for_agent', host=self.host)
[ "def", "get_hosting_devices_for_agent", "(", "self", ",", "context", ")", ":", "cctxt", "=", "self", ".", "client", ".", "prepare", "(", ")", "return", "cctxt", ".", "call", "(", "context", ",", "'get_hosting_devices_for_agent'", ",", "host", "=", "self", "....
47.666667
6.166667
def update_function_config(FunctionName, Role=None, Handler=None, Description=None, Timeout=None, MemorySize=None, region=None, key=None, keyid=None, profile=None, VpcConfig=None, WaitForRole=False, RoleRetries=5, ...
[ "def", "update_function_config", "(", "FunctionName", ",", "Role", "=", "None", ",", "Handler", "=", "None", ",", "Description", "=", "None", ",", "Timeout", "=", "None", ",", "MemorySize", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None"...
37.481013
24.594937
def access_time(self): """dfdatetime.DateTimeValues: access time or None if not available.""" timestamp = self._fsapfs_file_entry.get_access_time_as_integer() return dfdatetime_apfs_time.APFSTime(timestamp=timestamp)
[ "def", "access_time", "(", "self", ")", ":", "timestamp", "=", "self", ".", "_fsapfs_file_entry", ".", "get_access_time_as_integer", "(", ")", "return", "dfdatetime_apfs_time", ".", "APFSTime", "(", "timestamp", "=", "timestamp", ")" ]
56.25
16.75
def report(self): """ Report usage of training parameters. """ if self.logger: self.logger.info("accessed parameters:") for key in self.used_parameters: self.logger.info(" - %s %s" % (key, "(undefined)" if key in self.undefined_parameters else ""))
[ "def", "report", "(", "self", ")", ":", "if", "self", ".", "logger", ":", "self", ".", "logger", ".", "info", "(", "\"accessed parameters:\"", ")", "for", "key", "in", "self", ".", "used_parameters", ":", "self", ".", "logger", ".", "info", "(", "\" - ...
39.125
16.375
def kde(data, npoints=_npoints): """ Identify peak using Gaussian kernel density estimator. Parameters: ----------- data : The 1d data sample npoints : The number of kde points to evaluate """ # Clipping of severe outliers to concentrate more KDE samples in the parameter range of ...
[ "def", "kde", "(", "data", ",", "npoints", "=", "_npoints", ")", ":", "# Clipping of severe outliers to concentrate more KDE samples in the parameter range of interest", "mad", "=", "np", ".", "median", "(", "np", ".", "fabs", "(", "np", ".", "median", "(", "data", ...
41.368421
18.736842
def check_version_consistency(self): """ Determine if any releasers have inconsistent versions """ version = None releaser_name = None for releaser in self.releasers: try: next_version = releaser.determine_current_version() except...
[ "def", "check_version_consistency", "(", "self", ")", ":", "version", "=", "None", "releaser_name", "=", "None", "for", "releaser", "in", "self", ".", "releasers", ":", "try", ":", "next_version", "=", "releaser", ".", "determine_current_version", "(", ")", "e...
33.75
20.85
def set_inlets(self, pores=[], overwrite=False): r""" Parameters ---------- pores : array_like The list of inlet pores from which the Phase can enter the Network """ if overwrite: self['pore.invasion_sequence'] = -1 self['pore.invasion_seq...
[ "def", "set_inlets", "(", "self", ",", "pores", "=", "[", "]", ",", "overwrite", "=", "False", ")", ":", "if", "overwrite", ":", "self", "[", "'pore.invasion_sequence'", "]", "=", "-", "1", "self", "[", "'pore.invasion_sequence'", "]", "[", "pores", "]",...
33.625
18.9375
def _format_value(value): """Returns `value` in a format parseable by `parse_value`, or `None`. Simply put, This function ensures that when it returns a string value, the following will hold: parse_value(_format_value(value)) == value Args: value: The value to format. Returns: A string repre...
[ "def", "_format_value", "(", "value", ")", ":", "literal", "=", "repr", "(", "value", ")", "try", ":", "if", "parse_value", "(", "literal", ")", "==", "value", ":", "return", "literal", "except", "SyntaxError", ":", "pass", "return", "None" ]
23.454545
23.909091
def _get_requested_spec(self, obj, spec_name): """Helper to translate user specifications to needed objects.""" requested = self._specs_in[spec_name] if isinstance(requested, str): return _get_attr_by_tag(obj, requested, spec_name) else: return requested
[ "def", "_get_requested_spec", "(", "self", ",", "obj", ",", "spec_name", ")", ":", "requested", "=", "self", ".", "_specs_in", "[", "spec_name", "]", "if", "isinstance", "(", "requested", ",", "str", ")", ":", "return", "_get_attr_by_tag", "(", "obj", ",",...
43.428571
10.571429
def p_expr_add_term(self, args): ' expr ::= expr ADD_OP term ' op = 'add' if args[1].attr == '+' else 'subtract' return AST(op, [args[0], args[2]])
[ "def", "p_expr_add_term", "(", "self", ",", "args", ")", ":", "op", "=", "'add'", "if", "args", "[", "1", "]", ".", "attr", "==", "'+'", "else", "'subtract'", "return", "AST", "(", "op", ",", "[", "args", "[", "0", "]", ",", "args", "[", "2", "...
42
7.5
def channel_is_opened( self, participant1: Address, participant2: Address, block_identifier: BlockSpecification, channel_identifier: ChannelID, ) -> bool: """ Returns true if the channel is in an open state, false otherwise. """ try: ...
[ "def", "channel_is_opened", "(", "self", ",", "participant1", ":", "Address", ",", "participant2", ":", "Address", ",", "block_identifier", ":", "BlockSpecification", ",", "channel_identifier", ":", "ChannelID", ",", ")", "->", "bool", ":", "try", ":", "channel_...
37.277778
11.888889
def explore_batch(traj, batch): """Chooses exploration according to `batch`""" explore_dict = {} explore_dict['sigma'] = np.arange(10.0 * batch, 10.0*(batch+1), 1.0).tolist() # for batch = 0 explores sigma in [0.0, 1.0, 2.0, ..., 9.0], # for batch = 1 explores sigma in [10.0, 11.0, 12.0, ..., 19.0] ...
[ "def", "explore_batch", "(", "traj", ",", "batch", ")", ":", "explore_dict", "=", "{", "}", "explore_dict", "[", "'sigma'", "]", "=", "np", ".", "arange", "(", "10.0", "*", "batch", ",", "10.0", "*", "(", "batch", "+", "1", ")", ",", "1.0", ")", ...
45.125
19.125
def create_sparse_instance(cls, values, max_values, classname="weka.core.SparseInstance", weight=1.0): """ Creates a new sparse instance. :param values: the list of tuples (0-based index and internal format float). The indices of the tuples must be in ascending order and ...
[ "def", "create_sparse_instance", "(", "cls", ",", "values", ",", "max_values", ",", "classname", "=", "\"weka.core.SparseInstance\"", ",", "weight", "=", "1.0", ")", ":", "jni_classname", "=", "classname", ".", "replace", "(", "\".\"", ",", "\"/\"", ")", "indi...
44.392857
20.107143
def seconds_to_time(x): """Convert a number of second into a time""" t = int(x * 10**6) ms = t % 10**6 t = t // 10**6 s = t % 60 t = t // 60 m = t % 60 t = t // 60 h = t return time(h, m, s, ms)
[ "def", "seconds_to_time", "(", "x", ")", ":", "t", "=", "int", "(", "x", "*", "10", "**", "6", ")", "ms", "=", "t", "%", "10", "**", "6", "t", "=", "t", "//", "10", "**", "6", "s", "=", "t", "%", "60", "t", "=", "t", "//", "60", "m", ...
20.363636
20.363636
def create_output(decoder_output, rows, cols, targets, hparams): """Creates output from decoder output and vars. Args: decoder_output: Tensor of shape [batch, ...], where ... can be any rank such that the number of elements is batch * rows * cols * hparams.hidden_size. rows: Integer representing numb...
[ "def", "create_output", "(", "decoder_output", ",", "rows", ",", "cols", ",", "targets", ",", "hparams", ")", ":", "del", "targets", "# unused arg", "decoded_image", "=", "postprocess_image", "(", "decoder_output", ",", "rows", ",", "cols", ",", "hparams", ")"...
44.823529
21.411765
def send(self, jsonstr): """ Send jsonstr to the UDP collector >>> logger = UDPLogger() >>> logger.send('{"key": "value"}') """ udp_sock = socket(AF_INET, SOCK_DGRAM) udp_sock.sendto(jsonstr.encode('utf-8'), self.addr)
[ "def", "send", "(", "self", ",", "jsonstr", ")", ":", "udp_sock", "=", "socket", "(", "AF_INET", ",", "SOCK_DGRAM", ")", "udp_sock", ".", "sendto", "(", "jsonstr", ".", "encode", "(", "'utf-8'", ")", ",", "self", ".", "addr", ")" ]
29.666667
10.333333
def get_item(item, **kwargs): """ API versioning for each OpenStack service is independent. Generically capture the public members (non-routine and non-private) of the OpenStack SDK objects. Note the lack of the modify_output decorator. Preserving the field naming allows us to reconstruct o...
[ "def", "get_item", "(", "item", ",", "*", "*", "kwargs", ")", ":", "_item", "=", "{", "}", "for", "k", ",", "v", "in", "inspect", ".", "getmembers", "(", "item", ",", "lambda", "a", ":", "not", "(", "inspect", ".", "isroutine", "(", "a", ")", "...
40
25.714286
def _send_scp(self, x, y, p, *args, **kwargs): """Determine the best connection to use to send an SCP packet and use it to transmit. This internal version of the method is identical to send_scp except it has positional arguments for x, y and p. See the arguments for :py...
[ "def", "_send_scp", "(", "self", ",", "x", ",", "y", ",", "p", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Determine the size of packet we expect in return, this is usually the", "# size that we are informed we should expect by SCAMP/SARK or else is", "# the def...
40.190476
20.47619
def to_code(self, context: Context =None): """ Generate the code and return it as a string. """ # Do not override this method! context = context or Context() for imp in self.imports: if imp not in context.imports: context.imports.append(imp) ...
[ "def", "to_code", "(", "self", ",", "context", ":", "Context", "=", "None", ")", ":", "# Do not override this method!", "context", "=", "context", "or", "Context", "(", ")", "for", "imp", "in", "self", ".", "imports", ":", "if", "imp", "not", "in", "cont...
31.166667
12.75
def add(self, session): """ Add session to the container. @param session: Session object """ self._items[session.session_id] = session if session.expiry is not None: self._queue.push(session)
[ "def", "add", "(", "self", ",", "session", ")", ":", "self", ".", "_items", "[", "session", ".", "session_id", "]", "=", "session", "if", "session", ".", "expiry", "is", "not", "None", ":", "self", ".", "_queue", ".", "push", "(", "session", ")" ]
26.333333
12.555556
def _correct_build_location(self): """Move self._temp_build_dir to self._ideal_build_dir/self.req.name For some requirements (e.g. a path to a directory), the name of the package is not available until we run egg_info, so the build_location will return a temporary directory and store th...
[ "def", "_correct_build_location", "(", "self", ")", ":", "if", "self", ".", "source_dir", "is", "not", "None", ":", "return", "assert", "self", ".", "req", "is", "not", "None", "assert", "self", ".", "_temp_build_dir", "assert", "self", ".", "_ideal_build_di...
42.064516
15.806452
async def _handle_home(self, request: Request) -> Response: """Home page request handler.""" if self.description: title = f'{self.name} - {self.description}' else: title = self.name text = dedent( f'''<!DOCTYPE html> <html> <...
[ "async", "def", "_handle_home", "(", "self", ",", "request", ":", "Request", ")", "->", "Response", ":", "if", "self", ".", "description", ":", "title", "=", "f'{self.name} - {self.description}'", "else", ":", "title", "=", "self", ".", "name", "text", "=", ...
29.73913
16.956522
def get_num_features(estimator): """ Return size of a feature vector estimator expects as an input. """ if hasattr(estimator, 'coef_'): # linear models if len(estimator.coef_.shape) == 0: return 1 return estimator.coef_.shape[-1] elif hasattr(estimator, 'feature_importances_'): ...
[ "def", "get_num_features", "(", "estimator", ")", ":", "if", "hasattr", "(", "estimator", ",", "'coef_'", ")", ":", "# linear models", "if", "len", "(", "estimator", ".", "coef_", ".", "shape", ")", "==", "0", ":", "return", "1", "return", "estimator", "...
46.111111
14.555556
def is_type_target(self): """Returns the CustomType instance if this executable is an embedded procedure in a custom type declaration; else False. """ if self._is_type_target is None: #All we need to do is search through the custom types in the parent #module and...
[ "def", "is_type_target", "(", "self", ")", ":", "if", "self", ".", "_is_type_target", "is", "None", ":", "#All we need to do is search through the custom types in the parent", "#module and see if any of their executables points to this method.", "self", ".", "_is_type_target", "=...
44.388889
13.5
def create_html_link(urlbase, urlargd, link_label, linkattrd=None, escape_urlargd=True, escape_linkattrd=True, urlhash=None): """Creates a W3C compliant link. @param urlbase: base url (e.g. config.CFG_SITE_URL/search) @param urlargd: dictionary of parameters. (e.g. ...
[ "def", "create_html_link", "(", "urlbase", ",", "urlargd", ",", "link_label", ",", "linkattrd", "=", "None", ",", "escape_urlargd", "=", "True", ",", "escape_linkattrd", "=", "True", ",", "urlhash", "=", "None", ")", ":", "attributes_separator", "=", "' '", ...
51.566667
21.933333
def dpll(clauses, symbols, model): "See if the clauses are true in a partial model." unknown_clauses = [] ## clauses with an unknown truth value for c in clauses: val = pl_true(c, model) if val == False: return False if val != True: unknown_clauses.append(c) ...
[ "def", "dpll", "(", "clauses", ",", "symbols", ",", "model", ")", ":", "unknown_clauses", "=", "[", "]", "## clauses with an unknown truth value", "for", "c", "in", "clauses", ":", "val", "=", "pl_true", "(", "c", ",", "model", ")", "if", "val", "==", "F...
39.65
17.65
def _clause_formatter(self, cond): '''Formats conditions args is a list of ['field', 'operator', 'value'] ''' if len(cond) == 2 : cond = ' '.join(cond) return cond if 'in' in cond[1].lower() : if not isinstance(cond[2], (tuple, list)): ...
[ "def", "_clause_formatter", "(", "self", ",", "cond", ")", ":", "if", "len", "(", "cond", ")", "==", "2", ":", "cond", "=", "' '", ".", "join", "(", "cond", ")", "return", "cond", "if", "'in'", "in", "cond", "[", "1", "]", ".", "lower", "(", ")...
34.65625
22.59375
def write_doc(doc : MetapackDoc, mt_file=None): """ Write a Metatab doc to a CSV file, and update the Modified time :param doc: :param mt_file: :return: """ from rowgenerators import parse_app_url if not mt_file: mt_file = doc.ref add_giturl(doc) u = parse_app_url(mt_...
[ "def", "write_doc", "(", "doc", ":", "MetapackDoc", ",", "mt_file", "=", "None", ")", ":", "from", "rowgenerators", "import", "parse_app_url", "if", "not", "mt_file", ":", "mt_file", "=", "doc", ".", "ref", "add_giturl", "(", "doc", ")", "u", "=", "parse...
18.636364
21.727273
def from_signed_raw(cls: Type[MembershipType], signed_raw: str) -> MembershipType: """ Return Membership instance from signed raw format :param signed_raw: Signed raw format string :return: """ lines = signed_raw.splitlines(True) n = 0 version = int(Memb...
[ "def", "from_signed_raw", "(", "cls", ":", "Type", "[", "MembershipType", "]", ",", "signed_raw", ":", "str", ")", "->", "MembershipType", ":", "lines", "=", "signed_raw", ".", "splitlines", "(", "True", ")", "n", "=", "0", "version", "=", "int", "(", ...
28.974359
27.641026
def imread(filename, *args, **kwargs): """Return image data from TIFF file as numpy array. The first image series is returned if no arguments are provided. Parameters ---------- key : int, slice, or sequence of page indices Defines which pages to return as array. series : int D...
[ "def", "imread", "(", "filename", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "TIFFfile", "(", "filename", ")", "as", "tif", ":", "return", "tif", ".", "asarray", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
26.526316
19.263158
def parse(self, fp, parser=None, context=None): """ Parse an HTML or XML document and return the extacted object following the Parsley rules give at instantiation. :param fp: file-like object containing an HTML or XML document, or URL or filename :param parser: *lxml.etree._Feed...
[ "def", "parse", "(", "self", ",", "fp", ",", "parser", "=", "None", ",", "context", "=", "None", ")", ":", "if", "parser", "is", "None", ":", "parser", "=", "lxml", ".", "etree", ".", "HTMLParser", "(", ")", "doc", "=", "lxml", ".", "etree", ".",...
51.26087
28.913043
def load_with_scipy(file, data_name): import scipy.io """ Loads data from a netcdf file. Parameters ---------- file : string or file-like The name of the netcdf file to open. data_name : string The name of the data to extract from the netcdf file. Returns ------- ...
[ "def", "load_with_scipy", "(", "file", ",", "data_name", ")", ":", "import", "scipy", ".", "io", "logger", ".", "debug", "(", "'Loading data {} of netcdf file {} with scipy.io.'", ".", "format", "(", "data_name", ",", "file", ")", ")", "f", "=", "scipy", ".", ...
25.785714
22.571429
async def load_tracks(self, query) -> LoadResult: """ Executes a loadtracks request. Only works on Lavalink V3. Parameters ---------- query : str Returns ------- LoadResult """ self.__check_node_ready() url = self._uri + quote(str...
[ "async", "def", "load_tracks", "(", "self", ",", "query", ")", "->", "LoadResult", ":", "self", ".", "__check_node_ready", "(", ")", "url", "=", "self", ".", "_uri", "+", "quote", "(", "str", "(", "query", ")", ")", "data", "=", "await", "self", ".",...
24.72
16.8
def add_paths_to_os(self, key=None, update=None): ''' Add the paths in tree environ into the os environ This code goes through the tree environ and checks for existence in the os environ, then adds them Parameters: key (str): The section name to check agains...
[ "def", "add_paths_to_os", "(", "self", ",", "key", "=", "None", ",", "update", "=", "None", ")", ":", "if", "key", "is", "not", "None", ":", "allpaths", "=", "key", "if", "isinstance", "(", "key", ",", "list", ")", "else", "[", "key", "]", "else", ...
35.636364
22.454545
async def connect(dsn=None, *, host=None, port=None, user=None, password=None, passfile=None, database=None, loop=None, timeout=60, statement_cache_size=100, max_cached_statement_lifetime=300, ...
[ "async", "def", "connect", "(", "dsn", "=", "None", ",", "*", ",", "host", "=", "None", ",", "port", "=", "None", ",", "user", "=", "None", ",", "password", "=", "None", ",", "passfile", "=", "None", ",", "database", "=", "None", ",", "loop", "="...
39.984615
22.569231
def deserialize(self, value, attr=None, data=None, **kwargs): """Deserialize ``value``. :param value: The value to be deserialized. :param str attr: The attribute/key in `data` to be deserialized. :param dict data: The raw input data passed to the `Schema.load`. :param dict kwar...
[ "def", "deserialize", "(", "self", ",", "value", ",", "attr", "=", "None", ",", "data", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Validate required fields, deserialize, then validate", "# deserialized value", "self", ".", "_validate_missing", "(", "value"...
43.952381
18.714286
def write_additional(self, productversion, channel): """Write the additional information to the MAR header. Args: productversion (str): product and version string channel (str): channel string """ self.fileobj.seek(self.additional_offset) extras = extras...
[ "def", "write_additional", "(", "self", ",", "productversion", ",", "channel", ")", ":", "self", ".", "fileobj", ".", "seek", "(", "self", ".", "additional_offset", ")", "extras", "=", "extras_header", ".", "build", "(", "dict", "(", "count", "=", "1", "...
31.714286
16.238095
def split_coords_2d(seq): """ :param seq: a flat list with lons and lats :returns: a validated list of pairs (lon, lat) >>> split_coords_2d([1.1, 2.1, 2.2, 2.3]) [(1.1, 2.1), (2.2, 2.3)] """ lons, lats = [], [] for i, el in enumerate(seq): if i % 2 == 0: lons.append(...
[ "def", "split_coords_2d", "(", "seq", ")", ":", "lons", ",", "lats", "=", "[", "]", ",", "[", "]", "for", "i", ",", "el", "in", "enumerate", "(", "seq", ")", ":", "if", "i", "%", "2", "==", "0", ":", "lons", ".", "append", "(", "valid", ".", ...
28.533333
10.8
def update_currency_by_id(cls, currency_id, currency, **kwargs): """Update Currency Update attributes of Currency This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_currency_by_id(currency...
[ "def", "update_currency_by_id", "(", "cls", ",", "currency_id", ",", "currency", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async'", ")", ":", "return", "cls", ".", "...
44.636364
22.318182
def to_gremlin(self): """Return a unicode object with the Gremlin representation of this expression.""" self.validate() edge_direction, edge_name = self.fold_scope_location.get_first_folded_edge() validate_safe_string(edge_name) inverse_direction_table = { 'out': 'in...
[ "def", "to_gremlin", "(", "self", ")", ":", "self", ".", "validate", "(", ")", "edge_direction", ",", "edge_name", "=", "self", ".", "fold_scope_location", ".", "get_first_folded_edge", "(", ")", "validate_safe_string", "(", "edge_name", ")", "inverse_direction_ta...
41.115385
21.871795
def _jks_keystream(iv, password): """Helper keystream generator for _jks_pkey_decrypt""" cur = iv while 1: xhash = hashlib.sha1(bytes(password + cur)) # hashlib.sha1 in python 2.6 does not accept a bytearray argument cur = bytearray(xhash.digest()) # make sure we iterate over ints in both Py...
[ "def", "_jks_keystream", "(", "iv", ",", "password", ")", ":", "cur", "=", "iv", "while", "1", ":", "xhash", "=", "hashlib", ".", "sha1", "(", "bytes", "(", "password", "+", "cur", ")", ")", "# hashlib.sha1 in python 2.6 does not accept a bytearray argument", ...
46.25
28.25
def change_name(self, new_name): """Change the name of the shell, possibly updating the maximum name length""" if not new_name: name = self.hostname else: name = new_name.decode() self.display_name = display_names.change( self.display_name, nam...
[ "def", "change_name", "(", "self", ",", "new_name", ")", ":", "if", "not", "new_name", ":", "name", "=", "self", ".", "hostname", "else", ":", "name", "=", "new_name", ".", "decode", "(", ")", "self", ".", "display_name", "=", "display_names", ".", "ch...
34.888889
8.444444
def install_trigger_function(connection: connection, overwrite: bool=False) -> None: """Install the psycopg2-pgevents trigger function against the database. Parameters ---------- connection: psycopg2.extensions.connection Active connection to a PostGreSQL database. overwrite: bool W...
[ "def", "install_trigger_function", "(", "connection", ":", "connection", ",", "overwrite", ":", "bool", "=", "False", ")", "->", "None", ":", "prior_install", "=", "False", "if", "not", "overwrite", ":", "prior_install", "=", "trigger_function_installed", "(", "...
31.185185
26.888889
def line_plot(data, atts=None, percent=100.0, seed=1, title=None, outfile=None, wait=True): """ Uses the internal format to plot the dataset, one line per instance. :param data: the dataset :type data: Instances :param atts: the list of 0-based attribute indices of attributes to plot :type atts...
[ "def", "line_plot", "(", "data", ",", "atts", "=", "None", ",", "percent", "=", "100.0", ",", "seed", "=", "1", ",", "title", "=", "None", ",", "outfile", "=", "None", ",", "wait", "=", "True", ")", ":", "if", "not", "plot", ".", "matplotlib_availa...
30.907407
20.944444
def freeze(self): """Make the SchemaElement's connections immutable.""" self.in_connections = frozenset(self.in_connections) self.out_connections = frozenset(self.out_connections)
[ "def", "freeze", "(", "self", ")", ":", "self", ".", "in_connections", "=", "frozenset", "(", "self", ".", "in_connections", ")", "self", ".", "out_connections", "=", "frozenset", "(", "self", ".", "out_connections", ")" ]
50
16.25
def main(): """Main entry point for `dddp` command.""" parser = argparse.ArgumentParser(description=__doc__) django = parser.add_argument_group('Django Options') django.add_argument( '--verbosity', '-v', metavar='VERBOSITY', dest='verbosity', type=int, default=1, ) django.add_arg...
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "__doc__", ")", "django", "=", "parser", ".", "add_argument_group", "(", "'Django Options'", ")", "django", ".", "add_argument", "(", "'--verbosity'", ",",...
44.533333
21.066667
def unc_wrapper_args(*covariance_keys): """ Wrap function, calculate its Jacobian and calculate the covariance of the outputs given the covariance of the specified inputs. :param covariance_keys: indices and names of arguments corresponding to covariance :return: wrapped function bou...
[ "def", "unc_wrapper_args", "(", "*", "covariance_keys", ")", ":", "def", "wrapper", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapped_function", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "cov", "=", "kwargs", ".", "pop", "...
48.5625
20.84375
def basic_pool(features, max_area_width, max_area_height=1, height=1, fn=tf.reduce_max, name=None): """Pools for each area based on a given pooling function (fn). Args: features: a Tensor in a shape of [batch_size, height * width, depth]. max_area_width: the max width allowed for an area. ...
[ "def", "basic_pool", "(", "features", ",", "max_area_width", ",", "max_area_height", "=", "1", ",", "height", "=", "1", ",", "fn", "=", "tf", ".", "reduce_max", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "name_scope", "(", "name", ",", "d...
44.470588
16.529412
def percent(args=None): ''' Return partition information for volumes mounted on this minion CLI Example: .. code-block:: bash salt '*' disk.percent /var ''' if __grains__['kernel'] == 'Linux': cmd = 'df -P' elif __grains__['kernel'] == 'OpenBSD' or __grains__['kernel'] == ...
[ "def", "percent", "(", "args", "=", "None", ")", ":", "if", "__grains__", "[", "'kernel'", "]", "==", "'Linux'", ":", "cmd", "=", "'df -P'", "elif", "__grains__", "[", "'kernel'", "]", "==", "'OpenBSD'", "or", "__grains__", "[", "'kernel'", "]", "==", ...
27.148936
20.893617
def rank(self, dim, pct=False, keep_attrs=None): """Ranks the data. Equal values are assigned a rank that is the average of the ranks that would have been otherwise assigned to all of the values within that set. Ranks begin at 1, not 0. If pct, computes percentage ranks. NaNs ...
[ "def", "rank", "(", "self", ",", "dim", ",", "pct", "=", "False", ",", "keep_attrs", "=", "None", ")", ":", "ds", "=", "self", ".", "_to_temp_dataset", "(", ")", ".", "rank", "(", "dim", ",", "pct", "=", "pct", ",", "keep_attrs", "=", "keep_attrs",...
33.769231
22.871795
def ready(self): """ Finalizes application configuration. """ import wagtailplus.wagtailrelations.signals.handlers self.add_relationship_panels() self.add_relationship_methods() super(WagtailRelationsAppConfig, self).ready()
[ "def", "ready", "(", "self", ")", ":", "import", "wagtailplus", ".", "wagtailrelations", ".", "signals", ".", "handlers", "self", ".", "add_relationship_panels", "(", ")", "self", ".", "add_relationship_methods", "(", ")", "super", "(", "WagtailRelationsAppConfig"...
31.222222
11.444444
def valid_file(cls, filename): """ Check if the provided file is a valid file for this plugin. :arg filename: the path to the file to check. """ return not os.path.isdir(filename) \ and os.path.basename(filename).startswith('Session ') \ and filename.endswith('....
[ "def", "valid_file", "(", "cls", ",", "filename", ")", ":", "return", "not", "os", ".", "path", ".", "isdir", "(", "filename", ")", "and", "os", ".", "path", ".", "basename", "(", "filename", ")", ".", "startswith", "(", "'Session '", ")", "and", "fi...
35.222222
15
def sanitize(self): ''' Check if the current settings conform to the LISP specifications and fix them where possible. ''' # We override the MapRegisterMessage sa super(InfoMessage, self).sanitize() # R: R bit indicates this is a reply to an Info-Request (Info- ...
[ "def", "sanitize", "(", "self", ")", ":", "# We override the MapRegisterMessage sa", "super", "(", "InfoMessage", ",", "self", ")", ".", "sanitize", "(", ")", "# R: R bit indicates this is a reply to an Info-Request (Info-", "# Reply). R bit is set to 0 in an Info-Request. When...
51.34375
26.09375
def configure_login(app): """Configure login authentification Uses `Flask-Login <https://flask-login.readthedocs.org>`_ """ from heman.auth import login_manager, login login_manager.init_app(app) @app.teardown_request def force_logout(*args, **kwargs): login.logout_user()
[ "def", "configure_login", "(", "app", ")", ":", "from", "heman", ".", "auth", "import", "login_manager", ",", "login", "login_manager", ".", "init_app", "(", "app", ")", "@", "app", ".", "teardown_request", "def", "force_logout", "(", "*", "args", ",", "*"...
27.272727
14.727273
def find_day_by_weekday_offset(year, month, weekday, offset): """Get the day number based on a date and offset :param year: date year :type year: int :param month: date month :type month: int :param weekday: date week day :type weekday: int :param offset: offset (-1 is last, 1 is first ...
[ "def", "find_day_by_weekday_offset", "(", "year", ",", "month", ",", "weekday", ",", "offset", ")", ":", "# thanks calendar :)", "cal", "=", "calendar", ".", "monthcalendar", "(", "year", ",", "month", ")", "# If we ask for a -1 day, just reverse cal", "if", "offset...
25.972973
17.243243
def deploy(self, initial_instance_count, instance_type, accelerator_type=None, endpoint_name=None, update_endpoint=False, tags=None, kms_key=None): """Deploy this ``Model`` to an ``Endpoint`` and optionally return a ``Predictor``. Create a SageMaker ``Model`` and ``EndpointConfig``, and ...
[ "def", "deploy", "(", "self", ",", "initial_instance_count", ",", "instance_type", ",", "accelerator_type", "=", "None", ",", "endpoint_name", "=", "None", ",", "update_endpoint", "=", "False", ",", "tags", "=", "None", ",", "kms_key", "=", "None", ")", ":",...
57.69863
34.342466
def get_eip_address_info(addresses=None, allocation_ids=None, region=None, key=None, keyid=None, profile=None): ''' Get 'interesting' info about some, or all EIPs associated with the current account. addresses (list) - Optional list of addresses. If provided, only the addr...
[ "def", "get_eip_address_info", "(", "addresses", "=", "None", ",", "allocation_ids", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "if", "type", "(", "addresses", ")"...
39.111111
30.388889
def post(self, repo): """ Post to the metadata server Parameters ---------- repo """ datapackage = repo.package url = self.url token = self.token headers = { 'Authorization': 'Token {}'.format(token), 'Content-Ty...
[ "def", "post", "(", "self", ",", "repo", ")", ":", "datapackage", "=", "repo", ".", "package", "url", "=", "self", ".", "url", "token", "=", "self", ".", "token", "headers", "=", "{", "'Authorization'", ":", "'Token {}'", ".", "format", "(", "token", ...
21.466667
19.733333
def mousePressEvent( self, event ): """ Make sure on a mouse release event that we have a current item. If no item is current, then our edit item will become current. :param event | <QMouseReleaseEvent> """ item = self.itemAt(event.pos()) ...
[ "def", "mousePressEvent", "(", "self", ",", "event", ")", ":", "item", "=", "self", ".", "itemAt", "(", "event", ".", "pos", "(", ")", ")", "# set the tag creation item as active\r", "if", "item", "is", "None", ":", "create_item", "=", "self", ".", "create...
37.21875
14.78125
def preprocess_na(sent, label_type): """Preprocess Na sentences Args: sent: A sentence label_type: The type of label provided """ if label_type == "phonemes_and_tones": phonemes = True tones = True tgm = True elif label_type == "phonemes_and_tones_no_tgm": ...
[ "def", "preprocess_na", "(", "sent", ",", "label_type", ")", ":", "if", "label_type", "==", "\"phonemes_and_tones\"", ":", "phonemes", "=", "True", "tones", "=", "True", "tgm", "=", "True", "elif", "label_type", "==", "\"phonemes_and_tones_no_tgm\"", ":", "phone...
34.77305
13.64539
def condense(self): '''If siblings have the same label, merge them. If they have edge lengths, the resulting ``Node`` will have the larger of the lengths''' self.resolve_polytomies(); labels_below = dict(); longest_leaf_dist = dict() for node in self.traverse_postorder(): if node.is_...
[ "def", "condense", "(", "self", ")", ":", "self", ".", "resolve_polytomies", "(", ")", "labels_below", "=", "dict", "(", ")", "longest_leaf_dist", "=", "dict", "(", ")", "for", "node", "in", "self", ".", "traverse_postorder", "(", ")", ":", "if", "node",...
50.4
19.333333
def get_elem(elem_ref, default=None): """ Gets the element referenced by elem_ref or returns the elem_ref directly if its not a reference. :param elem_ref: :param default: :return: """ if not is_elem_ref(elem_ref): return elem_ref elif elem_ref[0] == ElemRefObj: return g...
[ "def", "get_elem", "(", "elem_ref", ",", "default", "=", "None", ")", ":", "if", "not", "is_elem_ref", "(", "elem_ref", ")", ":", "return", "elem_ref", "elif", "elem_ref", "[", "0", "]", "==", "ElemRefObj", ":", "return", "getattr", "(", "elem_ref", "[",...
30.285714
16
def on(self, event, listener, *user_args): """Register a ``listener`` to be called on ``event``. The listener will be called with any extra arguments passed to :meth:`emit` first, and then the extra arguments passed to :meth:`on` last. If the listener function returns :class:`F...
[ "def", "on", "(", "self", ",", "event", ",", "listener", ",", "*", "user_args", ")", ":", "self", ".", "_listeners", "[", "event", "]", ".", "append", "(", "_Listener", "(", "callback", "=", "listener", ",", "user_args", "=", "user_args", ")", ")" ]
42.833333
21.666667
def get_ruler_distances(image, p1, p2): """Get the distance calculated between two points. A Bunch of results is returned, containing pixel values and distance values if the image contains a valid WCS. """ x1, y1 = p1[:2] x2, y2 = p2[:2] dx, dy = x2 - x1, y2 - y1 res = Bunch.Bunch(x1=x...
[ "def", "get_ruler_distances", "(", "image", ",", "p1", ",", "p2", ")", ":", "x1", ",", "y1", "=", "p1", "[", ":", "2", "]", "x2", ",", "y2", "=", "p2", "[", ":", "2", "]", "dx", ",", "dy", "=", "x2", "-", "x1", ",", "y2", "-", "y1", "res"...
39.418605
18.27907
def to_array(self): """ Serializes this InlineKeyboardButton to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InlineKeyboardButton, self).to_array() array['text'] = u(self.text) # py2: type unicode, py3: type str...
[ "def", "to_array", "(", "self", ")", ":", "array", "=", "super", "(", "InlineKeyboardButton", ",", "self", ")", ".", "to_array", "(", ")", "array", "[", "'text'", "]", "=", "u", "(", "self", ".", "text", ")", "# py2: type unicode, py3: type str", "if", "...
40.571429
28.142857
def write_html(self, html_dir='/tmp', include_osd=False, osd_width=500, osd_height=500): """Write HTML test page using OpenSeadragon for the tiles generated. Assumes that the generate(..) method has already been called to set up identifier etc. Parameters: html_dir ...
[ "def", "write_html", "(", "self", ",", "html_dir", "=", "'/tmp'", ",", "include_osd", "=", "False", ",", "osd_width", "=", "500", ",", "osd_height", "=", "500", ")", ":", "osd_config", "=", "self", ".", "get_osd_config", "(", "self", ".", "osd_version", ...
49.268657
16.149254
def line(h1: Histogram1D, **kwargs) -> dict: """Line plot of 1D histogram values. Points are horizontally placed in bin centers. Parameters ---------- h1 : physt.histogram1d.Histogram1D Dimensionality of histogram for which it is applicable """ lw = kwargs.pop("lw", DEFAULT_STROKE...
[ "def", "line", "(", "h1", ":", "Histogram1D", ",", "*", "*", "kwargs", ")", "->", "dict", ":", "lw", "=", "kwargs", ".", "pop", "(", "\"lw\"", ",", "DEFAULT_STROKE_WIDTH", ")", "mark_template", "=", "[", "{", "\"type\"", ":", "\"line\"", ",", "\"encode...
28.518519
20.037037
def output_raw(self, text): """ Output results in raw JSON format """ payload = json.loads(text) out = json.dumps(payload, sort_keys=True, indent=self._indent, separators=(',', ': ')) print(self.colorize_json(out))
[ "def", "output_raw", "(", "self", ",", "text", ")", ":", "payload", "=", "json", ".", "loads", "(", "text", ")", "out", "=", "json", ".", "dumps", "(", "payload", ",", "sort_keys", "=", "True", ",", "indent", "=", "self", ".", "_indent", ",", "sepa...
36.571429
10.857143
def create_all(app, user=None, password=None, bucket_name=None, location=None, include_hidden=False, filepath_filter_regex=None, put_bucket_acl=True): """ Uploads of the static assets associated with a Flask application to Amazon S3. All static assets are identified on the...
[ "def", "create_all", "(", "app", ",", "user", "=", "None", ",", "password", "=", "None", ",", "bucket_name", "=", "None", ",", "location", "=", "None", ",", "include_hidden", "=", "False", ",", "filepath_filter_regex", "=", "None", ",", "put_bucket_acl", "...
42.537815
22.941176
def get_context_data(self, **kwargs): """Add context data to view""" context = super().get_context_data(**kwargs) context.update({ 'title': self.title, 'submit_value': self.submit_value, 'cancel_url': self.cancel_url }) return context
[ "def", "get_context_data", "(", "self", ",", "*", "*", "kwargs", ")", ":", "context", "=", "super", "(", ")", ".", "get_context_data", "(", "*", "*", "kwargs", ")", "context", ".", "update", "(", "{", "'title'", ":", "self", ".", "title", ",", "'subm...
33.555556
10.444444
def section(title, bar=OVERLINE, strm=sys.stdout): """Helper function for testing demo routines """ width = utils.term.width printy(bold(title.center(width))) printy(bold((bar * width)[:width]))
[ "def", "section", "(", "title", ",", "bar", "=", "OVERLINE", ",", "strm", "=", "sys", ".", "stdout", ")", ":", "width", "=", "utils", ".", "term", ".", "width", "printy", "(", "bold", "(", "title", ".", "center", "(", "width", ")", ")", ")", "pri...
34.833333
4.333333
def _NormalizePath(path): """Removes surrounding whitespace, leading separator and normalize.""" # TODO(emrekultursay): Calling os.path.normpath "may change the meaning of a # path that contains symbolic links" (e.g., "A/foo/../B" != "A/B" if foo is a # symlink). This might cause trouble when matching against l...
[ "def", "_NormalizePath", "(", "path", ")", ":", "# TODO(emrekultursay): Calling os.path.normpath \"may change the meaning of a", "# path that contains symbolic links\" (e.g., \"A/foo/../B\" != \"A/B\" if foo is a", "# symlink). This might cause trouble when matching against loaded module", "# path...
42.125
20.875
def get_packages(self, feed_id, protocol_type=None, package_name_query=None, normalized_package_name=None, include_urls=None, include_all_versions=None, is_listed=None, get_top_package_versions=None, is_release=None, include_description=None, top=None, skip=None, include_deleted=None, is_cached=None, direct_upstream_id...
[ "def", "get_packages", "(", "self", ",", "feed_id", ",", "protocol_type", "=", "None", ",", "package_name_query", "=", "None", ",", "normalized_package_name", "=", "None", ",", "include_urls", "=", "None", ",", "include_all_versions", "=", "None", ",", "is_liste...
89.5
53.844828
def _get_conversion_type(self, convert_to=None): '''a helper function to return the conversion type based on user preference and input recipe. Parameters ========== convert_to: a string either docker or singularity (default None) ''' acceptable = ['...
[ "def", "_get_conversion_type", "(", "self", ",", "convert_to", "=", "None", ")", ":", "acceptable", "=", "[", "'singularity'", ",", "'docker'", "]", "# Default is to convert to opposite kind", "conversion", "=", "\"singularity\"", "if", "self", ".", "name", "==", ...
33
19.3
def split_input(img): """ img: an RGB image of shape (s, 2s, 3). :return: [input, output] """ # split the image into left + right pairs s = img.shape[0] assert img.shape[1] == 2 * s input, output = img[:, :s, :], img[:, s:, :] if args.mode == 'BtoA': input, output = output, i...
[ "def", "split_input", "(", "img", ")", ":", "# split the image into left + right pairs", "s", "=", "img", ".", "shape", "[", "0", "]", "assert", "img", ".", "shape", "[", "1", "]", "==", "2", "*", "s", "input", ",", "output", "=", "img", "[", ":", ",...
32.8125
13.4375
def ytdl_progress_hook(self, d): """Called when youtube-dl updates progress""" if d['status'] == 'downloading': self.play_empty() if "elapsed" in d: if d["elapsed"] > self.current_download_elapsed + 4: self.current_download_elapsed = d["elapse...
[ "def", "ytdl_progress_hook", "(", "self", ",", "d", ")", ":", "if", "d", "[", "'status'", "]", "==", "'downloading'", ":", "self", ".", "play_empty", "(", ")", "if", "\"elapsed\"", "in", "d", ":", "if", "d", "[", "\"elapsed\"", "]", ">", "self", ".",...
48.321429
22.089286
def _create_or_reuse_item(local_file, parent_folder_id, reuse_existing=False): """ Create an item from the local file in the Midas Server folder corresponding to the parent folder id. :param local_file: full path to a file on the local file system :type local_file: string :param parent_folder_i...
[ "def", "_create_or_reuse_item", "(", "local_file", ",", "parent_folder_id", ",", "reuse_existing", "=", "False", ")", ":", "local_item_name", "=", "os", ".", "path", ".", "basename", "(", "local_file", ")", "item_id", "=", "None", "if", "reuse_existing", ":", ...
37.705882
18.588235
def _validate_args(self, args): ''' validate the user arguments ''' assert(args.bucket) if args.subscribers: for _subscriber in args.subscribers: assert(isinstance(_subscriber, AsperaBaseSubscriber)) if (args.transfer_config): assert(isinstance(a...
[ "def", "_validate_args", "(", "self", ",", "args", ")", ":", "assert", "(", "args", ".", "bucket", ")", "if", "args", ".", "subscribers", ":", "for", "_subscriber", "in", "args", ".", "subscribers", ":", "assert", "(", "isinstance", "(", "_subscriber", "...
40.944444
23.166667
def execute(self, eopatch): """ Execute method takes EOPatch and changes the specified feature """ feature_type, feature_name = next(self.feature(eopatch)) eopatch[feature_type][feature_name] = self.process(eopatch[feature_type][feature_name]) return eopatch
[ "def", "execute", "(", "self", ",", "eopatch", ")", ":", "feature_type", ",", "feature_name", "=", "next", "(", "self", ".", "feature", "(", "eopatch", ")", ")", "eopatch", "[", "feature_type", "]", "[", "feature_name", "]", "=", "self", ".", "process", ...
37.5
23.625
def ValidateLanguageCode(lang, column_name=None, problems=None): """ Validates a non-required language code value using IsValidLanguageCode(): - if invalid adds InvalidValue error (if problems accumulator is provided) - an empty language code is regarded as valid! Otherwise we might end up with many d...
[ "def", "ValidateLanguageCode", "(", "lang", ",", "column_name", "=", "None", ",", "problems", "=", "None", ")", ":", "if", "IsEmpty", "(", "lang", ")", "or", "IsValidLanguageCode", "(", "lang", ")", ":", "return", "True", "else", ":", "if", "problems", "...
40.076923
21.769231
def cmd_nc(host, port, family, ssl_enable, crlf, source_ip, source_port, protocol): """Some kind of netcat/ncat replacement. The execution emulates the feeling of this popular tools. Example: \b $ habu.nc --crlf www.portantier.com 80 Connected to 45.77.113.133 80 HEAD / HTTP/1.0 \b ...
[ "def", "cmd_nc", "(", "host", ",", "port", ",", "family", ",", "ssl_enable", ",", "crlf", ",", "source_ip", ",", "source_port", ",", "protocol", ")", ":", "resolved", "=", "socket", ".", "getaddrinfo", "(", "host", ",", "port", ")", "families", "=", "{...
26.730337
23.640449
def get_tasks(self): """Returns an ordered dictionary {task_name: task} of all tasks within this workflow. :return: Ordered dictionary with key being task_name (str) and an instance of a corresponding task from this workflow :rtype: OrderedDict """ tasks = collect...
[ "def", "get_tasks", "(", "self", ")", ":", "tasks", "=", "collections", ".", "OrderedDict", "(", ")", "for", "dep", "in", "self", ".", "ordered_dependencies", ":", "tasks", "[", "dep", ".", "name", "]", "=", "dep", ".", "task", "return", "tasks" ]
36.5
19.833333
def do_over(): '''Calls :py:func:`os.exec` with executable and args derived from sys.''' path = sys.executable args = [path] + sys.argv # And the rest, after a sudden wet thud, was silence. os.execv(path, args)
[ "def", "do_over", "(", ")", ":", "path", "=", "sys", ".", "executable", "args", "=", "[", "path", "]", "+", "sys", ".", "argv", "# And the rest, after a sudden wet thud, was silence.", "os", ".", "execv", "(", "path", ",", "args", ")" ]
32.142857
23.285714
def calculate_row_format(columns, keys=None): """ Calculate row format. Args: columns (dict): the keys are the column name and the value the max length. keys (list): optional list of keys to order columns as well as to filter for them. Returns: str: format for table row """...
[ "def", "calculate_row_format", "(", "columns", ",", "keys", "=", "None", ")", ":", "row_format", "=", "''", "if", "keys", "is", "None", ":", "keys", "=", "columns", ".", "keys", "(", ")", "else", ":", "keys", "=", "[", "key", "for", "key", "in", "k...
26.521739
21.652174
def confirm_execution(self): """Confirm from your if proposed-plan be executed.""" permit = '' while permit.lower() not in ('yes', 'no'): permit = input('Execute Proposed Plan? [yes/no] ') if permit.lower() == 'yes': return True else: return Fa...
[ "def", "confirm_execution", "(", "self", ")", ":", "permit", "=", "''", "while", "permit", ".", "lower", "(", ")", "not", "in", "(", "'yes'", ",", "'no'", ")", ":", "permit", "=", "input", "(", "'Execute Proposed Plan? [yes/no] '", ")", "if", "permit", "...
35
14.444444
def avail_locations(call=None): ''' List all available locations ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option' ) ret = {} conn = get_conn() ...
[ "def", "avail_locations", "(", "call", "=", "None", ")", ":", "if", "call", "==", "'action'", ":", "raise", "SaltCloudSystemExit", "(", "'The avail_locations function must be called with '", "'-f or --function, or with the --list-locations option'", ")", "ret", "=", "{", ...
29.65
20.95
def list_properties(type): """ :param type: a Python GObject instance or type that the signal is associated with :type type: :obj:`GObject.Object` :returns: a list of :obj:`GObject.ParamSpec` :rtype: [:obj:`GObject.ParamSpec`] Takes a GObject/GInterface subclass or a GType and returns a list o...
[ "def", "list_properties", "(", "type", ")", ":", "if", "isinstance", "(", "type", ",", "PGType", ")", ":", "type", "=", "type", ".", "pytype", "from", "pgi", ".", "obj", "import", "Object", ",", "InterfaceBase", "if", "not", "issubclass", "(", "type", ...
30.653846
19.423077
def start_listener(self): '''start listening for packets''' if self.sock is not None: self.sock.close() self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock.bind(('',...
[ "def", "start_listener", "(", "self", ")", ":", "if", "self", ".", "sock", "is", "not", "None", ":", "self", ".", "sock", ".", "close", "(", ")", "self", ".", "sock", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", ...
49.222222
17.444444
def _set_column_names(dep, exp): """ rename the columns in the dependent peptides table from the raw file to the corresponding {experiment}_{fraction}. :param dep: dependent peptides table. :param exp: experimental design table. """ colnames = exp['Experiment'].astype(str) + '_' + exp['Fraction'...
[ "def", "_set_column_names", "(", "dep", ",", "exp", ")", ":", "colnames", "=", "exp", "[", "'Experiment'", "]", ".", "astype", "(", "str", ")", "+", "'_'", "+", "exp", "[", "'Fraction'", "]", ".", "astype", "(", "str", ")", "file2col", "=", "dict", ...
42.636364
10.272727
def data_two_freqs(N=200): """A simple test example with two close frequencies """ nn = arange(N) xx = cos(0.257*pi*nn) + sin(0.2*pi*nn) + 0.01*randn(nn.size) return xx
[ "def", "data_two_freqs", "(", "N", "=", "200", ")", ":", "nn", "=", "arange", "(", "N", ")", "xx", "=", "cos", "(", "0.257", "*", "pi", "*", "nn", ")", "+", "sin", "(", "0.2", "*", "pi", "*", "nn", ")", "+", "0.01", "*", "randn", "(", "nn",...
26.142857
18.142857
def reconnect(self, old_node, new_node): """ Disconnect old_node and connect new_node copying over any properties on the original relationship. Useful for preventing cardinality violations :param old_node: :param new_node: :return: None """ self._check_...
[ "def", "reconnect", "(", "self", ",", "old_node", ",", "new_node", ")", ":", "self", ".", "_check_node", "(", "old_node", ")", "self", ".", "_check_node", "(", "new_node", ")", "if", "old_node", ".", "id", "==", "new_node", ".", "id", ":", "return", "o...
37.175
20.575
def load_local_config(filename): """Loads the pylint.config.py file. Args: filename (str): The python file containing the local configuration. Returns: module: The loaded Python module. """ if not filename: return imp.new_module('local_pylint_config') module = imp.load_...
[ "def", "load_local_config", "(", "filename", ")", ":", "if", "not", "filename", ":", "return", "imp", ".", "new_module", "(", "'local_pylint_config'", ")", "module", "=", "imp", ".", "load_source", "(", "'local_pylint_config'", ",", "filename", ")", "return", ...
28.076923
19.923077
def get_media_uri(self, item_id): """Get a streaming URI for an item. Note: You should not need to use this directly. It is used by the Sonos players (not the controllers) to obtain the uri of the media stream. If you want to have a player play a media item, ...
[ "def", "get_media_uri", "(", "self", ",", "item_id", ")", ":", "response", "=", "self", ".", "soap_client", ".", "call", "(", "'getMediaURI'", ",", "[", "(", "'id'", ",", "item_id", ")", "]", ")", "return", "response", ".", "get", "(", "'getMediaURIResul...
40.045455
22.045455
def int_input(message, low, high, show_range = True): ''' Ask a user for a int input between two values args: message (str): Prompt for user low (int): Low value, user entered value must be > this value to be accepted high (int): High value, user entered value must be < this value t...
[ "def", "int_input", "(", "message", ",", "low", ",", "high", ",", "show_range", "=", "True", ")", ":", "int_in", "=", "low", "-", "1", "while", "(", "int_in", "<", "low", ")", "or", "(", "int_in", ">", "high", ")", ":", "if", "show_range", ":", "...
34.153846
24.538462
def findRepl( self, text, repl, caseSensitive = False, replaceAll = False ): """ Looks for the inputed text and replaces it with the given replacement \ text. :param text | <str>...
[ "def", "findRepl", "(", "self", ",", "text", ",", "repl", ",", "caseSensitive", "=", "False", ",", "replaceAll", "=", "False", ")", ":", "# make sure something is selected", "if", "(", "not", "text", ")", ":", "return", "0", "# make sure we have some text select...
31.492063
13.857143
def event_schedule_difference(old_schedule, new_schedule): """Compute the difference between two schedules from an event perspective Parameters ---------- old_schedule : list or tuple of :py:class:`resources.ScheduledItem` objects new_schedule : list or tuple of :py:class:`resource...
[ "def", "event_schedule_difference", "(", "old_schedule", ",", "new_schedule", ")", ":", "old", "=", "{", "item", ".", "event", ".", "name", ":", "item", "for", "item", "in", "old_schedule", "}", "new", "=", "{", "item", ".", "event", ".", "name", ":", ...
35.844828
21.189655
def normalVectorRDD(sc, numRows, numCols, numPartitions=None, seed=None): """ Generates an RDD comprised of vectors containing i.i.d. samples drawn from the standard normal distribution. :param sc: SparkContext used to create the RDD. :param numRows: Number of Vectors in the RDD...
[ "def", "normalVectorRDD", "(", "sc", ",", "numRows", ",", "numCols", ",", "numPartitions", "=", "None", ",", "seed", "=", "None", ")", ":", "return", "callMLlibFunc", "(", "\"normalVectorRDD\"", ",", "sc", ".", "_jsc", ",", "numRows", ",", "numCols", ",", ...
44.772727
24.681818