text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def get_files(): """ Return the list of all source/header files in `c/` directory. The files will have pathnames relative to the current folder, for example "c/csv/reader_utils.cc". """ sources = [] headers = ["datatable/include/datatable.h"] assert os.path.isfile(headers[0]) for di...
[ "def", "get_files", "(", ")", ":", "sources", "=", "[", "]", "headers", "=", "[", "\"datatable/include/datatable.h\"", "]", "assert", "os", ".", "path", ".", "isfile", "(", "headers", "[", "0", "]", ")", "for", "dirpath", ",", "_", ",", "filenames", "i...
35.444444
0.001527
def signatures(self, all_are_optional: Optional[bool] = False) -> List[str]: """ Return the __init__ signature element(s) (var: type = default value). Note that signatures are not generated for non-python names, although we do take the liberty of suffixing a '_' for reserved words (e.g. class: ...
[ "def", "signatures", "(", "self", ",", "all_are_optional", ":", "Optional", "[", "bool", "]", "=", "False", ")", "->", "List", "[", "str", "]", ":", "if", "self", ".", "_type_reference", ":", "# This assumes that references are to things that have signatures", "re...
60.444444
0.008145
def download(self, filename, action='download', x_filename='', x_sendfile=None, real_filename=''): """ action will be "download", "inline" and if the request.GET has 'action', then the action will be replaced by it. """ from uliweb import request from uliweb.utils.c...
[ "def", "download", "(", "self", ",", "filename", ",", "action", "=", "'download'", ",", "x_filename", "=", "''", ",", "x_sendfile", "=", "None", ",", "real_filename", "=", "''", ")", ":", "from", "uliweb", "import", "request", "from", "uliweb", ".", "uti...
45.518519
0.011155
def absolute_error(y, y_pred): """Calculates the sum of the differences between target and prediction. Parameters: ----------- y : vector, shape (n_samples,) The target values. y_pred : vector, shape (n_samples,) The predicted values. Returns: -------- error : floa...
[ "def", "absolute_error", "(", "y", ",", "y_pred", ")", ":", "y", ",", "y_pred", "=", "convert_assert", "(", "y", ",", "y_pred", ")", "return", "np", ".", "sum", "(", "y", "-", "y_pred", ")" ]
21.52381
0.008475
async def _async_wait_for_process( future_process: Any, out: Optional[Union[TeeCapture, IO[str]]] = sys.stdout, err: Optional[Union[TeeCapture, IO[str]]] = sys.stderr ) -> CommandOutput: """Awaits the creation and completion of an asynchronous process. Args: future_process: The ...
[ "async", "def", "_async_wait_for_process", "(", "future_process", ":", "Any", ",", "out", ":", "Optional", "[", "Union", "[", "TeeCapture", ",", "IO", "[", "str", "]", "]", "]", "=", "sys", ".", "stdout", ",", "err", ":", "Optional", "[", "Union", "[",...
39.772727
0.001116
def _set_next_host_location(self, context): ''' A function which sets the next host location on the request, if applicable. :param ~azure.storage.models.RetryContext context: The retry context containing the previous host location and the request to evaluate and possi...
[ "def", "_set_next_host_location", "(", "self", ",", "context", ")", ":", "if", "len", "(", "context", ".", "request", ".", "host_locations", ")", ">", "1", ":", "# If there's more than one possible location, retry to the alternative", "if", "context", ".", "location_m...
57.75
0.009732
def _call_fan(branch, calls, executable): """Appends a list of callees to the branch for each parent in the call list that calls this executable. """ #Since we don't keep track of the specific logic in the executables #it is possible that we could get a infinite recursion of executables #that ke...
[ "def", "_call_fan", "(", "branch", ",", "calls", ",", "executable", ")", ":", "#Since we don't keep track of the specific logic in the executables", "#it is possible that we could get a infinite recursion of executables", "#that keep calling each other.", "if", "executable", "in", "b...
35.5625
0.008562
def parsed_function_to_ast(parsed: Parsed, parsed_key): """Create AST for top-level functions""" sub = parsed[parsed_key] subtree = { "type": "Function", "span": sub["span"], "function": { "name": sub["name"], "name_span": sub["name_span"], "pare...
[ "def", "parsed_function_to_ast", "(", "parsed", ":", "Parsed", ",", "parsed_key", ")", ":", "sub", "=", "parsed", "[", "parsed_key", "]", "subtree", "=", "{", "\"type\"", ":", "\"Function\"", ",", "\"span\"", ":", "sub", "[", "\"span\"", "]", ",", "\"funct...
28.785714
0.0016
def process(self, processor:PreProcessors=None): "Apply `processor` or `self.processor` to `self`." if processor is not None: self.processor = processor self.processor = listify(self.processor) for p in self.processor: p.process(self) return self
[ "def", "process", "(", "self", ",", "processor", ":", "PreProcessors", "=", "None", ")", ":", "if", "processor", "is", "not", "None", ":", "self", ".", "processor", "=", "processor", "self", ".", "processor", "=", "listify", "(", "self", ".", "processor"...
46.833333
0.024476
def to_sigproc_angle(angle_val): """ Convert an astropy.Angle to the ridiculous sigproc angle format string. """ x = str(angle_val) if '.' in x: if 'h' in x: d, m, s, ss = int(x[0:x.index('h')]), int(x[x.index('h')+1:x.index('m')]), \ int(x[x.index('m')+1:x.index('.'...
[ "def", "to_sigproc_angle", "(", "angle_val", ")", ":", "x", "=", "str", "(", "angle_val", ")", "if", "'.'", "in", "x", ":", "if", "'h'", "in", "x", ":", "d", ",", "m", ",", "s", ",", "ss", "=", "int", "(", "x", "[", "0", ":", "x", ".", "ind...
47.52381
0.014735
def closest_point(triangles, points): """ Return the closest point on the surface of each triangle for a list of corresponding points. Implements the method from "Real Time Collision Detection" and use the same variable names as "ClosestPtPointTriangle" to avoid being any more confusing. ...
[ "def", "closest_point", "(", "triangles", ",", "points", ")", ":", "# check input triangles and points", "triangles", "=", "np", ".", "asanyarray", "(", "triangles", ",", "dtype", "=", "np", ".", "float64", ")", "points", "=", "np", ".", "asanyarray", "(", "...
31.983333
0.000253
def google(self): """Gets the tile in the Google format, converted from TMS""" tms_x, tms_y = self.tms return tms_x, (2 ** self.zoom - 1) - tms_y
[ "def", "google", "(", "self", ")", ":", "tms_x", ",", "tms_y", "=", "self", ".", "tms", "return", "tms_x", ",", "(", "2", "**", "self", ".", "zoom", "-", "1", ")", "-", "tms_y" ]
41.5
0.011834
def get_filter_item(name: str, operation: bytes, value: bytes) -> bytes: """ A field could be found for this term, try to get filter string for it. """ assert isinstance(name, str) assert isinstance(value, bytes) if operation is None: return filter_format(b"(%s=%s)", [name, value]) e...
[ "def", "get_filter_item", "(", "name", ":", "str", ",", "operation", ":", "bytes", ",", "value", ":", "bytes", ")", "->", "bytes", ":", "assert", "isinstance", "(", "name", ",", "str", ")", "assert", "isinstance", "(", "value", ",", "bytes", ")", "if",...
38.384615
0.001957
def is_netcdf(url): ''' Returns True if the URL points to a valid local netCDF file :param str url: Location of file on the file system ''' # Try an obvious exclusion of remote resources if url.startswith('http'): return False # If it's a known extension, give it a shot if url....
[ "def", "is_netcdf", "(", "url", ")", ":", "# Try an obvious exclusion of remote resources", "if", "url", ".", "startswith", "(", "'http'", ")", ":", "return", "False", "# If it's a known extension, give it a shot", "if", "url", ".", "endswith", "(", "'nc'", ")", ":"...
24.92
0.001546
def resolve_return_value_options(self, options): """Handle dynamic option value lookups in the format ^^task_name.attr""" for key, value in options.items(): if isinstance(value, str) and value.startswith(RETURN_VALUE_OPTION_PREFIX): path, name = value[len(RETURN_VALUE_OPTION_...
[ "def", "resolve_return_value_options", "(", "self", ",", "options", ")", ":", "for", "key", ",", "value", "in", "options", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "str", ")", "and", "value", ".", "startswith", "(", "RETURN_VAL...
65.428571
0.012931
def issue_link_types(self): """Get a list of issue link type Resources from the server. :rtype: List[IssueLinkType] """ r_json = self._get_json('issueLinkType') link_types = [IssueLinkType(self._options, self._session, raw_link_json) for raw_link_json in r_...
[ "def", "issue_link_types", "(", "self", ")", ":", "r_json", "=", "self", ".", "_get_json", "(", "'issueLinkType'", ")", "link_types", "=", "[", "IssueLinkType", "(", "self", ".", "_options", ",", "self", ".", "_session", ",", "raw_link_json", ")", "for", "...
40.111111
0.00813
def expandPath(self, path): """ Follows the path and expand all nodes along the way. Returns (item, index) tuple of the last node in the path (the leaf node). This can be reused e.g. to select it. """ iiPath = self.model().findItemAndIndexPath(path) for (item, ind...
[ "def", "expandPath", "(", "self", ",", "path", ")", ":", "iiPath", "=", "self", ".", "model", "(", ")", ".", "findItemAndIndexPath", "(", "path", ")", "for", "(", "item", ",", "index", ")", "in", "iiPath", "[", "1", ":", "]", ":", "# skip invisible r...
43.916667
0.009294
def enabled(name, **kwargs): ''' Return True if the named service is enabled, false otherwise A service is considered enabled if in your service directory: - an executable ./run file exist - a file named "down" does not exist .. versionadded:: 2015.5.7 name Service name CLI Ex...
[ "def", "enabled", "(", "name", ",", "*", "*", "kwargs", ")", ":", "if", "not", "available", "(", "name", ")", ":", "log", ".", "error", "(", "'Service %s not found'", ",", "name", ")", "return", "False", "run_file", "=", "os", ".", "path", ".", "join...
24.266667
0.001321
def _process_batch_write_response(request, response, table_crypto_config): # type: (Dict, Dict, Dict[Text, CryptoConfig]) -> Dict """Handle unprocessed items in the response from a transparently encrypted write. :param dict request: The DynamoDB plaintext request dictionary :param dict response: The Dy...
[ "def", "_process_batch_write_response", "(", "request", ",", "response", ",", "table_crypto_config", ")", ":", "# type: (Dict, Dict, Dict[Text, CryptoConfig]) -> Dict", "try", ":", "unprocessed_items", "=", "response", "[", "\"UnprocessedItems\"", "]", "except", "KeyError", ...
43.868421
0.002347
def find_near_matches_substitutions_ngrams(subsequence, sequence, max_substitutions): """search for near-matches of subsequence in sequence This searches for near-matches, where the nearly-matching parts of the sequence must meet the following limitations (relativ...
[ "def", "find_near_matches_substitutions_ngrams", "(", "subsequence", ",", "sequence", ",", "max_substitutions", ")", ":", "_check_arguments", "(", "subsequence", ",", "sequence", ",", "max_substitutions", ")", "match_starts", "=", "set", "(", ")", "matches", "=", "[...
44.9
0.001091
def contains_entry(self, *args, **kwargs): """Asserts that val is a dict and contains the given entry or entries.""" self._check_dict_like(self.val, check_values=False) entries = list(args) + [{k:v} for k,v in kwargs.items()] if len(entries) == 0: raise ValueError('one or mor...
[ "def", "contains_entry", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_check_dict_like", "(", "self", ".", "val", ",", "check_values", "=", "False", ")", "entries", "=", "list", "(", "args", ")", "+", "[", "{", "k...
49
0.009009
def gcs_get_file(bucketname, filename, local_file, altexts=None, client=None, service_account_json=None, raiseonfail=False): """This gets a single file from a Google Cloud Storage bucket. Parameters ------...
[ "def", "gcs_get_file", "(", "bucketname", ",", "filename", ",", "local_file", ",", "altexts", "=", "None", ",", "client", "=", "None", ",", "service_account_json", "=", "None", ",", "raiseonfail", "=", "False", ")", ":", "if", "not", "client", ":", "if", ...
30.139785
0.001036
def regex(self): """Return compiled regex.""" if not self._compiled_regex: self._compiled_regex = re.compile(self.raw) return self._compiled_regex
[ "def", "regex", "(", "self", ")", ":", "if", "not", "self", ".", "_compiled_regex", ":", "self", ".", "_compiled_regex", "=", "re", ".", "compile", "(", "self", ".", "raw", ")", "return", "self", ".", "_compiled_regex" ]
35.6
0.010989
def autoreg(self, data: ['SASdata', str] = None, by: [str, list] = None, cls: [str, list] = None, hetero: str = None, model: str = None, nloptions: str = None, output: [str, bool, 'SASdata'] = None, restrict:...
[ "def", "autoreg", "(", "self", ",", "data", ":", "[", "'SASdata'", ",", "str", "]", "=", "None", ",", "by", ":", "[", "str", ",", "list", "]", "=", "None", ",", "cls", ":", "[", "str", ",", "list", "]", "=", "None", ",", "hetero", ":", "str",...
53.533333
0.011009
def BeginEdit(self, row, col, grid): """ Fetch the value from the table and prepare the edit control to begin editing. Set the focus to the edit control. *Must Override* """ # Disable if cell is locked, enable if cell is not locked grid = self.main_window.grid ...
[ "def", "BeginEdit", "(", "self", ",", "row", ",", "col", ",", "grid", ")", ":", "# Disable if cell is locked, enable if cell is not locked", "grid", "=", "self", ".", "main_window", ".", "grid", "key", "=", "grid", ".", "actions", ".", "cursor", "locked", "=",...
34.954545
0.001265
def fetch_items(self, category, **kwargs): """Fetch the articles :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items """ offset = kwargs['offset'] logger.info("Fetching articles of '%s' group on '%s' o...
[ "def", "fetch_items", "(", "self", ",", "category", ",", "*", "*", "kwargs", ")", ":", "offset", "=", "kwargs", "[", "'offset'", "]", "logger", ".", "info", "(", "\"Fetching articles of '%s' group on '%s' offset %s\"", ",", "self", ".", "group", ",", "self", ...
31.136364
0.001415
def render_tile(cells, ti, tj, render, params, metadata, layout, summary): """ Render each cell in the tile and stitch it into a single image """ image_size = params["cell_size"] * params["n_tile"] tile = Image.new("RGB", (image_size, image_size), (255,255,255)) keys = cells.keys() for i,key in enumerat...
[ "def", "render_tile", "(", "cells", ",", "ti", ",", "tj", ",", "render", ",", "params", ",", "metadata", ",", "layout", ",", "summary", ")", ":", "image_size", "=", "params", "[", "\"cell_size\"", "]", "*", "params", "[", "\"n_tile\"", "]", "tile", "="...
37.146341
0.017914
def _parameter_sweep(self, parameter_space, kernel_options, device_options, tuning_options): """Build a Noodles workflow by sweeping the parameter space""" results = [] #randomize parameter space to do pseudo load balancing parameter_space = list(parameter_space) random.shuffle(...
[ "def", "_parameter_sweep", "(", "self", ",", "parameter_space", ",", "kernel_options", ",", "device_options", ",", "tuning_options", ")", ":", "results", "=", "[", "]", "#randomize parameter space to do pseudo load balancing", "parameter_space", "=", "list", "(", "param...
38.368421
0.009371
def font(self): """ Selected font. :return: font tuple (family_name, size, \*options), :class:`~font.Font` object """ if self._family is None: return None, None else: font_tuple = self.__generate_font_tuple() font_obj = font.Fo...
[ "def", "font", "(", "self", ")", ":", "if", "self", ".", "_family", "is", "None", ":", "return", "None", ",", "None", "else", ":", "font_tuple", "=", "self", ".", "__generate_font_tuple", "(", ")", "font_obj", "=", "font", ".", "Font", "(", "family", ...
43.5625
0.009831
def _unique(x): """Faster version of np.unique(). This version is restricted to 1D arrays of non-negative integers. It is only faster if len(x) >> len(unique(x)). """ if x is None or len(x) == 0: return np.array([], dtype=np.int64) # WARNING: only keep positive values. # cluster=-...
[ "def", "_unique", "(", "x", ")", ":", "if", "x", "is", "None", "or", "len", "(", "x", ")", "==", "0", ":", "return", "np", ".", "array", "(", "[", "]", ",", "dtype", "=", "np", ".", "int64", ")", "# WARNING: only keep positive values.", "# cluster=-1...
26.1875
0.002304
def _GetMessageFromFactory(factory, full_name): """Get a proto class from the MessageFactory by name. Args: factory: a MessageFactory instance. full_name: str, the fully qualified name of the proto type. Returns: A class, for the type identified by full_name. Raises: KeyError, if the proto is n...
[ "def", "_GetMessageFromFactory", "(", "factory", ",", "full_name", ")", ":", "proto_descriptor", "=", "factory", ".", "pool", ".", "FindMessageTypeByName", "(", "full_name", ")", "proto_cls", "=", "factory", ".", "GetPrototype", "(", "proto_descriptor", ")", "retu...
35.285714
0.009862
def read(self, how_much=128): # FIXME: 128 might be too much ... what is largest? """ This toggles the RTS pin and reads in data. It also converts the buffer back into a list of bytes and searches through the list to find valid packets of info. If there is more than one packet, this returns an array of valid...
[ "def", "read", "(", "self", ",", "how_much", "=", "128", ")", ":", "# FIXME: 128 might be too much ... what is largest?", "# ret = self.readPkts(how_much)", "# return ret", "ret", "=", "[", "]", "self", ".", "setRTS", "(", "self", ".", "DD_READ", ")", "# this in_wai...
31.407407
0.030892
def _sample(self, n_samples): """ Sample Generate samples for posterior distribution using Gauss-Newton proposal parameters Inputs : n_samples : number of samples to generate Hidden Outputs : chain : chain of samples n_samples : ...
[ "def", "_sample", "(", "self", ",", "n_samples", ")", ":", "try", ":", "n_samples", "=", "int", "(", "n_samples", ")", "except", ":", "raise", "TypeError", "(", "\"number of samples has to be an integer\"", ")", "exit", "(", ")", "# fetch info", "X", "=", "s...
31.313131
0.013446
def _get_stream_parameters(kind, device, channels, dtype, latency, samplerate): """Generate PaStreamParameters struct.""" if device is None: if kind == 'input': device = _pa.Pa_GetDefaultInputDevice() elif kind == 'output': device = _pa.Pa_GetDefaultOutputDevice() in...
[ "def", "_get_stream_parameters", "(", "kind", ",", "device", ",", "channels", ",", "dtype", ",", "latency", ",", "samplerate", ")", ":", "if", "device", "is", "None", ":", "if", "kind", "==", "'input'", ":", "device", "=", "_pa", ".", "Pa_GetDefaultInputDe...
36.136364
0.001225
def tasks(self, task_cls=None): """ :meth:`.WTaskRegistryBase.tasks` implementation """ result = [] for tasks in self.__registry.values(): result.extend(tasks) if task_cls is not None: result = filter(lambda x: issubclass(x, task_cls), result) return tuple(result)
[ "def", "tasks", "(", "self", ",", "task_cls", "=", "None", ")", ":", "result", "=", "[", "]", "for", "tasks", "in", "self", ".", "__registry", ".", "values", "(", ")", ":", "result", ".", "extend", "(", "tasks", ")", "if", "task_cls", "is", "not", ...
27.4
0.035336
def parse_nested( bels: list, char_locs: CharLocs, parsed: Parsed, errors: Errors ) -> Tuple[Parsed, Errors]: """ Parse nested BEL object """ for sp in char_locs[ "nested_parens" ]: # sp = start parenthesis, ep = end parenthesis ep, level = char_locs["nested_parens"][sp] if ep ...
[ "def", "parse_nested", "(", "bels", ":", "list", ",", "char_locs", ":", "CharLocs", ",", "parsed", ":", "Parsed", ",", "errors", ":", "Errors", ")", "->", "Tuple", "[", "Parsed", ",", "Errors", "]", ":", "for", "sp", "in", "char_locs", "[", "\"nested_p...
31.071429
0.002232
def QA_fetch_get_globalindex_list(ip=None, port=None): """全球指数列表 Keyword Arguments: ip {[type]} -- [description] (default: {None}) port {[type]} -- [description] (default: {None}) 37 11 全球指数(静态) FW 12 5 国际指数 WI """ global extension_m...
[ "def", "QA_fetch_get_globalindex_list", "(", "ip", "=", "None", ",", "port", "=", "None", ")", ":", "global", "extension_market_list", "extension_market_list", "=", "QA_fetch_get_extensionmarket_list", "(", ")", "if", "extension_market_list", "is", "None", "else", "ex...
30.058824
0.001898
def _get_csv_reader(self, f, dialect): """ Returns a csv.reader for the given file handler and csv Dialect named tuple. If the file has a header, it already will be gone through. Also, if self.ipa_col is not set, an attempt will be made to infer which the IPA column is. ValueError would be raised otherwise. ...
[ "def", "_get_csv_reader", "(", "self", ",", "f", ",", "dialect", ")", ":", "reader", "=", "csv", ".", "reader", "(", "f", ",", "delimiter", "=", "dialect", ".", "delimiter", ",", "quotechar", "=", "dialect", ".", "quotechar", ",", "doublequote", "=", "...
30.1
0.040773
def get_me(self, *args, **kwargs): """See :func:`get_me`""" return get_me(*args, **self._merge_overrides(**kwargs)).run()
[ "def", "get_me", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "get_me", "(", "*", "args", ",", "*", "*", "self", ".", "_merge_overrides", "(", "*", "*", "kwargs", ")", ")", ".", "run", "(", ")" ]
45
0.014599
def run_exec(self, cmd, start_opts=None, globals_=None, locals_=None): """ Run debugger on string `cmd' which will executed via the builtin function exec. Arguments `globals_' and `locals_' are the dictionaries to use for local and global variables. By default, the value of globals is gl...
[ "def", "run_exec", "(", "self", ",", "cmd", ",", "start_opts", "=", "None", ",", "globals_", "=", "None", ",", "locals_", "=", "None", ")", ":", "if", "globals_", "is", "None", ":", "globals_", "=", "globals", "(", ")", "if", "locals_", "is", "None",...
40.2
0.001619
def ScaleLarger(self): """Increases the zoom of the graph one step (0.1 units).""" newfactor = self._zoomfactor + 0.1 if float(newfactor) > 0 and float(newfactor) < self._MAX_ZOOM: self._zoomfactor = newfactor
[ "def", "ScaleLarger", "(", "self", ")", ":", "newfactor", "=", "self", ".", "_zoomfactor", "+", "0.1", "if", "float", "(", "newfactor", ")", ">", "0", "and", "float", "(", "newfactor", ")", "<", "self", ".", "_MAX_ZOOM", ":", "self", ".", "_zoomfactor"...
44.6
0.008811
def blocks(data, min_len=2, max_len=np.inf, digits=None, only_nonzero=False): """ Given an array, find the indices of contiguous blocks of equal values. Parameters --------- data: (n) array min_len: int, the minimum length group to be returned ...
[ "def", "blocks", "(", "data", ",", "min_len", "=", "2", ",", "max_len", "=", "np", ".", "inf", ",", "digits", "=", "None", ",", "only_nonzero", "=", "False", ")", ":", "data", "=", "float_to_int", "(", "data", ",", "digits", "=", "digits", ")", "# ...
32.619048
0.000709
def get(self, key, default=None): """Return a value from this :class:`.Context`.""" return self._data.get(key, compat_builtins.__dict__.get(key, default))
[ "def", "get", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "return", "self", ".", "_data", ".", "get", "(", "key", ",", "compat_builtins", ".", "__dict__", ".", "get", "(", "key", ",", "default", ")", ")" ]
42
0.011696
def evtrack(self,m,feh=0.0,minage=None,maxage=None,dage=0.02, return_df=True): """ Returns evolution track for a single initial mass and feh. :param m: Initial mass of desired evolution track. :param feh: (optional) Metallicity of desired track. ...
[ "def", "evtrack", "(", "self", ",", "m", ",", "feh", "=", "0.0", ",", "minage", "=", "None", ",", "maxage", "=", "None", ",", "dage", "=", "0.02", ",", "return_df", "=", "True", ")", ":", "if", "minage", "is", "None", ":", "minage", "=", "self", ...
32.87931
0.01833
def parse(file_path, content=None): """ Create a PythonFile object with specified file_path and content. If content is None then, it is loaded from the file_path method. Otherwise, file_path is only used for reporting errors. """ try: if content is None: ...
[ "def", "parse", "(", "file_path", ",", "content", "=", "None", ")", ":", "try", ":", "if", "content", "is", "None", ":", "with", "open", "(", "file_path", ")", "as", "f", ":", "content", "=", "f", ".", "read", "(", ")", "py_tree", "=", "RedBaron", ...
42.2
0.002317
def set_servers(self, node_couplets): """Set the current collection of servers. The entries are 2-tuples of contexts and nodes. """ node_couplets_s = set(node_couplets) if node_couplets_s != self.__node_couplets_s: _logger.info("Servers have changed. NEW: %s REMOVE...
[ "def", "set_servers", "(", "self", ",", "node_couplets", ")", ":", "node_couplets_s", "=", "set", "(", "node_couplets", ")", "if", "node_couplets_s", "!=", "self", ".", "__node_couplets_s", ":", "_logger", ".", "info", "(", "\"Servers have changed. NEW: %s REMOVED: ...
42.315789
0.008516
def get_nendo (): """今は何年度?""" y, m = map(int, time.strftime("%Y %m").split()) return y if m >= 4 else y - 1
[ "def", "get_nendo", "(", ")", ":", "y", ",", "m", "=", "map", "(", "int", ",", "time", ".", "strftime", "(", "\"%Y %m\"", ")", ".", "split", "(", ")", ")", "return", "y", "if", "m", ">=", "4", "else", "y", "-", "1" ]
29.25
0.016667
def result_code(self, value): """The result_code property. Args: value (string). the property value. """ if value == self._defaults['resultCode'] and 'resultCode' in self._values: del self._values['resultCode'] else: self._values['resu...
[ "def", "result_code", "(", "self", ",", "value", ")", ":", "if", "value", "==", "self", ".", "_defaults", "[", "'resultCode'", "]", "and", "'resultCode'", "in", "self", ".", "_values", ":", "del", "self", ".", "_values", "[", "'resultCode'", "]", "else",...
32.7
0.011905
def _parse_dataset(file_path, tmp_dir, train): """Convert the dataset in to a simpler format. This function creates two files. One for being processed to produce a vocab and another to generate the data. Args: file_path: string, path to the file to parse. tmp_dir: string, path to the directory to outp...
[ "def", "_parse_dataset", "(", "file_path", ",", "tmp_dir", ",", "train", ")", ":", "input_path", "=", "file_path", "file_name", "=", "'train'", "if", "train", "else", "'dev'", "gen_output_path", "=", "os", ".", "path", ".", "join", "(", "tmp_dir", ",", "fi...
35.754717
0.010786
def _init(self): """ Turn the records into actual usable keys. """ self._entry_points = {} for entry_point in self.raw_entry_points: if entry_point.dist.project_name != self.reserved.get( entry_point.name, entry_point.dist.project_name): ...
[ "def", "_init", "(", "self", ")", ":", "self", ".", "_entry_points", "=", "{", "}", "for", "entry_point", "in", "self", ".", "raw_entry_points", ":", "if", "entry_point", ".", "dist", ".", "project_name", "!=", "self", ".", "reserved", ".", "get", "(", ...
39.806452
0.001582
def effect_associated_with_protein_coding_transcript(effect): """ Parameters ---------- effect : subclass of MutationEffect Returns True if effect is associated with a transcript and that transcript has a protein_coding biotype. """ return apply_to_transcript_if_exists( effect=e...
[ "def", "effect_associated_with_protein_coding_transcript", "(", "effect", ")", ":", "return", "apply_to_transcript_if_exists", "(", "effect", "=", "effect", ",", "fn", "=", "lambda", "t", ":", "t", ".", "biotype", "==", "\"protein_coding\"", ",", "default", "=", "...
29.923077
0.002494
def handle(cls, value, **kwargs): """Decrypt the specified value with a master key in KMS. kmssimple field types should be in the following format: [<region>@]<base64 encrypted value> Note: The region is optional, and defaults to the environment's `AWS_DEFAULT_REGION` if n...
[ "def", "handle", "(", "cls", ",", "value", ",", "*", "*", "kwargs", ")", ":", "value", "=", "read_value_from_path", "(", "value", ")", "region", "=", "None", "if", "\"@\"", "in", "value", ":", "region", ",", "value", "=", "value", ".", "split", "(", ...
33.660377
0.001089
def random(cls, components, width=False, colour=None): """ Generate a random legend for a given list of components. Args: components (list or Striplog): A list of components. If you pass a Striplog, it will use the primary components. If you pass a co...
[ "def", "random", "(", "cls", ",", "components", ",", "width", "=", "False", ",", "colour", "=", "None", ")", ":", "try", ":", "# Treating as a Striplog.", "list_of_Decors", "=", "[", "Decor", ".", "random", "(", "c", ")", "for", "c", "in", "[", "i", ...
40.4
0.002417
def results(self, **query_params): """Returns a streaming handle to this job's search results. To get a nice, Pythonic iterator, pass the handle to :class:`splunklib.results.ResultsReader`, as in:: import splunklib.client as client import splunklib.results as results ...
[ "def", "results", "(", "self", ",", "*", "*", "query_params", ")", ":", "query_params", "[", "'segmentation'", "]", "=", "query_params", ".", "get", "(", "'segmentation'", ",", "'none'", ")", "return", "self", ".", "get", "(", "\"results\"", ",", "*", "*...
47.263158
0.002182
def update_client_grants(self, client_id, scope=[], authorities=[], grant_types=[], redirect_uri=[], replace=False): """ Will extend the client with additional scopes or authorities. Any existing scopes and authorities will be left as is unless asked to replace entirely. ...
[ "def", "update_client_grants", "(", "self", ",", "client_id", ",", "scope", "=", "[", "]", ",", "authorities", "=", "[", "]", ",", "grant_types", "=", "[", "]", ",", "redirect_uri", "=", "[", "]", ",", "replace", "=", "False", ")", ":", "self", ".", ...
37.15625
0.002048
def _get_delete_query(self): """ Get the query builder for a delete operation on the pivot. :rtype: orator.orm.Builder """ foreign = self.get_attribute(self.__foreign_key) query = self.new_query().where(self.__foreign_key, foreign) return query.where(self.__oth...
[ "def", "_get_delete_query", "(", "self", ")", ":", "foreign", "=", "self", ".", "get_attribute", "(", "self", ".", "__foreign_key", ")", "query", "=", "self", ".", "new_query", "(", ")", ".", "where", "(", "self", ".", "__foreign_key", ",", "foreign", ")...
32.272727
0.008219
def update_handler(feeds): '''Update all cross-referencing filters results for feeds and others, related to them. Intended to be called from non-Feed update hooks (like new Post saving).''' # Check if this call is a result of actions initiated from # one of the hooks in a higher frame (resulting in recursion)...
[ "def", "update_handler", "(", "feeds", ")", ":", "# Check if this call is a result of actions initiated from", "# one of the hooks in a higher frame (resulting in recursion).", "if", "Feed", ".", "_filters_update_handler_lock", ":", "return", "return", "Feed", ".", "_filters_updat...
60.714286
0.023202
def install_nginx(instance, dbhost, dbname, port, hostname=None): """Install nginx configuration""" _check_root() log("Installing nginx configuration") if hostname is None: try: configuration = _get_system_configuration(dbhost, dbname) hostname = configuration.hostname...
[ "def", "install_nginx", "(", "instance", ",", "dbhost", ",", "dbname", ",", "port", ",", "hostname", "=", "None", ")", ":", "_check_root", "(", ")", "log", "(", "\"Installing nginx configuration\"", ")", "if", "hostname", "is", "None", ":", "try", ":", "co...
32.438596
0.00105
def send(self, url, http_method, **client_args): """ Sends an API request, taking into account that datasets are part of the visualization endpoint. :param url: Endpoint URL :param http_method: The method used to make the request to the API :param client_args: Arguments ...
[ "def", "send", "(", "self", ",", "url", ",", "http_method", ",", "*", "*", "client_args", ")", ":", "try", ":", "client_args", "=", "client_args", "or", "{", "}", "if", "\"params\"", "not", "in", "client_args", ":", "client_args", "[", "\"params\"", "]",...
35.413793
0.001896
def left_to_right(self): """This is for text that flows Left to Right""" self._entry_mode |= Command.MODE_INCREMENT self.command(self._entry_mode)
[ "def", "left_to_right", "(", "self", ")", ":", "self", ".", "_entry_mode", "|=", "Command", ".", "MODE_INCREMENT", "self", ".", "command", "(", "self", ".", "_entry_mode", ")" ]
41.75
0.011765
def get_model_indexes(model): """Return list of all indexes in which a model is configured. A model may be configured to appear in multiple indexes. This function will return the names of the indexes as a list of strings. This is useful if you want to know which indexes need updating when a model i...
[ "def", "get_model_indexes", "(", "model", ")", ":", "indexes", "=", "[", "]", "for", "index", "in", "get_index_names", "(", ")", ":", "for", "app_model", "in", "get_index_models", "(", "index", ")", ":", "if", "app_model", "==", "model", ":", "indexes", ...
31.277778
0.001724
def adjustSize(self): """ Adjusts the size of this popup to best fit the new widget size. """ widget = self.centralWidget() if widget is None: super(XPopupWidget, self).adjustSize() return widget.adjustSize() hint = widge...
[ "def", "adjustSize", "(", "self", ")", ":", "widget", "=", "self", ".", "centralWidget", "(", ")", "if", "widget", "is", "None", ":", "super", "(", "XPopupWidget", ",", "self", ")", ".", "adjustSize", "(", ")", "return", "widget", ".", "adjustSize", "(...
32.483333
0.011952
def setdefault(self, key, defaultvalue = None): """ Support dict-like setdefault (create if not existed) """ (t, k) = self._getsubitem(key, True) return t.__dict__.setdefault(k, defaultvalue)
[ "def", "setdefault", "(", "self", ",", "key", ",", "defaultvalue", "=", "None", ")", ":", "(", "t", ",", "k", ")", "=", "self", ".", "_getsubitem", "(", "key", ",", "True", ")", "return", "t", ".", "__dict__", ".", "setdefault", "(", "k", ",", "d...
37.666667
0.017316
def getPartition(self, seq, p, q): """Returns the pth partition of q partitions of seq.""" # Test for error conditions here if p<0 or p>=q: print "No partition exists." return remainder = len(seq)%q basesize = len(seq)//q hi = [] ...
[ "def", "getPartition", "(", "self", ",", "seq", ",", "p", ",", "q", ")", ":", "# Test for error conditions here", "if", "p", "<", "0", "or", "p", ">=", "q", ":", "print", "\"No partition exists.\"", "return", "remainder", "=", "len", "(", "seq", ")", "%"...
29.535714
0.012881
def R2deriv(self,R,phi=0.,t=0.): """ NAME: R2deriv PURPOSE: evaluate the second radial derivative INPUT: R - Cylindrical radius (can be Quantity) phi= azimuth (optional; can be Quantity) t= time (optional; can be Quantity) ...
[ "def", "R2deriv", "(", "self", ",", "R", ",", "phi", "=", "0.", ",", "t", "=", "0.", ")", ":", "try", ":", "return", "self", ".", "_amp", "*", "self", ".", "_R2deriv", "(", "R", ",", "phi", "=", "phi", ",", "t", "=", "t", ")", "except", "At...
19.774194
0.015552
def almostequal(first, second, places=7, printit=True): """ Test if two values are equal to a given number of places. This is based on python's unittest so may be covered by Python's license. """ if first == second: return True if round(abs(second - first), places) != 0: if...
[ "def", "almostequal", "(", "first", ",", "second", ",", "places", "=", "7", ",", "printit", "=", "True", ")", ":", "if", "first", "==", "second", ":", "return", "True", "if", "round", "(", "abs", "(", "second", "-", "first", ")", ",", "places", ")"...
29.294118
0.001946
def index2bool(index, length=None): """ Returns a numpy boolean array with Trues in the input index positions. :param index: index array with the Trues positions. :type index: ndarray (type=int) :param length: Length of the returned array. :type length: int or None :return...
[ "def", "index2bool", "(", "index", ",", "length", "=", "None", ")", ":", "if", "index", ".", "shape", "[", "0", "]", "==", "0", "and", "length", "is", "None", ":", "return", "np", ".", "arange", "(", "0", ",", "dtype", "=", "bool", ")", "if", "...
31.095238
0.013373
def __write_lipd(dat, usr_path): """ Write LiPD data to file, provided an output directory and dataset name. :param dict dat: Metadata :param str usr_path: Destination path :param str dsn: Dataset name of one specific file to write :return none: """ global settings # no path provide...
[ "def", "__write_lipd", "(", "dat", ",", "usr_path", ")", ":", "global", "settings", "# no path provided. start gui browse", "if", "not", "usr_path", ":", "# got dir path", "usr_path", ",", "_ignore", "=", "get_src_or_dst", "(", "\"write\"", ",", "\"directory\"", ")"...
37.675
0.00194
def marginSell(self, currencyPair, rate, amount, lendingRate=None): """Places a margin sell order in a given market. Parameters and output are the same as for the marginBuy method.""" return self._private('marginSell', currencyPair=currencyPair, rate=rate, amount=amo...
[ "def", "marginSell", "(", "self", ",", "currencyPair", ",", "rate", ",", "amount", ",", "lendingRate", "=", "None", ")", ":", "return", "self", ".", "_private", "(", "'marginSell'", ",", "currencyPair", "=", "currencyPair", ",", "rate", "=", "rate", ",", ...
69
0.008596
def decode_varint_1(buffer, pos=0): """ Decode an integer from a varint presentation. See https://developers.google.com/protocol-buffers/docs/encoding?csw=1#varints on how those can be produced. Arguments: buffer (bytes-like): any object acceptable by ``memoryview`` pos (int...
[ "def", "decode_varint_1", "(", "buffer", ",", "pos", "=", "0", ")", ":", "value", "=", "0", "shift", "=", "0", "memview", "=", "memoryview", "(", "buffer", ")", "for", "i", "in", "range", "(", "pos", ",", "pos", "+", "10", ")", ":", "try", ":", ...
32.290323
0.00097
def pack(self): """convenience function for packing""" block = bytearray(self.size) self.pack_into(block) return block
[ "def", "pack", "(", "self", ")", ":", "block", "=", "bytearray", "(", "self", ".", "size", ")", "self", ".", "pack_into", "(", "block", ")", "return", "block" ]
29.2
0.013333
def get_l2_m2_m_server_credentials(self, authorization, **kwargs): # noqa: E501 """Fetch LwM2M server credentials. # noqa: E501 This REST API is intended to be used by customers to fetch LwM2M server credentials that they will need to use with their clients to connect to LwM2M server. **Example usag...
[ "def", "get_l2_m2_m_server_credentials", "(", "self", ",", "authorization", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'asynchronous'", ")", ":", "return", "...
64.285714
0.00146
def format_value(value,number_format): "Convert number to string using a style string" style,sufix,scale = decode_format(number_format) fmt = "{0:" + style + "}" + sufix return fmt.format(scale * value)
[ "def", "format_value", "(", "value", ",", "number_format", ")", ":", "style", ",", "sufix", ",", "scale", "=", "decode_format", "(", "number_format", ")", "fmt", "=", "\"{0:\"", "+", "style", "+", "\"}\"", "+", "sufix", "return", "fmt", ".", "format", "(...
30.571429
0.018182
def summarize_address_range(first, last): """Summarize a network range given the first and last IP addresses. Example: >>> summarize_address_range(IPv4Address('1.1.1.0'), IPv4Address('1.1.1.130')) [IPv4Network('1.1.1.0/25'), IPv4Network('1.1.1.128/31'), IPv4Network('1.1.1.13...
[ "def", "summarize_address_range", "(", "first", ",", "last", ")", ":", "if", "not", "(", "isinstance", "(", "first", ",", "_BaseIP", ")", "and", "isinstance", "(", "last", ",", "_BaseIP", ")", ")", ":", "raise", "TypeError", "(", "'first and last must be IP ...
32.873016
0.000469
def spatialBin(self, roi): """ Calculate indices of ROI pixels corresponding to object locations. """ if hasattr(self,'pixel_roi_index') and hasattr(self,'pixel'): logger.warning('Catalog alread spatially binned') return # ADW: Not safe to set index = -1...
[ "def", "spatialBin", "(", "self", ",", "roi", ")", ":", "if", "hasattr", "(", "self", ",", "'pixel_roi_index'", ")", "and", "hasattr", "(", "self", ",", "'pixel'", ")", ":", "logger", ".", "warning", "(", "'Catalog alread spatially binned'", ")", "return", ...
43.785714
0.019169
def _to_backend(self, p): """Converts something to the correct path representation. If given a Path, this will simply unpack it, if it's the correct type. If given the correct backend, it will return that. If given bytes for unicode of unicode for bytes, it will encode/decode wi...
[ "def", "_to_backend", "(", "self", ",", "p", ")", ":", "if", "isinstance", "(", "p", ",", "self", ".", "_cmp_base", ")", ":", "return", "p", ".", "path", "elif", "isinstance", "(", "p", ",", "self", ".", "_backend", ")", ":", "return", "p", "elif",...
45.333333
0.002058
def _release_all(self): """Releases all locks to kill all threads""" for i in self.inputs: i.call_release(True) self.available_lock.release()
[ "def", "_release_all", "(", "self", ")", ":", "for", "i", "in", "self", ".", "inputs", ":", "i", ".", "call_release", "(", "True", ")", "self", ".", "available_lock", ".", "release", "(", ")" ]
34.6
0.011299
def calculate_correlations(tetra_z): """Returns dataframe of Pearson correlation coefficients. - tetra_z - dictionary of Z-scores, keyed by sequence ID Calculates Pearson correlation coefficient from Z scores for each tetranucleotide. This is done longhand here, which is fast enough, but for robus...
[ "def", "calculate_correlations", "(", "tetra_z", ")", ":", "orgs", "=", "sorted", "(", "tetra_z", ".", "keys", "(", ")", ")", "correlations", "=", "pd", ".", "DataFrame", "(", "index", "=", "orgs", ",", "columns", "=", "orgs", ",", "dtype", "=", "float...
48.21875
0.001271
def get_package_data(): """get data files which will be included in the main tcod/ directory""" BITSIZE, LINKAGE = platform.architecture() files = [ "py.typed", "lib/LIBTCOD-CREDITS.txt", "lib/LIBTCOD-LICENSE.txt", "lib/README-SDL.txt", ] if "win32" in sys.platform: ...
[ "def", "get_package_data", "(", ")", ":", "BITSIZE", ",", "LINKAGE", "=", "platform", ".", "architecture", "(", ")", "files", "=", "[", "\"py.typed\"", ",", "\"lib/LIBTCOD-CREDITS.txt\"", ",", "\"lib/LIBTCOD-LICENSE.txt\"", ",", "\"lib/README-SDL.txt\"", ",", "]", ...
30.882353
0.001848
def _AnalyzeEvents(self, storage_writer, analysis_plugins, event_filter=None): """Analyzes events in a plaso storage. Args: storage_writer (StorageWriter): storage writer. analysis_plugins (dict[str, AnalysisPlugin]): analysis plugins that should be run and their names. event_filter...
[ "def", "_AnalyzeEvents", "(", "self", ",", "storage_writer", ",", "analysis_plugins", ",", "event_filter", "=", "None", ")", ":", "self", ".", "_status", "=", "definitions", ".", "STATUS_INDICATOR_RUNNING", "self", ".", "_number_of_consumed_events", "=", "0", "sel...
33.422764
0.008032
def IS_calc(TP, FP, FN, POP): """ Calculate IS (Information score). :param TP: true positive :type TP : int :param FP: false positive :type FP : int :param FN: false negative :type FN : int :param POP: population :type POP : int :return: IS as float """ try: ...
[ "def", "IS_calc", "(", "TP", ",", "FP", ",", "FN", ",", "POP", ")", ":", "try", ":", "result", "=", "-", "math", ".", "log", "(", "(", "(", "TP", "+", "FN", ")", "/", "POP", ")", ",", "2", ")", "+", "math", ".", "log", "(", "(", "TP", "...
22.65
0.002119
def saveFileTo(self, buf, encoding): """Dump an XML document to an I/O buffer. Warning ! This call xmlOutputBufferClose() on buf which is not available after this call. """ if buf is None: buf__o = None else: buf__o = buf._o ret = libxml2mod.xmlSaveFileTo(buf__o, sel...
[ "def", "saveFileTo", "(", "self", ",", "buf", ",", "encoding", ")", ":", "if", "buf", "is", "None", ":", "buf__o", "=", "None", "else", ":", "buf__o", "=", "buf", ".", "_o", "ret", "=", "libxml2mod", ".", "xmlSaveFileTo", "(", "buf__o", ",", "self", ...
43.375
0.011299
def freqz_resp_list(b,a=np.array([1]),mode = 'dB',fs=1.0,Npts = 1024,fsize=(6,4)): """ A method for displaying digital filter frequency response magnitude, phase, and group delay. A plot is produced using matplotlib freq_resp(self,mode = 'dB',Npts = 1024) A method for displaying the filter ...
[ "def", "freqz_resp_list", "(", "b", ",", "a", "=", "np", ".", "array", "(", "[", "1", "]", ")", ",", "mode", "=", "'dB'", ",", "fs", "=", "1.0", ",", "Npts", "=", "1024", ",", "fsize", "=", "(", "6", ",", "4", ")", ")", ":", "if", "type", ...
40.488372
0.00813
def _run_algorithm(self): """ Runs nearest neighbor (NN) identification and feature scoring to yield MultiSURF scores. """ nan_entries = np.isnan(self._X) NNlist = [self._find_neighbors(datalen) for datalen in range(self._datalen)] scores = np.sum(Parallel(n_jobs=self.n_jobs)(delayed( ...
[ "def", "_run_algorithm", "(", "self", ")", ":", "nan_entries", "=", "np", ".", "isnan", "(", "self", ".", "_X", ")", "NNlist", "=", "[", "self", ".", "_find_neighbors", "(", "datalen", ")", "for", "datalen", "in", "range", "(", "self", ".", "_datalen",...
55.666667
0.010309
def _tlv_multiplicities_check(tlv_type_count): """ check if multiplicity of present TLVs conforms to the standard :param tlv_type_count: dict containing counte-per-TLV """ # * : 0..n, 1 : one and only one. standard_multiplicities = { LLDPDUEndOfLLDPDU.__name_...
[ "def", "_tlv_multiplicities_check", "(", "tlv_type_count", ")", ":", "# * : 0..n, 1 : one and only one.", "standard_multiplicities", "=", "{", "LLDPDUEndOfLLDPDU", ".", "__name__", ":", "1", ",", "LLDPDUChassisID", ".", "__name__", ":", "1", ",", "LLDPDUPortID", ".", ...
38.631579
0.001329
def lon_lat_bins(bb, coord_bin_width): """ Define bin edges for disaggregation histograms. Given bins data as provided by :func:`collect_bin_data`, this function finds edges of histograms, taking into account maximum and minimum values of magnitude, distance and coordinates as well as requested siz...
[ "def", "lon_lat_bins", "(", "bb", ",", "coord_bin_width", ")", ":", "west", ",", "south", ",", "east", ",", "north", "=", "bb", "west", "=", "numpy", ".", "floor", "(", "west", "/", "coord_bin_width", ")", "*", "coord_bin_width", "east", "=", "numpy", ...
42.75
0.001144
def create_app(path=None, user_content=False, context=None, username=None, password=None, render_offline=False, render_wide=False, render_inline=False, api_url=None, title=None, text=None, autorefresh=None, quiet=None, grip_class=None): """ Creates a Grip application...
[ "def", "create_app", "(", "path", "=", "None", ",", "user_content", "=", "False", ",", "context", "=", "None", ",", "username", "=", "None", ",", "password", "=", "None", ",", "render_offline", "=", "False", ",", "render_wide", "=", "False", ",", "render...
35.911765
0.000797
def bet_place( self, betting_market_id, amount_to_bet, backer_multiplier, back_or_lay, account=None, **kwargs ): """ Place a bet :param str betting_market_id: The identifier for the market to bet in :param peerp...
[ "def", "bet_place", "(", "self", ",", "betting_market_id", ",", "amount_to_bet", ",", "backer_multiplier", ",", "back_or_lay", ",", "account", "=", "None", ",", "*", "*", "kwargs", ")", ":", "from", ".", "import", "GRAPHENE_BETTING_ODDS_PRECISION", "assert", "is...
36.409091
0.001824
def _phi( p ): # this function is faster than using scipy.stats.norm.isf(p) # but the permissity of the license isn't explicitly listed. # using scipy.stats.norm.isf(p) is an acceptable alternative """ Modified from the author's original perl code (original comments follow below) by dfield@yaho...
[ "def", "_phi", "(", "p", ")", ":", "# this function is faster than using scipy.stats.norm.isf(p)", "# but the permissity of the license isn't explicitly listed.", "# using scipy.stats.norm.isf(p) is an acceptable alternative", "if", "p", "<=", "0", "or", "p", ">=", "1", ":", "# T...
39.53125
0.00887
def sign_out(entry, time_out=None, forgot=False): """Sign out of an existing entry in the timesheet. If the user forgot to sign out, flag the entry. :param entry: `models.Entry` object. The entry to sign out. :param time_out: (optional) `datetime.time` object. Specify the sign out time. :param forg...
[ "def", "sign_out", "(", "entry", ",", "time_out", "=", "None", ",", "forgot", "=", "False", ")", ":", "# noqa", "if", "time_out", "is", "None", ":", "time_out", "=", "datetime", ".", "today", "(", ")", ".", "time", "(", ")", "if", "forgot", ":", "e...
34.869565
0.002427
def load_data(flist, drop_duplicates=False): ''' Usage: set train, target, and test key and feature files. FEATURE_LIST_stage2 = { 'train':( TEMP_PATH + 'v1_stage1_all_fold.csv', TEMP_PATH + 'v2_stage1_all_fold.csv', ...
[ "def", "load_data", "(", "flist", ",", "drop_duplicates", "=", "False", ")", ":", "if", "(", "len", "(", "flist", "[", "'train'", "]", ")", "==", "0", ")", "or", "(", "len", "(", "flist", "[", "'target'", "]", ")", "==", "0", ")", "or", "(", "l...
37.409091
0.011839
def filter_merged_pull_requests(self, pull_requests): """ This method filter only merged PR and fetch missing required attributes for pull requests. Using merged date is more correct than closed date. :param list(dict) pull_requests: Pre-filtered pull requests. :rtype: l...
[ "def", "filter_merged_pull_requests", "(", "self", ",", "pull_requests", ")", ":", "if", "self", ".", "options", ".", "verbose", ":", "print", "(", "\"Fetching merge date for pull requests...\"", ")", "closed_pull_requests", "=", "self", ".", "fetcher", ".", "fetch_...
33.645161
0.001864
def _set_list_ids_from_xml_iter(self, xml, xmlpath, var): ''' Set a list variable from the frameids of matching xml entities ''' es = xml.iterfind(xmlpath) if es is not None: l = [] for e in es: l.append( e.attrib['frameid'] ) ...
[ "def", "_set_list_ids_from_xml_iter", "(", "self", ",", "xml", ",", "xmlpath", ",", "var", ")", ":", "es", "=", "xml", ".", "iterfind", "(", "xmlpath", ")", "if", "es", "is", "not", "None", ":", "l", "=", "[", "]", "for", "e", "in", "es", ":", "l...
31.181818
0.016997
def build_dct(dic, keys, value): """Builds a dictionary with arbitrary depth out of a key list""" key = keys.pop(0) if len(keys): dic.setdefault(key, {}) build_dct(dic[key], keys, value) else: # Transform cookbook default attribute strings into proper booleans if value ==...
[ "def", "build_dct", "(", "dic", ",", "keys", ",", "value", ")", ":", "key", "=", "keys", ".", "pop", "(", "0", ")", "if", "len", "(", "keys", ")", ":", "dic", ".", "setdefault", "(", "key", ",", "{", "}", ")", "build_dct", "(", "dic", "[", "k...
33.428571
0.002079
def get_banks_by_assessment_taken(self, assessment_taken_id): """Gets the list of ``Banks`` mapped to an ``AssessmentTaken``. arg: assessment_taken_id (osid.id.Id): ``Id`` of an ``AssessmentTaken`` return: (osid.assessment.BankList) - list of banks raise: NotFound - ...
[ "def", "get_banks_by_assessment_taken", "(", "self", ",", "assessment_taken_id", ")", ":", "# Implemented from template for", "# osid.resource.ResourceBinSession.get_bins_by_resource", "mgr", "=", "self", ".", "_get_provider_manager", "(", "'ASSESSMENT'", ",", "local", "=", "...
51.368421
0.002012
def setUp(self, tp, empty=False): '''Problematic, loose all model group information. <all>, <choice>, <sequence> .. tp -- type definition empty -- no model group, just use as a dummy holder. ''' self._item = tp self.name = tp.getAttribute('name') ...
[ "def", "setUp", "(", "self", ",", "tp", ",", "empty", "=", "False", ")", ":", "self", ".", "_item", "=", "tp", "self", ".", "name", "=", "tp", ".", "getAttribute", "(", "'name'", ")", "self", ".", "ns", "=", "tp", ".", "getTargetNamespace", "(", ...
27.647059
0.011305
def genderStats(self, asFractions = False): """Creates a dict (`{'Male' : maleCount, 'Female' : femaleCount, 'Unknown' : unknownCount}`) with the numbers of male, female and unknown names in the collection. # Parameters _asFractions_ : `optional bool` > Default `False`, if `True` the ...
[ "def", "genderStats", "(", "self", ",", "asFractions", "=", "False", ")", ":", "maleCount", "=", "0", "femaleCount", "=", "0", "unknownCount", "=", "0", "for", "R", "in", "self", ":", "m", ",", "f", ",", "u", "=", "R", ".", "authGenders", "(", "_co...
39.035714
0.015179
def lorenz(values, weights = None): """ Computes Lorenz Curve coordinates """ if weights is None: weights = ones(len(values)) df = pd.DataFrame({'v': values, 'w': weights}) df = df.sort_values(by = 'v') x = cumsum(df['w']) x = x / float(x[-1:]) y = cumsum(df['v'] * df['w']) ...
[ "def", "lorenz", "(", "values", ",", "weights", "=", "None", ")", ":", "if", "weights", "is", "None", ":", "weights", "=", "ones", "(", "len", "(", "values", ")", ")", "df", "=", "pd", ".", "DataFrame", "(", "{", "'v'", ":", "values", ",", "'w'",...
23.2
0.013812
def _traverse_command(self, name, *args, **kwargs): """Add key AND the hash field to the args, and call the Redis command.""" args = list(args) args.insert(0, self.name) return super(InstanceHashField, self)._traverse_command(name, *args, **kwargs)
[ "def", "_traverse_command", "(", "self", ",", "name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "args", "=", "list", "(", "args", ")", "args", ".", "insert", "(", "0", ",", "self", ".", "name", ")", "return", "super", "(", "InstanceHashF...
55.2
0.014286
def register_id(self, id, module): """Associate the given id with the given project module.""" assert isinstance(id, basestring) assert isinstance(module, basestring) self.id2module[id] = module
[ "def", "register_id", "(", "self", ",", "id", ",", "module", ")", ":", "assert", "isinstance", "(", "id", ",", "basestring", ")", "assert", "isinstance", "(", "module", ",", "basestring", ")", "self", ".", "id2module", "[", "id", "]", "=", "module" ]
44.4
0.00885