text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def _destinations_in_two_columns(pdf, destinations, cutoff=3): """ Check if the named destinations are organized along two columns (heuristic) @param pdf: a PdfFileReader object @param destinations: 'cutoff' is used to tune the heuristic: if 'cutoff' destinations in the would-be second column ...
[ "def", "_destinations_in_two_columns", "(", "pdf", ",", "destinations", ",", "cutoff", "=", "3", ")", ":", "# iterator for the x coordinates of refs in the would-be second column", "xpositions", "=", "(", "_destination_position", "(", "pdf", ",", "dest", ")", "[", "3", ...
38.55
0.001266
def touch(self, mode=0o666, exist_ok=True): """Create a fake file for the path with the given access mode, if it doesn't exist. Args: mode: the file mode for the file if it does not exist exist_ok: if the file already exists and this is True, nothing happ...
[ "def", "touch", "(", "self", ",", "mode", "=", "0o666", ",", "exist_ok", "=", "True", ")", ":", "if", "self", ".", "_closed", ":", "self", ".", "_raise_closed", "(", ")", "if", "self", ".", "exists", "(", ")", ":", "if", "exist_ok", ":", "self", ...
36.72
0.002123
def get_function_source(ft, **kwargs)->str: "Returns link to `ft` in source code." try: line = inspect.getsourcelines(ft)[1] except Exception: return '' mod_path = get_module_name(ft).replace('.', '/') + '.py' return get_source_link(mod_path, line, **kwargs)
[ "def", "get_function_source", "(", "ft", ",", "*", "*", "kwargs", ")", "->", "str", ":", "try", ":", "line", "=", "inspect", ".", "getsourcelines", "(", "ft", ")", "[", "1", "]", "except", "Exception", ":", "return", "''", "mod_path", "=", "get_module_...
45.5
0.014388
def comment_from_tag(tag): """ Convenience function to create a full-fledged comment for a given tag, for example it is convenient to assign a Comment to a ReturnValueSymbol. """ if not tag: return None comment = Comment(name=tag.name, meta={'description': tag.d...
[ "def", "comment_from_tag", "(", "tag", ")", ":", "if", "not", "tag", ":", "return", "None", "comment", "=", "Comment", "(", "name", "=", "tag", ".", "name", ",", "meta", "=", "{", "'description'", ":", "tag", ".", "description", "}", ",", "annotations"...
32.583333
0.002488
def get_attributes(self): """ Returns the Node attributes. Usage:: >>> node_a = AbstractNode("MyNodeA", attributeA=Attribute(value="A"), attributeB=Attribute(value="B")) >>> node_a.get_attributes() [<Attribute object at 0x7fa471d3b5e0>, <Attribute object at ...
[ "def", "get_attributes", "(", "self", ")", ":", "return", "[", "attribute", "for", "attribute", "in", "self", ".", "itervalues", "(", ")", "if", "issubclass", "(", "attribute", ".", "__class__", ",", "Attribute", ")", "]" ]
32.733333
0.009901
def _make_phased_magseries_plot(axes, periodind, stimes, smags, serrs, varperiod, varepoch, phasewrap, phasesort, phasebin, minbinelems, ...
[ "def", "_make_phased_magseries_plot", "(", "axes", ",", "periodind", ",", "stimes", ",", "smags", ",", "serrs", ",", "varperiod", ",", "varepoch", ",", "phasewrap", ",", "phasesort", ",", "phasebin", ",", "minbinelems", ",", "plotxlim", ",", "lspmethod", ",", ...
34.413295
0.001388
def create_graph_html(js_template, css_template, html_template=None): """ Create HTML code block given the graph Javascript and CSS. """ if html_template is None: html_template = read_lib('html', 'graph') # Create div ID for the graph and give it to the JS and CSS templates so # they can refere...
[ "def", "create_graph_html", "(", "js_template", ",", "css_template", ",", "html_template", "=", "None", ")", ":", "if", "html_template", "is", "None", ":", "html_template", "=", "read_lib", "(", "'html'", ",", "'graph'", ")", "# Create div ID for the graph and give ...
35.764706
0.001603
def _get_url_hashes(path): """Get hashes of urls in file.""" urls = _read_text_file(path) def url_hash(u): h = hashlib.sha1() try: u = u.encode('utf-8') except UnicodeDecodeError: logging.error('Cannot hash url: %s', u) h.update(u) return h.hexdigest() return {url_hash(u): True f...
[ "def", "_get_url_hashes", "(", "path", ")", ":", "urls", "=", "_read_text_file", "(", "path", ")", "def", "url_hash", "(", "u", ")", ":", "h", "=", "hashlib", ".", "sha1", "(", ")", "try", ":", "u", "=", "u", ".", "encode", "(", "'utf-8'", ")", "...
26.833333
0.024024
def make_ref(self, branch): """ Make a branch on github :param branch: Name of the branch to create :return: Sha of the branch or self.ProxyError """ master_sha = self.get_ref(self.master_upstream) if not isinstance(master_sha, str): return self.ProxyError( ...
[ "def", "make_ref", "(", "self", ",", "branch", ")", ":", "master_sha", "=", "self", ".", "get_ref", "(", "self", ".", "master_upstream", ")", "if", "not", "isinstance", "(", "master_sha", ",", "str", ")", ":", "return", "self", ".", "ProxyError", "(", ...
33.888889
0.00239
def get_access_token(self, code): """Returns Access Token retrieved from the Health Graph API Token Endpoint following the login to RunKeeper. to RunKeeper. @param code: Code returned by Health Graph API at the Authorization or RunKeeper Login phase. ...
[ "def", "get_access_token", "(", "self", ",", "code", ")", ":", "payload", "=", "{", "'grant_type'", ":", "'authorization_code'", ",", "'code'", ":", "code", ",", "'client_id'", ":", "self", ".", "_client_id", ",", "'client_secret'", ":", "self", ".", "_clien...
43.111111
0.008827
def conjugate(self): """Complex conjugate of of the indexed sum""" return self.__class__.create(self.term.conjugate(), *self.ranges)
[ "def", "conjugate", "(", "self", ")", ":", "return", "self", ".", "__class__", ".", "create", "(", "self", ".", "term", ".", "conjugate", "(", ")", ",", "*", "self", ".", "ranges", ")" ]
48.666667
0.013514
def listing( source: list, ordered: bool = False, expand_full: bool = False ): """ An unordered or ordered list of the specified *source* iterable where each element is converted to a string representation for display. :param source: The iterable to display as a list. ...
[ "def", "listing", "(", "source", ":", "list", ",", "ordered", ":", "bool", "=", "False", ",", "expand_full", ":", "bool", "=", "False", ")", ":", "r", "=", "_get_report", "(", ")", "r", ".", "append_body", "(", "render", ".", "listing", "(", "source"...
35.148148
0.001026
def _salt_cloud_force_ascii(exc): ''' Helper method to try its best to convert any Unicode text into ASCII without stack tracing since salt internally does not handle Unicode strings This method is not supposed to be used directly. Once `py:module: salt.utils.cloud` is imported this method register...
[ "def", "_salt_cloud_force_ascii", "(", "exc", ")", ":", "if", "not", "isinstance", "(", "exc", ",", "(", "UnicodeEncodeError", ",", "UnicodeTranslateError", ")", ")", ":", "raise", "TypeError", "(", "'Can\\'t handle {0}'", ".", "format", "(", "exc", ")", ")", ...
35.48
0.001098
def start(self): """ :meth:`WStoppableTask.start` implementation that creates new thread """ start_event = self.start_event() stop_event = self.stop_event() ready_event = self.ready_event() def thread_target(): try: start_event.set() self.thread_started() if ready_event is not None: re...
[ "def", "start", "(", "self", ")", ":", "start_event", "=", "self", ".", "start_event", "(", ")", "stop_event", "=", "self", ".", "stop_event", "(", ")", "ready_event", "=", "self", ".", "ready_event", "(", ")", "def", "thread_target", "(", ")", ":", "t...
23
0.034532
def getUsage(api_key=None, api_version=None): ''' Show current usages statistics :param api_key: The Random.org api key. :param api_version: The Random.org api version. :return: The current usage statistics. CLI Example: .. code-block:: bash salt '*' random_org.getUsage ...
[ "def", "getUsage", "(", "api_key", "=", "None", ",", "api_version", "=", "None", ")", ":", "ret", "=", "{", "'res'", ":", "True", "}", "if", "not", "api_key", "or", "not", "api_version", ":", "try", ":", "options", "=", "__salt__", "[", "'config.option...
30.711538
0.00182
def write_job(self,fh): """ Write the DAG entry for this node's job to the DAG file descriptor. @param fh: descriptor of open DAG file. """ if isinstance(self.job(),CondorDAGManJob): # create an external subdag from this dag fh.write( ' '.join( ['SUBDAG EXTERNAL', self.__name, se...
[ "def", "write_job", "(", "self", ",", "fh", ")", ":", "if", "isinstance", "(", "self", ".", "job", "(", ")", ",", "CondorDAGManJob", ")", ":", "# create an external subdag from this dag", "fh", ".", "write", "(", "' '", ".", "join", "(", "[", "'SUBDAG EXTE...
37.882353
0.025758
def csv_writer(parser, keep, extract, args): """Writes the data in CSV format.""" # The output output = sys.stdout if args.output == "-" else open(args.output, "w") try: # Getting the samples samples = np.array(parser.get_samples(), dtype=str) k = _get_sample_select(samples=samp...
[ "def", "csv_writer", "(", "parser", ",", "keep", ",", "extract", ",", "args", ")", ":", "# The output", "output", "=", "sys", ".", "stdout", "if", "args", ".", "output", "==", "\"-\"", "else", "open", "(", "args", ".", "output", ",", "\"w\"", ")", "t...
34.363636
0.000514
def create_lb(kwargs=None, call=None): ''' Create a load-balancer configuration. CLI Example: .. code-block:: bash salt-cloud -f create_lb gce name=lb region=us-central1 ports=80 ''' if call != 'function': raise SaltCloudSystemExit( 'The create_lb function must be ...
[ "def", "create_lb", "(", "kwargs", "=", "None", ",", "call", "=", "None", ")", ":", "if", "call", "!=", "'function'", ":", "raise", "SaltCloudSystemExit", "(", "'The create_lb function must be called with -f or --function.'", ")", "if", "not", "kwargs", "or", "'na...
26.82716
0.000444
def bark_filter(global_conf, **local_conf): """ Factory function for Bark. Returns a function which, when passed the application, returns an instance of BarkMiddleware. :param global_conf: The global configuration, from the [DEFAULT] section of the PasteDeploy configuration fil...
[ "def", "bark_filter", "(", "global_conf", ",", "*", "*", "local_conf", ")", ":", "# First, parse the configuration", "conf_file", "=", "None", "sections", "=", "{", "}", "for", "key", ",", "value", "in", "local_conf", ".", "items", "(", ")", ":", "# 'config'...
37.75641
0.000331
def listen_now_items(self): """Get a listing of Listen Now items. Note: This does not include situations; use the :meth:`situations` method instead. Returns: dict: With ``albums`` and ``stations`` keys of listen now items. """ response = self._call( mc_calls.ListenNowGetListenNowItems ) lis...
[ "def", "listen_now_items", "(", "self", ")", ":", "response", "=", "self", ".", "_call", "(", "mc_calls", ".", "ListenNowGetListenNowItems", ")", "listen_now_item_list", "=", "response", ".", "body", ".", "get", "(", "'listennow_items'", ",", "[", "]", ")", ...
25.545455
0.030875
def setUrl(self, url): """ Attempt to safely set the URL by string. """ if isUrl(url): self._url = url else: raise exceptions.BadUrlException(url) return self
[ "def", "setUrl", "(", "self", ",", "url", ")", ":", "if", "isUrl", "(", "url", ")", ":", "self", ".", "_url", "=", "url", "else", ":", "raise", "exceptions", ".", "BadUrlException", "(", "url", ")", "return", "self" ]
24.666667
0.008696
def not_found(url, wait=10): """ Returns True when the url generates a "404 Not Found" error. """ try: connection = open(url, wait) except HTTP404NotFound: return True except: return False return False
[ "def", "not_found", "(", "url", ",", "wait", "=", "10", ")", ":", "try", ":", "connection", "=", "open", "(", "url", ",", "wait", ")", "except", "HTTP404NotFound", ":", "return", "True", "except", ":", "return", "False", "return", "False" ]
19.416667
0.012295
def do_get_config(self, line): """get_config <peer> <source> eg. get_config sw1 startup """ def f(p, args): try: source = args[0] except: print("argument error") return print(p.get_config(source)) ...
[ "def", "do_get_config", "(", "self", ",", "line", ")", ":", "def", "f", "(", "p", ",", "args", ")", ":", "try", ":", "source", "=", "args", "[", "0", "]", "except", ":", "print", "(", "\"argument error\"", ")", "return", "print", "(", "p", ".", "...
23.714286
0.008696
def create_rules(aes, value): """Create a Rules instance for a single aesthetic value. Parameter --------- aes: str The name of the aesthetic value: str or list The value associated with any aesthetic """ if isinstance(value, six.string_types): return Rules(aes) ...
[ "def", "create_rules", "(", "aes", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ":", "return", "Rules", "(", "aes", ")", "else", ":", "rules", "=", "Rules", "(", ")", "for", "idx", ",", "(", "patte...
28.058824
0.002028
def _compare_strings(cls, source, target): """ Compares a source string to a target string, and addresses the condition in which the source string includes unquoted special characters. It performs a simple regular expression match, with the assumption that (as required) ...
[ "def", "_compare_strings", "(", "cls", ",", "source", ",", "target", ")", ":", "start", "=", "0", "end", "=", "len", "(", "source", ")", "begins", "=", "0", "ends", "=", "0", "# Reading of initial wildcard in source", "if", "source", ".", "startswith", "("...
33.013333
0.001176
def handle_g_error(error, return_value): """Convert a :c:type:`GError**` to a Python :exception:`ImageLoadingError`, and raise it. """ error = error[0] assert bool(return_value) == (error == ffi.NULL) if error != ffi.NULL: if error.message != ffi.NULL: message = ('Pixbuf err...
[ "def", "handle_g_error", "(", "error", ",", "return_value", ")", ":", "error", "=", "error", "[", "0", "]", "assert", "bool", "(", "return_value", ")", "==", "(", "error", "==", "ffi", ".", "NULL", ")", "if", "error", "!=", "ffi", ".", "NULL", ":", ...
35.6
0.001825
def AnalizarLiquidacion(self, liq): "Método interno para analizar la respuesta de AFIP" # proceso los datos básicos de la liquidación (devuelto por consultar): cab = liq.get('cabecera') if cab: self.CAE = str(cab.get('cae', '')) self.FechaVencimientoCae = str(cab....
[ "def", "AnalizarLiquidacion", "(", "self", ",", "liq", ")", ":", "# proceso los datos básicos de la liquidación (devuelto por consultar):", "cab", "=", "liq", ".", "get", "(", "'cabecera'", ")", "if", "cab", ":", "self", ".", "CAE", "=", "str", "(", "cab", ".", ...
46.567901
0.001038
def create_frvect(timeseries): """Create a `~frameCPP.FrVect` from a `TimeSeries` This method is primarily designed to make writing data to GWF files a bit easier. Parameters ---------- timeseries : `TimeSeries` the input `TimeSeries` Returns ------- frvect : `~frameCPP.Fr...
[ "def", "create_frvect", "(", "timeseries", ")", ":", "# create timing dimension", "dims", "=", "frameCPP", ".", "Dimension", "(", "timeseries", ".", "size", ",", "timeseries", ".", "dx", ".", "value", ",", "str", "(", "timeseries", ".", "dx", ".", "unit", ...
29.107143
0.001188
def local_service(self, name_or_id): """Get the locally synced information for a service. This method is safe to call outside of the background event loop without any race condition. Internally it uses a thread-safe mutex to protect the local copies of supervisor data and ensure that i...
[ "def", "local_service", "(", "self", ",", "name_or_id", ")", ":", "if", "not", "self", ".", "_loop", ".", "inside_loop", "(", ")", ":", "self", ".", "_state_lock", ".", "acquire", "(", ")", "try", ":", "if", "isinstance", "(", "name_or_id", ",", "int",...
37.352941
0.002302
def host_config(self): """ Ensure the host configuration file exists """ if platform.system() == 'Darwin': default_file_dir = join(expanduser('~'), 'vent_files') else: default_file_dir = '/opt/vent_files' status = self.ensure_di...
[ "def", "host_config", "(", "self", ")", ":", "if", "platform", ".", "system", "(", ")", "==", "'Darwin'", ":", "default_file_dir", "=", "join", "(", "expanduser", "(", "'~'", ")", ",", "'vent_files'", ")", "else", ":", "default_file_dir", "=", "'/opt/vent_...
42.333333
0.0022
def predict_log_proba(self, X): """ Return log-probability estimates for the RDD containing the test vector X. Parameters ---------- X : RDD containing array-like items, shape = [m_samples, n_features] Returns ------- C : RDD with array-like item...
[ "def", "predict_log_proba", "(", "self", ",", "X", ")", ":", "# required, scikit call self.predict_log_proba(X) in predict_proba", "# and thus this function is call, it must have the same behavior when", "# not called by sparkit-learn", "if", "not", "isinstance", "(", "X", ",", "Bl...
40.12
0.001947
def load(self, **kwargs): """Load both point source and diffuse components.""" coordsys = kwargs.get('coordsys', 'CEL') extdir = kwargs.get('extdir', self.extdir) srcname = kwargs.get('srcname', None) self.clear() self.load_diffuse_srcs() for c in self.config['...
[ "def", "load", "(", "self", ",", "*", "*", "kwargs", ")", ":", "coordsys", "=", "kwargs", ".", "get", "(", "'coordsys'", ",", "'CEL'", ")", "extdir", "=", "kwargs", ".", "get", "(", "'extdir'", ",", "self", ".", "extdir", ")", "srcname", "=", "kwar...
32.529412
0.001756
def compliment(rest): """ Generate a random compliment from http://www.madsci.org/cgi-bin/cgiwrap/~lynn/jardin/SCG """ compurl = 'http://www.madsci.org/cgi-bin/cgiwrap/~lynn/jardin/SCG' comphtml = ''.join([i.decode() for i in urllib.request.urlopen(compurl)]) compmark1 = '<h2>\n\n' compmark2 = '\n</h2>' compli...
[ "def", "compliment", "(", "rest", ")", ":", "compurl", "=", "'http://www.madsci.org/cgi-bin/cgiwrap/~lynn/jardin/SCG'", "comphtml", "=", "''", ".", "join", "(", "[", "i", ".", "decode", "(", ")", "for", "i", "in", "urllib", ".", "request", ".", "urlopen", "(...
39.25
0.02487
def import_task_modules(): """ Import all installed apps and add modules to registry """ top_level_modules = settings.INSTALLED_APPS module_names = [] for module in top_level_modules: #Import package mod = import_module(module) #Find all modules in package path fo...
[ "def", "import_task_modules", "(", ")", ":", "top_level_modules", "=", "settings", ".", "INSTALLED_APPS", "module_names", "=", "[", "]", "for", "module", "in", "top_level_modules", ":", "#Import package", "mod", "=", "import_module", "(", "module", ")", "#Find all...
42
0.011643
def sapm_spectral_loss(airmass_absolute, module): """ Calculates the SAPM spectral loss coefficient, F1. Parameters ---------- airmass_absolute : numeric Absolute airmass module : dict-like A dict, Series, or DataFrame defining the SAPM performance parameters. See the :...
[ "def", "sapm_spectral_loss", "(", "airmass_absolute", ",", "module", ")", ":", "am_coeff", "=", "[", "module", "[", "'A4'", "]", ",", "module", "[", "'A3'", "]", ",", "module", "[", "'A2'", "]", ",", "module", "[", "'A1'", "]", ",", "module", "[", "'...
25.27027
0.00103
def getExpirations(self, contract_identifier, expired=0): """ return expiration of contract / "multi" contract's contracts """ expirations = [] contracts = self.contractDetails(contract_identifier)["contracts"] if contracts[0].m_secType not in ("FUT", "FOP", "OPT"): return [...
[ "def", "getExpirations", "(", "self", ",", "contract_identifier", ",", "expired", "=", "0", ")", ":", "expirations", "=", "[", "]", "contracts", "=", "self", ".", "contractDetails", "(", "contract_identifier", ")", "[", "\"contracts\"", "]", "if", "contracts",...
36.545455
0.002424
def scan(): """ Scan for Crazyflie and return its URI. """ # Initiate the low level drivers cflib.crtp.init_drivers(enable_debug_driver=False) # Scan for Crazyflies print('Scanning interfaces for Crazyflies...') available = cflib.crtp.scan_interfaces() interfaces = [uri for uri, _ ...
[ "def", "scan", "(", ")", ":", "# Initiate the low level drivers", "cflib", ".", "crtp", ".", "init_drivers", "(", "enable_debug_driver", "=", "False", ")", "# Scan for Crazyflies", "print", "(", "'Scanning interfaces for Crazyflies...'", ")", "available", "=", "cflib", ...
27.1875
0.002222
def dt_comp(self, sampled_topics): """ Compute document-topic matrix from sampled_topics. """ samples = sampled_topics.shape[0] dt = np.zeros((self.D, self.K, samples)) for s in range(samples): dt[:, :, s] = \ samplers_ld...
[ "def", "dt_comp", "(", "self", ",", "sampled_topics", ")", ":", "samples", "=", "sampled_topics", ".", "shape", "[", "0", "]", "dt", "=", "np", ".", "zeros", "(", "(", "self", ".", "D", ",", "self", ".", "K", ",", "samples", ")", ")", "for", "s",...
29.666667
0.008715
def post(self, uri, params={}, data={}): '''A generic method to make POST requests to the OpenDNS Investigate API on the given URI. ''' return self._session.post( urljoin(Investigate.BASE_URL, uri), params=params, data=data, headers=self._auth_header, ...
[ "def", "post", "(", "self", ",", "uri", ",", "params", "=", "{", "}", ",", "data", "=", "{", "}", ")", ":", "return", "self", ".", "_session", ".", "post", "(", "urljoin", "(", "Investigate", ".", "BASE_URL", ",", "uri", ")", ",", "params", "=", ...
38
0.008571
def pow(val: Any, exponent: Any, default: Any = RaiseTypeErrorIfNotProvided) -> Any: """Returns `val**factor` of the given value, if defined. Values define an extrapolation by defining a __pow__(self, exponent) method. Note that the method may return NotImplemented to indicate a particular ...
[ "def", "pow", "(", "val", ":", "Any", ",", "exponent", ":", "Any", ",", "default", ":", "Any", "=", "RaiseTypeErrorIfNotProvided", ")", "->", "Any", ":", "raiser", "=", "getattr", "(", "val", ",", "'__pow__'", ",", "None", ")", "result", "=", "NotImple...
43.342105
0.001188
def check_lazy_load_subadres(f): ''' Decorator function to lazy load a :class:`Subadres`. ''' def wrapper(*args): subadres = args[0] if ( subadres._metadata is None or subadres.aard_id is None or subadres.huisnummer_id is None ): lo...
[ "def", "check_lazy_load_subadres", "(", "f", ")", ":", "def", "wrapper", "(", "*", "args", ")", ":", "subadres", "=", "args", "[", "0", "]", "if", "(", "subadres", ".", "_metadata", "is", "None", "or", "subadres", ".", "aard_id", "is", "None", "or", ...
33.368421
0.001534
def load_with_fn(load_fn, content_or_strm, container, allow_primitives=False, **options): """ Load data from given string or stream 'content_or_strm'. :param load_fn: Callable to load data :param content_or_strm: data content or stream provides it :param container: callble to make ...
[ "def", "load_with_fn", "(", "load_fn", ",", "content_or_strm", ",", "container", ",", "allow_primitives", "=", "False", ",", "*", "*", "options", ")", ":", "ret", "=", "load_fn", "(", "content_or_strm", ",", "*", "*", "options", ")", "if", "anyconfig", "."...
40.3
0.001212
def _categorize(self, category): """Remove torrents with unwanted category from self.torrents""" self.torrents = [result for result in self.torrents if result.category == category]
[ "def", "_categorize", "(", "self", ",", "category", ")", ":", "self", ".", "torrents", "=", "[", "result", "for", "result", "in", "self", ".", "torrents", "if", "result", ".", "category", "==", "category", "]" ]
47
0.036649
def _try_mask_row(row1, row2, all_close, ignore_order): ''' if each value in row1 matches a value in row2, mask row2 row1 1d array row2 1d masked array whose mask is all False ignore_order : bool Ignore column order all_close : bool compare with np.isclose instea...
[ "def", "_try_mask_row", "(", "row1", ",", "row2", ",", "all_close", ",", "ignore_order", ")", ":", "if", "ignore_order", ":", "for", "value1", "in", "row1", ":", "if", "not", "_try_mask_first_value", "(", "value1", ",", "row2", ",", "all_close", ")", ":", ...
28.185185
0.001271
def romanise(number): """Return the roman numeral for a number. Note that this only works for number in interval range [0, 12] since at the moment we only use it on realtime earthquake to conver MMI value. :param number: The number that will be romanised :type number: float :return Roman nume...
[ "def", "romanise", "(", "number", ")", ":", "if", "number", "is", "None", ":", "return", "''", "roman_list", "=", "[", "'0'", ",", "'I'", ",", "'II'", ",", "'III'", ",", "'IV'", ",", "'V'", ",", "'VI'", ",", "'VII'", ",", "'VIII'", ",", "'IX'", "...
28
0.00157
def message(self_,msg,*args,**kw): """ Print msg merged with args as a message. See Python's logging module for details of message formatting. """ self_.__db_print(INFO,msg,*args,**kw)
[ "def", "message", "(", "self_", ",", "msg", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "self_", ".", "__db_print", "(", "INFO", ",", "msg", ",", "*", "args", ",", "*", "*", "kw", ")" ]
31.285714
0.035556
def _IncludeFields(encoded_message, message, include_fields): """Add the requested fields to the encoded message.""" if include_fields is None: return encoded_message result = json.loads(encoded_message) for field_name in include_fields: try: value = _GetField(message, field_...
[ "def", "_IncludeFields", "(", "encoded_message", ",", "message", ",", "include_fields", ")", ":", "if", "include_fields", "is", "None", ":", "return", "encoded_message", "result", "=", "json", ".", "loads", "(", "encoded_message", ")", "for", "field_name", "in",...
40.705882
0.001412
def encrypt(self, key, data, mecha=MechanismRSAPKCS1): """ C_EncryptInit/C_Encrypt :param key: a key handle, obtained calling :func:`findObjects`. :type key: integer :param data: the data to be encrypted :type data: (binary) string or list/tuple of bytes :param ...
[ "def", "encrypt", "(", "self", ",", "key", ",", "data", ",", "mecha", "=", "MechanismRSAPKCS1", ")", ":", "encrypted", "=", "ckbytelist", "(", ")", "m", "=", "mecha", ".", "to_native", "(", ")", "data1", "=", "ckbytelist", "(", "data", ")", "rv", "="...
37.166667
0.001457
def magic_fields(self): """the magic fields for the schema""" return {f:v for f, v in self.fields.items() if f.startswith('_')}
[ "def", "magic_fields", "(", "self", ")", ":", "return", "{", "f", ":", "v", "for", "f", ",", "v", "in", "self", ".", "fields", ".", "items", "(", ")", "if", "f", ".", "startswith", "(", "'_'", ")", "}" ]
47
0.020979
def split_locale(locale: Text) -> Tuple[Text, Optional[Text]]: """ Decompose the locale into a normalized tuple. The first item is the locale (as lowercase letters) while the second item is either the country as lower case either None if no country was supplied. """ items = re.split(r'[_\-]', ...
[ "def", "split_locale", "(", "locale", ":", "Text", ")", "->", "Tuple", "[", "Text", ",", "Optional", "[", "Text", "]", "]", ":", "items", "=", "re", ".", "split", "(", "r'[_\\-]'", ",", "locale", ".", "lower", "(", ")", ",", "1", ")", "try", ":",...
30.142857
0.002299
def sign( self, hash, random_k ): """Return a signature for the provided hash, using the provided random nonce. It is absolutely vital that random_k be an unpredictable number in the range [1, self.public_key.point.order()-1]. If an attacker can guess random_k, he can compute our private key from a ...
[ "def", "sign", "(", "self", ",", "hash", ",", "random_k", ")", ":", "G", "=", "self", ".", "public_key", ".", "generator", "n", "=", "G", ".", "order", "(", ")", "k", "=", "random_k", "%", "n", "p1", "=", "k", "*", "G", "r", "=", "p1", ".", ...
43.32
0.014453
def catch_phrase(self): """ :example 'Robust full-range hub' """ result = [] for word_list in self.catch_phrase_words: result.append(self.random_element(word_list)) return " ".join(result)
[ "def", "catch_phrase", "(", "self", ")", ":", "result", "=", "[", "]", "for", "word_list", "in", "self", ".", "catch_phrase_words", ":", "result", ".", "append", "(", "self", ".", "random_element", "(", "word_list", ")", ")", "return", "\" \"", ".", "joi...
26.777778
0.008032
def lstree(self, astr_path=""): """ Print/return the tree from the current node. """ self.sCore.reset() str_cwd = self.cwd() if len(astr_path): self.cdnode(astr_path) str_ls = '%s' % self.snode_current print(str...
[ "def", "lstree", "(", "self", ",", "astr_path", "=", "\"\"", ")", ":", "self", ".", "sCore", ".", "reset", "(", ")", "str_cwd", "=", "self", ".", "cwd", "(", ")", "if", "len", "(", "astr_path", ")", ":", "self", ".", "cdnode", "(", "astr_path", "...
35.636364
0.014925
def paint(self, p, *args): ''' I have no idea why, but we need to generate the picture after painting otherwise it draws incorrectly. ''' if self.picturenotgened: self.generatePicture(self.getBoundingParents()[0].rect()) self.picturenotgened = False ...
[ "def", "paint", "(", "self", ",", "p", ",", "*", "args", ")", ":", "if", "self", ".", "picturenotgened", ":", "self", ".", "generatePicture", "(", "self", ".", "getBoundingParents", "(", ")", "[", "0", "]", ".", "rect", "(", ")", ")", "self", ".", ...
41.6
0.011765
def do_b0(self, line): """Send the Master a BinaryInput (group 2) value of False at index 6. Command syntax is: b0""" self.application.apply_update(opendnp3.Binary(False), index=6)
[ "def", "do_b0", "(", "self", ",", "line", ")", ":", "self", ".", "application", ".", "apply_update", "(", "opendnp3", ".", "Binary", "(", "False", ")", ",", "index", "=", "6", ")" ]
64.666667
0.015306
def info(request, message, extra_tags='', fail_silently=False, async=False): """Adds a message with the ``INFO`` level.""" if ASYNC and async: messages.info(_get_user(request), message) else: add_message(request, constants.INFO, message, extra_tags=extra_tags, fail_silent...
[ "def", "info", "(", "request", ",", "message", ",", "extra_tags", "=", "''", ",", "fail_silently", "=", "False", ",", "async", "=", "False", ")", ":", "if", "ASYNC", "and", "async", ":", "messages", ".", "info", "(", "_get_user", "(", "request", ")", ...
47.285714
0.008902
def draw(cdf, size=None): """ Generate a random sample according to the cumulative distribution given by `cdf`. Jit-complied by Numba in nopython mode. Parameters ---------- cdf : array_like(float, ndim=1) Array containing the cumulative distribution. size : scalar(int), optional(d...
[ "def", "draw", "(", "cdf", ",", "size", "=", "None", ")", ":", "if", "isinstance", "(", "size", ",", "types", ".", "Integer", ")", ":", "def", "draw_impl", "(", "cdf", ",", "size", ")", ":", "rs", "=", "np", ".", "random", ".", "random_sample", "...
28.35
0.000853
def get_auth_uri(self, state, scopes=None, implicit=False): """Constructs the full auth uri and returns it.. Parameters ---------- state : string The state to pass through the auth process scopes : list (optional) The list of scope to have ...
[ "def", "get_auth_uri", "(", "self", ",", "state", ",", "scopes", "=", "None", ",", "implicit", "=", "False", ")", ":", "if", "state", "is", "None", "or", "state", "==", "''", ":", "raise", "AttributeError", "(", "'\"state\" must be non empty, non None string'"...
34.3
0.001417
def merge_from_master(git_action, study_id, auth_info, parent_sha): """merge from master into the WIP for this study/author this is needed to allow a worker's future saves to be merged seamlessly into master """ return _merge_from_master(git_action, doc_id=study_id, ...
[ "def", "merge_from_master", "(", "git_action", ",", "study_id", ",", "auth_info", ",", "parent_sha", ")", ":", "return", "_merge_from_master", "(", "git_action", ",", "doc_id", "=", "study_id", ",", "auth_info", "=", "auth_info", ",", "parent_sha", "=", "parent_...
47.1
0.002083
def getCountKwargs(func): """ Returns a list ["count kwarg", "count_max kwarg"] for a given function. Valid combinations are defined in `progress.validCountKwargs`. Returns None if no keyword arguments are found. """ # Get all arguments of the function if hasattr(func, "__code__"): ...
[ "def", "getCountKwargs", "(", "func", ")", ":", "# Get all arguments of the function", "if", "hasattr", "(", "func", ",", "\"__code__\"", ")", ":", "func_args", "=", "func", ".", "__code__", ".", "co_varnames", "[", ":", "func", ".", "__code__", ".", "co_argco...
35.666667
0.009107
def cli(): """ Commandline for looter :d """ argv = docopt(__doc__, version=VERSION) if argv['genspider']: name = f"{argv['<name>']}.py" use_async = argv['--async'] template = 'data_async.tmpl' if use_async else 'data.tmpl' package_dir = Path(__file__).parent ...
[ "def", "cli", "(", ")", ":", "argv", "=", "docopt", "(", "__doc__", ",", "version", "=", "VERSION", ")", "if", "argv", "[", "'genspider'", "]", ":", "name", "=", "f\"{argv['<name>']}.py\"", "use_async", "=", "argv", "[", "'--async'", "]", "template", "="...
36.192308
0.001035
def print(source, template=None, **kwargs): """Print each element of an asynchronous sequence without modifying it. An optional template can be provided to be formatted with the elements. All the keyword arguments are forwarded to the builtin function print. """ def func(value): if template...
[ "def", "print", "(", "source", ",", "template", "=", "None", ",", "*", "*", "kwargs", ")", ":", "def", "func", "(", "value", ")", ":", "if", "template", ":", "value", "=", "template", ".", "format", "(", "value", ")", "builtins", ".", "print", "(",...
39.090909
0.002273
def update_viewer_state(rec, context): """ Given viewer session information, make sure the session information is compatible with the current version of the viewers, and if not, update the session information in-place. """ if '_protocol' not in rec: rec.pop('properties') rec['...
[ "def", "update_viewer_state", "(", "rec", ",", "context", ")", ":", "if", "'_protocol'", "not", "in", "rec", ":", "rec", ".", "pop", "(", "'properties'", ")", "rec", "[", "'state'", "]", "=", "{", "}", "rec", "[", "'state'", "]", "[", "'values'", "]"...
38.394737
0.002005
def accept(self, reply_socket, channel): """Sends ACCEPT reply.""" info = self.info or b'' self.send_raw(reply_socket, ACCEPT, info, *channel)
[ "def", "accept", "(", "self", ",", "reply_socket", ",", "channel", ")", ":", "info", "=", "self", ".", "info", "or", "b''", "self", ".", "send_raw", "(", "reply_socket", ",", "ACCEPT", ",", "info", ",", "*", "channel", ")" ]
40.75
0.012048
def _match_processes(self, pid, name, cur_process): """ Determine whether user-specified "pid/processes" contain this process :param pid: The user input of pid :param name: The user input of process name :param process: current process info :return: True or Not; (if both pid/process are given, t...
[ "def", "_match_processes", "(", "self", ",", "pid", ",", "name", ",", "cur_process", ")", ":", "cur_pid", ",", "cur_name", "=", "self", ".", "_get_tuple", "(", "cur_process", ".", "split", "(", "'/'", ")", ")", "pid_match", "=", "False", "if", "not", "...
28.869565
0.008746
def set_nvram(self, nvram): """ Sets amount of NVRAM allocated to this router :param nvram: amount of NVRAM in Kbytes (integer) """ if self._nvram == nvram: return yield from self._hypervisor.send('vm set_nvram "{name}" {nvram}'.format(name=self._name, nvra...
[ "def", "set_nvram", "(", "self", ",", "nvram", ")", ":", "if", "self", ".", "_nvram", "==", "nvram", ":", "return", "yield", "from", "self", ".", "_hypervisor", ".", "send", "(", "'vm set_nvram \"{name}\" {nvram}'", ".", "format", "(", "name", "=", "self",...
50.8125
0.008454
def get_contents(self): """The contents of an alias is the concatenation of the content signatures of all its sources.""" childsigs = [n.get_csig() for n in self.children()] return ''.join(childsigs)
[ "def", "get_contents", "(", "self", ")", ":", "childsigs", "=", "[", "n", ".", "get_csig", "(", ")", "for", "n", "in", "self", ".", "children", "(", ")", "]", "return", "''", ".", "join", "(", "childsigs", ")" ]
45.4
0.008658
def set_payload(self,val): """Set a payload for this object :param val: payload to be stored :type val: Anything that can be put in a list """ self._options = self._options._replace(payload = val)
[ "def", "set_payload", "(", "self", ",", "val", ")", ":", "self", ".", "_options", "=", "self", ".", "_options", ".", "_replace", "(", "payload", "=", "val", ")" ]
30.142857
0.018433
def destr(d,*l): '''destructure a dict (like take, but return a list)''' if type(l[0]) is not str: l=l[0]; return [d[i] for i in l];
[ "def", "destr", "(", "d", ",", "*", "l", ")", ":", "if", "type", "(", "l", "[", "0", "]", ")", "is", "not", "str", ":", "l", "=", "l", "[", "0", "]", "return", "[", "d", "[", "i", "]", "for", "i", "in", "l", "]" ]
29.6
0.046053
def __add_variables(self, *args, **kwargs): """ Adds given variables to __variables attribute. :param \*args: Variables. :type \*args: \* :param \*\*kwargs: Variables : Values. :type \*\*kwargs: \* """ for variable in args: self.__variables[v...
[ "def", "__add_variables", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "variable", "in", "args", ":", "self", ".", "__variables", "[", "variable", "]", "=", "None", "self", ".", "__variables", ".", "update", "(", "kwargs", ...
27.923077
0.026667
async def items(self): """Lists all the active tokens Returns: ObjectMeta: where value is a list of tokens It returns a body like this:: [ { "CreateIndex": 3, "ModifyIndex": 3, "ID": "8f246b77-f3e1-ff88-5b48...
[ "async", "def", "items", "(", "self", ")", ":", "response", "=", "await", "self", ".", "_api", ".", "get", "(", "\"/v1/acl/list\"", ")", "results", "=", "[", "decode_token", "(", "r", ")", "for", "r", "in", "response", ".", "body", "]", "return", "co...
29.555556
0.002427
def js2str(js, sort_keys=True, indent=4): """Encode js to nicely formatted human readable string. (utf-8 encoding) Usage:: >>> from weatherlab.lib.dataIO.js import js2str >>> s = js2str({"a": 1, "b": 2}) >>> print(s) { "a": 1, "b": 2 } **中文文...
[ "def", "js2str", "(", "js", ",", "sort_keys", "=", "True", ",", "indent", "=", "4", ")", ":", "return", "json", ".", "dumps", "(", "js", ",", "sort_keys", "=", "sort_keys", ",", "indent", "=", "indent", ",", "separators", "=", "(", "\",\"", ",", "\...
23.894737
0.002119
def dict_given_run_array(samples, thread_min_max): """ Converts an array of information about samples back into a nested sampling run dictionary (see data_processing module docstring for more details). N.B. the output dict only contains the following keys: 'logl', 'thread_label', 'nlive_array', 'th...
[ "def", "dict_given_run_array", "(", "samples", ",", "thread_min_max", ")", ":", "ns_run", "=", "{", "'logl'", ":", "samples", "[", ":", ",", "0", "]", ",", "'thread_labels'", ":", "samples", "[", ":", ",", "1", "]", ",", "'thread_min_max'", ":", "thread_...
47.857143
0.000325
def publish(self, jid, node, payload, *, id_=None, publish_options=None): """ Publish an item to a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to publish to. :type n...
[ "def", "publish", "(", "self", ",", "jid", ",", "node", ",", "payload", ",", "*", ",", "id_", "=", "None", ",", "publish_options", "=", "None", ")", ":", "publish", "=", "pubsub_xso", ".", "Publish", "(", ")", "publish", ".", "node", "=", "node", "...
41.853333
0.001245
def send_query(query_dict): """Query ChEMBL API Parameters ---------- query_dict : dict 'query' : string of the endpoint to query 'params' : dict of params for the query Returns ------- js : dict dict parsed from json that is unique to the submitted query """ ...
[ "def", "send_query", "(", "query_dict", ")", ":", "query", "=", "query_dict", "[", "'query'", "]", "params", "=", "query_dict", "[", "'params'", "]", "url", "=", "'https://www.ebi.ac.uk/chembl/api/data/'", "+", "query", "+", "'.json'", "r", "=", "requests", "....
25.238095
0.001818
def send_request(self, method, params): """Send a request """ msg, msgid = self._encoder.create_request(method, params) self._send_message(msg) self._pending_requests.add(msgid) return msgid
[ "def", "send_request", "(", "self", ",", "method", ",", "params", ")", ":", "msg", ",", "msgid", "=", "self", ".", "_encoder", ".", "create_request", "(", "method", ",", "params", ")", "self", ".", "_send_message", "(", "msg", ")", "self", ".", "_pendi...
33.142857
0.008403
def _py_expand_short(subsequence, sequence, max_l_dist): """Straightforward implementation of partial match expansion.""" # The following diagram shows the score calculation step. # # Each new score is the minimum of: # * a OR a + 1 (substitution, if needed) # * b + 1 (deletion, i.e. skipping ...
[ "def", "_py_expand_short", "(", "subsequence", ",", "sequence", ",", "max_l_dist", ")", ":", "# The following diagram shows the score calculation step.", "#", "# Each new score is the minimum of:", "# * a OR a + 1 (substitution, if needed)", "# * b + 1 (deletion, i.e. skipping a sequen...
30.245283
0.001208
def concretize(self, **kwargs): """ Return a concretization of the contents of the file, as a flat bytestring. """ size = self.state.solver.min(self._size, **kwargs) data = self.load(0, size) kwargs['cast_to'] = kwargs.get('cast_to', bytes) kwargs['extra_constrai...
[ "def", "concretize", "(", "self", ",", "*", "*", "kwargs", ")", ":", "size", "=", "self", ".", "state", ".", "solver", ".", "min", "(", "self", ".", "_size", ",", "*", "*", "kwargs", ")", "data", "=", "self", ".", "load", "(", "0", ",", "size",...
43.9
0.008929
def long_click(self, pos, duration=2.0): """ Similar to click but press the screen for the given time interval and then release Args: pos (:obj:`2-list/2-tuple`): coordinates (x, y) in range from 0 to 1 duration: duration of press the screen """ try: ...
[ "def", "long_click", "(", "self", ",", "pos", ",", "duration", "=", "2.0", ")", ":", "try", ":", "duration", "=", "float", "(", "duration", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'Argument `duration` should be <float>. Got {}'", ".", "f...
40.882353
0.008439
def check_param_list_validity(self, param_list): """ Parameters ---------- param_list : list. Contains four elements, each being a numpy array. Either all of the arrays should be 1D or all of the arrays should be 2D. If 2D, the arrays should have the s...
[ "def", "check_param_list_validity", "(", "self", ",", "param_list", ")", ":", "if", "param_list", "is", "None", ":", "return", "None", "# Make sure there are four elements in param_list", "check_type_and_size_of_param_list", "(", "param_list", ",", "4", ")", "# Make sure ...
42.971429
0.00065
def ReadAllClientGraphSeries( self, client_label, report_type, time_range = None, cursor=None): """Reads graph series for the given label and report-type from the DB.""" query = """ SELECT UNIX_TIMESTAMP(timestamp), graph_series FROM client_report_graphs WHERE cli...
[ "def", "ReadAllClientGraphSeries", "(", "self", ",", "client_label", ",", "report_type", ",", "time_range", "=", "None", ",", "cursor", "=", "None", ")", ":", "query", "=", "\"\"\"\n SELECT UNIX_TIMESTAMP(timestamp), graph_series\n FROM client_report_graphs\n W...
36.03125
0.010135
def Cpig(self, T): r'''Computes ideal-gas heat capacity at a specified temperature of an organic compound using the Joback method as a function of chemical structure only. .. math:: C_p^{ig} = \sum_i a_i - 37.93 + \left[ \sum_i b_i + 0.210 \right] T +...
[ "def", "Cpig", "(", "self", ",", "T", ")", ":", "if", "self", ".", "calculated_Cpig_coeffs", "is", "None", ":", "self", ".", "calculated_Cpig_coeffs", "=", "Joback", ".", "Cpig_coeffs", "(", "self", ".", "counts", ")", "return", "horner", "(", "reversed", ...
32.103448
0.009385
def resource_created_response(resource): """Return HTTP response with status code *201*, signaling a created *resource* :param resource: resource created as a result of current request :type resource: :class:`sandman.model.Model` :rtype: :class:`flask.Response` """ if _get_acceptable_respo...
[ "def", "resource_created_response", "(", "resource", ")", ":", "if", "_get_acceptable_response_type", "(", ")", "==", "JSON", ":", "response", "=", "_single_resource_json_response", "(", "resource", ")", "else", ":", "response", "=", "_single_resource_html_response", ...
35.705882
0.001605
def blit( self, dest: "Console", dest_x: int = 0, dest_y: int = 0, src_x: int = 0, src_y: int = 0, width: int = 0, height: int = 0, fg_alpha: float = 1.0, bg_alpha: float = 1.0, key_color: Optional[Tuple[int, int, int]] = None, ...
[ "def", "blit", "(", "self", ",", "dest", ":", "\"Console\"", ",", "dest_x", ":", "int", "=", "0", ",", "dest_y", ":", "int", "=", "0", ",", "src_x", ":", "int", "=", "0", ",", "src_y", ":", "int", "=", "0", ",", "width", ":", "int", "=", "0",...
32.821429
0.001056
def plot_joint_sfs(s, ax=None, imshow_kwargs=None): """Plot a joint site frequency spectrum. Parameters ---------- s : array_like, int, shape (n_chromosomes_pop1, n_chromosomes_pop2) Joint site frequency spectrum. ax : axes, optional Axes on which to draw. If not provided, a new fig...
[ "def", "plot_joint_sfs", "(", "s", ",", "ax", "=", "None", ",", "imshow_kwargs", "=", "None", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "from", "matplotlib", ".", "colors", "import", "LogNorm", "# check inputs", "s", "=", "asarray_ndim", ...
26.425532
0.000776
def load_table_from_uri( self, source_uris, destination, job_id=None, job_id_prefix=None, location=None, project=None, job_config=None, retry=DEFAULT_RETRY, ): """Starts a job for loading data into a table from CloudStorage. Se...
[ "def", "load_table_from_uri", "(", "self", ",", "source_uris", ",", "destination", ",", "job_id", "=", "None", ",", "job_id_prefix", "=", "None", ",", "location", "=", "None", ",", "project", "=", "None", ",", "job_config", "=", "None", ",", "retry", "=", ...
36.867647
0.001943
def update(self) -> None: """Call method |Parameter.update| of all "secondary" parameters. Directly after initialisation, neither the primary (`control`) parameters nor the secondary (`derived`) parameters of application model |hstream_v1| are ready for usage: >>> from hydpy.m...
[ "def", "update", "(", "self", ")", "->", "None", ":", "for", "subpars", "in", "self", ".", "secondary_subpars", ":", "for", "par", "in", "subpars", ":", "try", ":", "par", ".", "update", "(", ")", "except", "BaseException", ":", "objecttools", ".", "au...
33.76087
0.001252
def product_status(request, form): ''' Summarises the inventory status of the given items, grouping by invoice status. ''' products = form.cleaned_data["product"] categories = form.cleaned_data["category"] items = commerce.ProductItem.objects.filter( Q(product__in=products) | Q(product__ca...
[ "def", "product_status", "(", "request", ",", "form", ")", ":", "products", "=", "form", ".", "cleaned_data", "[", "\"product\"", "]", "categories", "=", "form", ".", "cleaned_data", "[", "\"category\"", "]", "items", "=", "commerce", ".", "ProductItem", "."...
29.205882
0.000975
def forward_char(self, e): # (C-f) u"""Move forward a character. """ self.l_buffer.forward_char(self.argument_reset) self.finalize()
[ "def", "forward_char", "(", "self", ",", "e", ")", ":", "# (C-f)\r", "self", ".", "l_buffer", ".", "forward_char", "(", "self", ".", "argument_reset", ")", "self", ".", "finalize", "(", ")" ]
39
0.018868
def moment(p, v, order=1): """ Calculates the moments of the probability distribution p with vector v """ if order == 1: return (v*p).sum() elif order == 2: return np.sqrt( ((v**2)*p).sum() - (v*p).sum()**2 )
[ "def", "moment", "(", "p", ",", "v", ",", "order", "=", "1", ")", ":", "if", "order", "==", "1", ":", "return", "(", "v", "*", "p", ")", ".", "sum", "(", ")", "elif", "order", "==", "2", ":", "return", "np", ".", "sqrt", "(", "(", "(", "v...
38.5
0.016949
def p_lconcatlist(self, p): 'lconcatlist : lconcatlist COMMA lconcat_one' p[0] = p[1] + (p[3],) p.set_lineno(0, p.lineno(1))
[ "def", "p_lconcatlist", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "+", "(", "p", "[", "3", "]", ",", ")", "p", ".", "set_lineno", "(", "0", ",", "p", ".", "lineno", "(", "1", ")", ")" ]
36.25
0.013514
def prior_rvs(self, size=1, prior=None): """Returns random variates drawn from the prior. If the ``sampling_params`` are different from the ``variable_params``, the variates are transformed to the `sampling_params` parameter space before being returned. Parameters -----...
[ "def", "prior_rvs", "(", "self", ",", "size", "=", "1", ",", "prior", "=", "None", ")", ":", "# draw values from the prior", "if", "prior", "is", "None", ":", "prior", "=", "self", ".", "prior_distribution", "p0", "=", "prior", ".", "rvs", "(", "size", ...
37.741935
0.001667
def build_model(self, algo_params): """(internal)""" if algo_params["training_frame"] is None: raise ValueError("Missing training_frame") x = algo_params.pop("x") y = algo_params.pop("y", None) training_frame = algo_params.pop("training_frame") validation_frame = algo_par...
[ "def", "build_model", "(", "self", ",", "algo_params", ")", ":", "if", "algo_params", "[", "\"training_frame\"", "]", "is", "None", ":", "raise", "ValueError", "(", "\"Missing training_frame\"", ")", "x", "=", "algo_params", ".", "pop", "(", "\"x\"", ")", "y...
70.25
0.009658
def string(self): """:return: the dump as a string""" if self.__text_is_expected: return self._string() else: return self._bytes().decode(self.__encoding)
[ "def", "string", "(", "self", ")", ":", "if", "self", ".", "__text_is_expected", ":", "return", "self", ".", "_string", "(", ")", "else", ":", "return", "self", ".", "_bytes", "(", ")", ".", "decode", "(", "self", ".", "__encoding", ")" ]
32.833333
0.009901
def _tr_quote(line_info): "Translate lines escaped with: ," return '%s%s("%s")' % (line_info.pre, line_info.ifun, '", "'.join(line_info.the_rest.split()) )
[ "def", "_tr_quote", "(", "line_info", ")", ":", "return", "'%s%s(\"%s\")'", "%", "(", "line_info", ".", "pre", ",", "line_info", ".", "ifun", ",", "'\", \"'", ".", "join", "(", "line_info", ".", "the_rest", ".", "split", "(", ")", ")", ")" ]
49.25
0.02
def _set_signature_type(self): """Ensures that the algorithm signature type is a known type and sets a reference value.""" try: verify_interface(ec.EllipticCurve, self.algorithm.signing_algorithm_info) return ec.EllipticCurve except InterfaceNotImplemented: ra...
[ "def", "_set_signature_type", "(", "self", ")", ":", "try", ":", "verify_interface", "(", "ec", ".", "EllipticCurve", ",", "self", ".", "algorithm", ".", "signing_algorithm_info", ")", "return", "ec", ".", "EllipticCurve", "except", "InterfaceNotImplemented", ":",...
53.285714
0.010554
def release_docs_side_effect(content): """Updates the template so that curly braces are escaped correctly. Args: content (str): The template for ``docs/index.rst.release.template``. Returns: str: The updated template with properly escaped curly braces. """ # First replace **all** c...
[ "def", "release_docs_side_effect", "(", "content", ")", ":", "# First replace **all** curly braces.", "result", "=", "content", ".", "replace", "(", "\"{\"", ",", "\"{{\"", ")", ".", "replace", "(", "\"}\"", ",", "\"}}\"", ")", "# Then reset the actual template argume...
43
0.001264
def attributes(self): """Get the attributes which are exported by this object model.""" return [ obj[len(IMPL_PREFIX) :] for obj in dir(self) if obj.startswith(IMPL_PREFIX) ]
[ "def", "attributes", "(", "self", ")", ":", "return", "[", "obj", "[", "len", "(", "IMPL_PREFIX", ")", ":", "]", "for", "obj", "in", "dir", "(", "self", ")", "if", "obj", ".", "startswith", "(", "IMPL_PREFIX", ")", "]" ]
41.2
0.019048
def update_last_activity(self, request, now): """ If ``request.GET['idleFor']`` is set, check if it refers to a more recent activity than ``request.session['_session_security']`` and update it in this case. """ last_activity = get_last_activity(request.session) se...
[ "def", "update_last_activity", "(", "self", ",", "request", ",", "now", ")", ":", "last_activity", "=", "get_last_activity", "(", "request", ".", "session", ")", "server_idle_for", "=", "(", "now", "-", "last_activity", ")", ".", "seconds", "# Gracefully ignore ...
36.96
0.00211
def on_websocket_message(message: str) -> None: """Handle messages from browser.""" msgs = json.loads(message) for msg in msgs: if not isinstance(msg, dict): logger.error('Invalid WS message format: {}'.format(message)) continue _type = msg.get('type') if _typ...
[ "def", "on_websocket_message", "(", "message", ":", "str", ")", "->", "None", ":", "msgs", "=", "json", ".", "loads", "(", "message", ")", "for", "msg", "in", "msgs", ":", "if", "not", "isinstance", "(", "msg", ",", "dict", ")", ":", "logger", ".", ...
37.1875
0.001639