text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def semicovariance(prices, benchmark=0, frequency=252): """ Estimate the semicovariance matrix, i.e the covariance given that the returns are less than the benchmark. .. semicov = E([min(r_i - B, 0)] . [min(r_j - B, 0)]) :param prices: adjusted closing prices of the asset, each row is a date ...
[ "def", "semicovariance", "(", "prices", ",", "benchmark", "=", "0", ",", "frequency", "=", "252", ")", ":", "if", "not", "isinstance", "(", "prices", ",", "pd", ".", "DataFrame", ")", ":", "warnings", ".", "warn", "(", "\"prices are not in a dataframe\"", ...
40.916667
0.00199
def genius(song): """ Returns the lyrics found in genius.com for the specified mp3 file or an empty string if not found. """ translate = { '@': 'at', '&': 'and', URLESCAPE: '', ' ': '-' } artist = song.artist.capitalize() artist = normalize(artist, transla...
[ "def", "genius", "(", "song", ")", ":", "translate", "=", "{", "'@'", ":", "'at'", ",", "'&'", ":", "'and'", ",", "URLESCAPE", ":", "''", ",", "' '", ":", "'-'", "}", "artist", "=", "song", ".", "artist", ".", "capitalize", "(", ")", "artist", "=...
25.56
0.001508
def flatten(l): """Flatten a nested list.""" return sum(map(flatten, l), []) \ if isinstance(l, list) or isinstance(l, tuple) else [l]
[ "def", "flatten", "(", "l", ")", ":", "return", "sum", "(", "map", "(", "flatten", ",", "l", ")", ",", "[", "]", ")", "if", "isinstance", "(", "l", ",", "list", ")", "or", "isinstance", "(", "l", ",", "tuple", ")", "else", "[", "l", "]" ]
36.75
0.013333
def write(self, pkt): """ This is a simple serial write command. It toggles the RTS pin and formats all of the data into bytes before it writes. """ self.setRTS(self.DD_WRITE) self.flushInput() # prep data array for transmition pkt = bytearray(pkt) pkt = bytes(pkt) num = self.serial.write(pkt) # ...
[ "def", "write", "(", "self", ",", "pkt", ")", ":", "self", ".", "setRTS", "(", "self", ".", "DD_WRITE", ")", "self", ".", "flushInput", "(", ")", "# prep data array for transmition", "pkt", "=", "bytearray", "(", "pkt", ")", "pkt", "=", "bytes", "(", "...
26.6
0.03632
def characterSet(self, charset: str) -> None: """Set character set of this document.""" charset_node = self._find_charset_node() or Meta(parent=self.head) charset_node.setAttribute('charset', charset)
[ "def", "characterSet", "(", "self", ",", "charset", ":", "str", ")", "->", "None", ":", "charset_node", "=", "self", ".", "_find_charset_node", "(", ")", "or", "Meta", "(", "parent", "=", "self", ".", "head", ")", "charset_node", ".", "setAttribute", "("...
55.25
0.008929
def parse_theta2_report (self, fh): """ Parse the final THetA2 log file. """ parsed_data = {} for l in fh: if l.startswith('#'): continue else: s = l.split("\t") purities = s[1].split(',') parsed_data['propor...
[ "def", "parse_theta2_report", "(", "self", ",", "fh", ")", ":", "parsed_data", "=", "{", "}", "for", "l", "in", "fh", ":", "if", "l", ".", "startswith", "(", "'#'", ")", ":", "continue", "else", ":", "s", "=", "l", ".", "split", "(", "\"\\t\"", "...
42.705882
0.008086
def handleError(exception, debugFlag=False, abortFlag=True): """Error handling utility. Print more or less error information depending on debug flag. Unless abort is set False, exits with error code 1.""" if isinstance(exception, CmdError) or not debugFlag: error(str(exception)) else: ...
[ "def", "handleError", "(", "exception", ",", "debugFlag", "=", "False", ",", "abortFlag", "=", "True", ")", ":", "if", "isinstance", "(", "exception", ",", "CmdError", ")", "or", "not", "debugFlag", ":", "error", "(", "str", "(", "exception", ")", ")", ...
39.166667
0.002079
def vector(self) -> typing.Tuple[typing.Tuple[float, float], typing.Tuple[float, float]]: """Return the vector property in relative coordinates. Vector will be a tuple of tuples ((y_start, x_start), (y_end, x_end)).""" ...
[ "def", "vector", "(", "self", ")", "->", "typing", ".", "Tuple", "[", "typing", ".", "Tuple", "[", "float", ",", "float", "]", ",", "typing", ".", "Tuple", "[", "float", ",", "float", "]", "]", ":", "..." ]
48.6
0.016194
def categorical_to_numeric(table): """Encode categorical columns to numeric by converting each category to an integer value. Parameters ---------- table : pandas.DataFrame Table with categorical columns to encode. Returns ------- encoded : pandas.DataFrame Table with ca...
[ "def", "categorical_to_numeric", "(", "table", ")", ":", "def", "transform", "(", "column", ")", ":", "if", "is_categorical_dtype", "(", "column", ".", "dtype", ")", ":", "return", "column", ".", "cat", ".", "codes", "if", "column", ".", "dtype", ".", "c...
33.052632
0.001547
def get_pretty_child_location(self, child_name, blank_parent_part: bool = False): """ Utility method to return a string representation of the location of a child :param child_name: :param blank_parent_part: :return: """ if blank_parent_part: idx = len(...
[ "def", "get_pretty_child_location", "(", "self", ",", "child_name", ",", "blank_parent_part", ":", "bool", "=", "False", ")", ":", "if", "blank_parent_part", ":", "idx", "=", "len", "(", "self", ".", "location", ")", "return", "(", "' '", "*", "(", "idx", ...
40.769231
0.009225
def read_smet(filename, mode): """Reads smet data and returns the data in required dataformat (pd df) See https://models.slf.ch/docserver/meteoio/SMET_specifications.pdf for further details on the specifications of this file format. Parameters ---- filename : SMET file to read mode : "...
[ "def", "read_smet", "(", "filename", ",", "mode", ")", ":", "# dictionary", "# based on smet spec V.1.1 and self defined", "# daily data", "dict_d", "=", "{", "'TA'", ":", "'tmean'", ",", "'TMAX'", ":", "'tmax'", ",", "# no spec", "'TMIN'", ":", "'tmin'", ",", "...
25.074074
0.000474
async def multiple_request(self, urls, is_gather=False, **kwargs): """For crawling multiple urls""" if is_gather: resp_results = await asyncio.gather( *[ self.handle_request(self.request(url=url, **kwargs)) for url in urls ...
[ "async", "def", "multiple_request", "(", "self", ",", "urls", ",", "is_gather", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "is_gather", ":", "resp_results", "=", "await", "asyncio", ".", "gather", "(", "*", "[", "self", ".", "handle_request",...
42.6
0.002296
def _get(self, url): """Make a get request against the charmstore. This method is used by other API methods to standardize querying. @param url The full url to query (e.g. https://api.jujucharms.com/charmstore/v4/macaroon) """ try: response = requests.get...
[ "def", "_get", "(", "self", ",", "url", ")", ":", "try", ":", "response", "=", "requests", ".", "get", "(", "url", ",", "verify", "=", "self", ".", "verify", ",", "cookies", "=", "self", ".", "cookies", ",", "timeout", "=", "self", ".", "timeout", ...
44.439024
0.001074
def denoise_grid(self, val, expand=1): """ for every cell in the grid of 'val' fill all cells around it to de noise the grid """ updated_grid = [[self.grd.get_tile(y,x) \ for x in range(self.grd.grid_width)] \ for y in rang...
[ "def", "denoise_grid", "(", "self", ",", "val", ",", "expand", "=", "1", ")", ":", "updated_grid", "=", "[", "[", "self", ".", "grd", ".", "get_tile", "(", "y", ",", "x", ")", "for", "x", "in", "range", "(", "self", ".", "grd", ".", "grid_width",...
51.4
0.012731
def get(self, ring, angle): """Get RGB color tuple of color at index pixel""" pixel = self.angleToPixel(angle, ring) return self._get_base(pixel)
[ "def", "get", "(", "self", ",", "ring", ",", "angle", ")", ":", "pixel", "=", "self", ".", "angleToPixel", "(", "angle", ",", "ring", ")", "return", "self", ".", "_get_base", "(", "pixel", ")" ]
41.5
0.011834
def get_certificate(self, **kwargs): """Get the attributes of the current array certificate. :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **GET cert** :type \*\*kwargs: optional :retu...
[ "def", "get_certificate", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_rest_version", ">=", "LooseVersion", "(", "\"1.12\"", ")", ":", "return", "self", ".", "_request", "(", "\"GET\"", ",", "\"cert/{0}\"", ".", "format", "(", "kw...
32.590909
0.009485
def credentials_lists(self): """ Access the credentials_lists :returns: twilio.rest.trunking.v1.trunk.credential_list.CredentialListList :rtype: twilio.rest.trunking.v1.trunk.credential_list.CredentialListList """ if self._credentials_lists is None: self._cre...
[ "def", "credentials_lists", "(", "self", ")", ":", "if", "self", ".", "_credentials_lists", "is", "None", ":", "self", ".", "_credentials_lists", "=", "CredentialListList", "(", "self", ".", "_version", ",", "trunk_sid", "=", "self", ".", "_solution", "[", "...
43.5
0.011261
def fits(self, current_count, current_size, max_size, new_span): """Checks if the new span fits in the max payload size.""" return current_size + len(new_span) <= max_size
[ "def", "fits", "(", "self", ",", "current_count", ",", "current_size", ",", "max_size", ",", "new_span", ")", ":", "return", "current_size", "+", "len", "(", "new_span", ")", "<=", "max_size" ]
61.666667
0.010695
def build_wheel( self, wheel_directory, config_settings=None, metadata_directory=None): """Build a wheel from this project. Returns the name of the newly created file. In general, this will call the 'build_wheel' hook in the backend. However, if that was previou...
[ "def", "build_wheel", "(", "self", ",", "wheel_directory", ",", "config_settings", "=", "None", ",", "metadata_directory", "=", "None", ")", ":", "if", "metadata_directory", "is", "not", "None", ":", "metadata_directory", "=", "abspath", "(", "metadata_directory",...
42.315789
0.002433
def distance_between(self, u, v): '''Return the distance between nodes ``u`` and ``v`` in this ``Tree`` Args: ``u`` (``Node``): Node ``u`` ``v`` (``Node``): Node ``v`` Returns: ``float``: The distance between nodes ``u`` and ``v`` ''' if not...
[ "def", "distance_between", "(", "self", ",", "u", ",", "v", ")", ":", "if", "not", "isinstance", "(", "u", ",", "Node", ")", ":", "raise", "TypeError", "(", "\"u must be a Node\"", ")", "if", "not", "isinstance", "(", "v", ",", "Node", ")", ":", "rai...
33.757576
0.009599
def values(self): """ Get values :return: """ if not hasattr(self, VALUES_ATTR_NAME): setattr(self, VALUES_ATTR_NAME, {}) return getattr(self, VALUES_ATTR_NAME)
[ "def", "values", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "VALUES_ATTR_NAME", ")", ":", "setattr", "(", "self", ",", "VALUES_ATTR_NAME", ",", "{", "}", ")", "return", "getattr", "(", "self", ",", "VALUES_ATTR_NAME", ")" ]
23.666667
0.00905
def FromResponse(cls, response): """Create a DeviceFlowInfo from a server response. The response should be a dict containing entries as described here: http://tools.ietf.org/html/draft-ietf-oauth-v2-05#section-3.7.1 """ # device_code, user_code, and verification_url are require...
[ "def", "FromResponse", "(", "cls", ",", "response", ")", ":", "# device_code, user_code, and verification_url are required.", "kwargs", "=", "{", "'device_code'", ":", "response", "[", "'device_code'", "]", ",", "'user_code'", ":", "response", "[", "'user_code'", "]",...
41.533333
0.001569
def aggregate_events(aggregations, start_date=None, end_date=None, update_bookmark=True): """Aggregate indexed events.""" start_date = dateutil_parse(start_date) if start_date else None end_date = dateutil_parse(end_date) if end_date else None results = [] for a in aggregations:...
[ "def", "aggregate_events", "(", "aggregations", ",", "start_date", "=", "None", ",", "end_date", "=", "None", ",", "update_bookmark", "=", "True", ")", ":", "start_date", "=", "dateutil_parse", "(", "start_date", ")", "if", "start_date", "else", "None", "end_d...
47.083333
0.001736
def from_T050017(cls, url, coltype = LIGOTimeGPS): """ Parse a URL in the style of T050017-00 into a CacheEntry. The T050017-00 file name format is, essentially, observatory-description-start-duration.extension Example: >>> c = CacheEntry.from_T050017("file://localhost/data/node144/frames/S5/strain-L2/LL...
[ "def", "from_T050017", "(", "cls", ",", "url", ",", "coltype", "=", "LIGOTimeGPS", ")", ":", "match", "=", "cls", ".", "_url_regex", ".", "search", "(", "url", ")", "if", "not", "match", ":", "raise", "ValueError", "(", "\"could not convert %s to CacheEntry\...
31.933333
0.032421
def copytree(src, dst, symlinks=True): """ Modified from shutil.copytree docs code sample, merges files rather than requiring dst to not exist. """ from shutil import copy2, Error, copystat names = os.listdir(src) if not Path(dst).exists(): os.makedirs(dst) errors = [] for...
[ "def", "copytree", "(", "src", ",", "dst", ",", "symlinks", "=", "True", ")", ":", "from", "shutil", "import", "copy2", ",", "Error", ",", "copystat", "names", "=", "os", ".", "listdir", "(", "src", ")", "if", "not", "Path", "(", "dst", ")", ".", ...
31.74359
0.000784
def copy_obj(obj): ''' does a deepcopy of an object, but does not copy a class i.e. x = {"key":[<classInstance1>,<classInstance2>,<classInstance3>]} y = copy_obj(x) y --> {"key":[<classInstance1>,<classInstance2>,<classInstance3>]} del y['key'][0] y --> {"key":[<class...
[ "def", "copy_obj", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "dict", ")", ":", "return_obj", "=", "{", "}", "for", "key", ",", "value", "in", "obj", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "dict", ")",...
38.5625
0.000791
def create_cfg(self, cfg_file, defaults=None, mode='json'): ''' set mode to json or yaml? probably remove this option..Todo Creates the config file for your app with default values The file will only be created if it doesn't exits also sets up the first_run attribute. ...
[ "def", "create_cfg", "(", "self", ",", "cfg_file", ",", "defaults", "=", "None", ",", "mode", "=", "'json'", ")", ":", "assert", "mode", "in", "(", "'json'", ",", "'yaml'", ")", "self", ".", "cfg_mode", "=", "mode", "self", ".", "cfg_file", "=", "cfg...
33.297297
0.001577
def sum(x, weights=None): ''' sum(x) yields either a potential-sum object if x is a potential function or the sum of x if x is not. If x is not a potential-field then it must be a vector. sum(x, weights=w) uses the given weights to produce a weighted sum. ''' x = to_potential(x) if is_cons...
[ "def", "sum", "(", "x", ",", "weights", "=", "None", ")", ":", "x", "=", "to_potential", "(", "x", ")", "if", "is_const_potential", "(", "x", ")", ":", "return", "PotentialConstant", "(", "np", ".", "sum", "(", "x", ".", "c", ")", ")", "else", ":...
48.333333
0.011287
def find_skill(self, param, author=None, skills=None): # type: (str, str, List[SkillEntry]) -> SkillEntry """Find skill by name or url""" if param.startswith('https://') or param.startswith('http://'): repo_id = SkillEntry.extract_repo_id(param) for skill in self.list(): ...
[ "def", "find_skill", "(", "self", ",", "param", ",", "author", "=", "None", ",", "skills", "=", "None", ")", ":", "# type: (str, str, List[SkillEntry]) -> SkillEntry", "if", "param", ".", "startswith", "(", "'https://'", ")", "or", "param", ".", "startswith", ...
43.451613
0.002179
def items(self): """Return a copy of identity_dict items.""" return [(k, unidecode.unidecode(v)) for k, v in self.identity_dict.items()]
[ "def", "items", "(", "self", ")", ":", "return", "[", "(", "k", ",", "unidecode", ".", "unidecode", "(", "v", ")", ")", "for", "k", ",", "v", "in", "self", ".", "identity_dict", ".", "items", "(", ")", "]" ]
41.25
0.011905
def from_parameter(cls: Type[SIGParameterType], parameter: str) -> Optional[SIGParameterType]: """ Return a SIGParameter instance from an index parameter :param parameter: Index parameter :return: """ sig = SIGParameter.re_sig.match(parameter) if sig: ...
[ "def", "from_parameter", "(", "cls", ":", "Type", "[", "SIGParameterType", "]", ",", "parameter", ":", "str", ")", "->", "Optional", "[", "SIGParameterType", "]", ":", "sig", "=", "SIGParameter", ".", "re_sig", ".", "match", "(", "parameter", ")", "if", ...
27.692308
0.008065
def sort_sections(self, order): """ Sort sections according to the section names in the order list. All remaining sections are added to the end in their original order :param order: Iterable of section names :return: """ order_lc = [e.lower() for e in order] ...
[ "def", "sort_sections", "(", "self", ",", "order", ")", ":", "order_lc", "=", "[", "e", ".", "lower", "(", ")", "for", "e", "in", "order", "]", "sections", "=", "OrderedDict", "(", "(", "k", ",", "self", ".", "sections", "[", "k", "]", ")", "for"...
32.222222
0.015075
def _collect_plugin(self, plugin): '''Wraps the collect_plugin() method so we can apply a timeout against the plugin as a whole''' with ThreadPoolExecutor(1) as pool: try: t = pool.submit(self.collect_plugin, plugin) # Re-type int 0 to NoneType, as oth...
[ "def", "_collect_plugin", "(", "self", ",", "plugin", ")", ":", "with", "ThreadPoolExecutor", "(", "1", ")", "as", "pool", ":", "try", ":", "t", "=", "pool", ".", "submit", "(", "self", ".", "collect_plugin", ",", "plugin", ")", "# Re-type int 0 to NoneTyp...
49.5
0.002478
def run_node(cls, node, # type: NodeProto inputs, # type: Any device='CPU', # type: Text outputs_info=None, # type: Optional[Sequence[Tuple[numpy.dtype, Tuple[int, ...]]]] **kwargs # type: Dict[Text, Any] ): # ty...
[ "def", "run_node", "(", "cls", ",", "node", ",", "# type: NodeProto", "inputs", ",", "# type: Any", "device", "=", "'CPU'", ",", "# type: Text", "outputs_info", "=", "None", ",", "# type: Optional[Sequence[Tuple[numpy.dtype, Tuple[int, ...]]]]", "*", "*", "kwargs", "#...
50.652174
0.008425
def find_converting_reactions(model, pair): """ Find all reactions which convert a given metabolite pair. Parameters ---------- model : cobra.Model The metabolic model under investigation. pair: tuple or list A pair of metabolite identifiers without compartment suffix. Retu...
[ "def", "find_converting_reactions", "(", "model", ",", "pair", ")", ":", "first", "=", "set", "(", "find_met_in_model", "(", "model", ",", "pair", "[", "0", "]", ")", ")", "second", "=", "set", "(", "find_met_in_model", "(", "model", ",", "pair", "[", ...
32.033333
0.00101
def _prepare_connection(**nxos_api_kwargs): ''' Prepare the connection with the remote network device, and clean up the key value pairs, removing the args used for the connection init. ''' nxos_api_kwargs = clean_kwargs(**nxos_api_kwargs) init_kwargs = {} # Clean up any arguments that are no...
[ "def", "_prepare_connection", "(", "*", "*", "nxos_api_kwargs", ")", ":", "nxos_api_kwargs", "=", "clean_kwargs", "(", "*", "*", "nxos_api_kwargs", ")", "init_kwargs", "=", "{", "}", "# Clean up any arguments that are not required", "for", "karg", ",", "warg", "in",...
39.111111
0.000924
def write_output_metadata(output_params): """Dump output JSON and verify parameters if output metadata exist.""" if "path" in output_params: metadata_path = os.path.join(output_params["path"], "metadata.json") logger.debug("check for output %s", metadata_path) try: existing_p...
[ "def", "write_output_metadata", "(", "output_params", ")", ":", "if", "\"path\"", "in", "output_params", ":", "metadata_path", "=", "os", ".", "path", ".", "join", "(", "output_params", "[", "\"path\"", "]", ",", "\"metadata.json\"", ")", "logger", ".", "debug...
50.558824
0.002283
def all_selected_options(self): """Returns a list of all selected options belonging to this select tag""" ret = [] for opt in self.options: if opt.is_selected(): ret.append(opt) return ret
[ "def", "all_selected_options", "(", "self", ")", ":", "ret", "=", "[", "]", "for", "opt", "in", "self", ".", "options", ":", "if", "opt", ".", "is_selected", "(", ")", ":", "ret", ".", "append", "(", "opt", ")", "return", "ret" ]
34.571429
0.012097
def font_info(font_str): """Extract font information from a font string, such as supplied to the 'font' argument to a widget. """ vals = font_str.split(';') point_size, style, weight = 8, 'normal', 'normal' family = vals[0] if len(vals) > 1: style = vals[1] if len(vals) > 2: ...
[ "def", "font_info", "(", "font_str", ")", ":", "vals", "=", "font_str", ".", "split", "(", "';'", ")", "point_size", ",", "style", ",", "weight", "=", "8", ",", "'normal'", ",", "'normal'", "family", "=", "vals", "[", "0", "]", "if", "len", "(", "v...
29.894737
0.001706
def string_match(self, datastring, findstring, flags=None): """ Returns position of findstring in datastring or None if not found. Flags is a list of strings. Supported strings are: * "MATCH_CASE": The case has to match for valid find * "WHOLE_WORD": The word has to be surround...
[ "def", "string_match", "(", "self", ",", "datastring", ",", "findstring", ",", "flags", "=", "None", ")", ":", "if", "type", "(", "datastring", ")", "is", "IntType", ":", "# Empty cell", "return", "None", "if", "flags", "is", "None", ":", "flags", "=", ...
32.731707
0.001447
def cond_init(m:nn.Module, init_func:LayerFunc): "Initialize the non-batchnorm layers of `m` with `init_func`." if (not isinstance(m, bn_types)) and requires_grad(m): init_default(m, init_func)
[ "def", "cond_init", "(", "m", ":", "nn", ".", "Module", ",", "init_func", ":", "LayerFunc", ")", ":", "if", "(", "not", "isinstance", "(", "m", ",", "bn_types", ")", ")", "and", "requires_grad", "(", "m", ")", ":", "init_default", "(", "m", ",", "i...
66.333333
0.024876
def fourier_series(x, *a): """ Arbitrary dimensionality fourier series. The first parameter is a_0, and the second parameter is the interval/scale parameter. The parameters are altering sin and cos paramters. n = (len(a)-2)/2 """ output = 0 output += a[0]/2 w = a[1] for n ...
[ "def", "fourier_series", "(", "x", ",", "*", "a", ")", ":", "output", "=", "0", "output", "+=", "a", "[", "0", "]", "/", "2", "w", "=", "a", "[", "1", "]", "for", "n", "in", "range", "(", "2", ",", "len", "(", "a", ")", ",", "2", ")", "...
22.666667
0.002016
def get_agile_board(self, board_id): """ Get agile board info by id :param board_id: :return: """ url = 'rest/agile/1.0/board/{}'.format(str(board_id)) return self.get(url)
[ "def", "get_agile_board", "(", "self", ",", "board_id", ")", ":", "url", "=", "'rest/agile/1.0/board/{}'", ".", "format", "(", "str", "(", "board_id", ")", ")", "return", "self", ".", "get", "(", "url", ")" ]
27.625
0.008772
def mousePressEvent(self, event): """Reimplement Qt method""" if sys.platform.startswith('linux') and event.button() == Qt.MidButton: self.calltip_widget.hide() self.setFocus() event = QMouseEvent(QEvent.MouseButtonPress, event.pos(), ...
[ "def", "mousePressEvent", "(", "self", ",", "event", ")", ":", "if", "sys", ".", "platform", ".", "startswith", "(", "'linux'", ")", "and", "event", ".", "button", "(", ")", "==", "Qt", ".", "MidButton", ":", "self", ".", "calltip_widget", ".", "hide",...
52.782609
0.001618
def secured_apps_copy(self, apps): """ Given the http app list of a website, return what should be in the secure version """ return [[app_name, path] for app_name, path in apps if app_name not in (self.LETSENCRYPT_VERIFY_APP_NAME,)]
[ "def", "secured_apps_copy", "(", "self", ",", "apps", ")", ":", "return", "[", "[", "app_name", ",", "path", "]", "for", "app_name", ",", "path", "in", "apps", "if", "app_name", "not", "in", "(", "self", ".", "LETSENCRYPT_VERIFY_APP_NAME", ",", ")", "]" ...
65.25
0.011364
def find_object(obj, remainder, notfound_handlers, request): ''' 'Walks' the url path in search of an action for which a controller is implemented and returns that controller object along with what's left of the remainder. ''' prev_obj = None while True: if obj is None: r...
[ "def", "find_object", "(", "obj", ",", "remainder", ",", "notfound_handlers", ",", "request", ")", ":", "prev_obj", "=", "None", "while", "True", ":", "if", "obj", "is", "None", ":", "raise", "PecanNotFound", "if", "iscontroller", "(", "obj", ")", ":", "...
37.902439
0.000314
def mergesort(list_of_lists, key=None): """ Perform an N-way merge operation on sorted lists. @param list_of_lists: (really iterable of iterable) of sorted elements (either by naturally or by C{key}) @param key: specify sort key function (like C{sort()}, C{sorted()}) Yields tuples of the form C{(i...
[ "def", "mergesort", "(", "list_of_lists", ",", "key", "=", "None", ")", ":", "heap", "=", "[", "]", "for", "i", ",", "itr", "in", "enumerate", "(", "iter", "(", "pl", ")", "for", "pl", "in", "list_of_lists", ")", ":", "try", ":", "item", "=", "it...
31.893939
0.000922
def format_lp(nodes, constraints_x, qa, constraints_y, qb): """ Maximize 4 x1 + 2 x2 + 3 x3 + x4 Subject To x1 + x2 <= 1 End """ lp_handle = cStringIO.StringIO() lp_handle.write("Maximize\n ") records = 0 for i, score in nodes: lp_handle.write("+ %d x%d " % (score,...
[ "def", "format_lp", "(", "nodes", ",", "constraints_x", ",", "qa", ",", "constraints_y", ",", "qb", ")", ":", "lp_handle", "=", "cStringIO", ".", "StringIO", "(", ")", "lp_handle", ".", "write", "(", "\"Maximize\\n \"", ")", "records", "=", "0", "for", "...
27.553191
0.000746
def repair_refs(key, value, fmt, meta): # pylint: disable=unused-argument """Using "-f markdown+autolink_bare_uris" with pandoc < 1.18 splits a reference like "{@fig:one}" into email Link and Str elements. This function replaces the mess with the Cite and Str elements we normally get. Call this befor...
[ "def", "repair_refs", "(", "key", ",", "value", ",", "fmt", ",", "meta", ")", ":", "# pylint: disable=unused-argument", "if", "_PANDOCVERSION", ">=", "'1.18'", ":", "return", "# The problem spans multiple elements, and so can only be identified in", "# element lists. Element...
38.894737
0.001321
def format_request_email_body(increq, **ctx): """Format the email message body for inclusion request notification. :param increq: Inclusion request object for which the request is made. :type increq: `invenio_communities.models.InclusionRequest` :param ctx: Optional extra context parameters passed to f...
[ "def", "format_request_email_body", "(", "increq", ",", "*", "*", "ctx", ")", ":", "template", "=", "current_app", ".", "config", "[", "\"COMMUNITIES_REQUEST_EMAIL_BODY_TEMPLATE\"", "]", ",", "return", "format_request_email_templ", "(", "increq", ",", "template", ",...
44.833333
0.001821
def get_pages(self, include_draft=False): """ Get all custom pages (supported formats, excluding other files like '.js', '.css', '.html'). :param include_draft: return draft page or not :return: an iterable of Page objects """ def pages_generator(pages_root_path...
[ "def", "get_pages", "(", "self", ",", "include_draft", "=", "False", ")", ":", "def", "pages_generator", "(", "pages_root_path", ")", ":", "for", "file_path", "in", "traverse_directory", "(", "pages_root_path", ",", "yield_dir", "=", "False", ")", ":", "rel_pa...
42.172414
0.001599
def connect_s3_bucket_to_lambda(self, bucket, function_arn, events, prefix=None, suffix=None): # type: (str, str, List[str], OptStr, OptStr) -> None """Configure S3 bucket to invoke a lambda function. The S3 bucket must already have permission to invoke the ...
[ "def", "connect_s3_bucket_to_lambda", "(", "self", ",", "bucket", ",", "function_arn", ",", "events", ",", "prefix", "=", "None", ",", "suffix", "=", "None", ")", ":", "# type: (str, str, List[str], OptStr, OptStr) -> None", "s3", "=", "self", ".", "_client", "(",...
47.880952
0.001949
def annotate(args): """ %prog annotate new.bed old.bed 2> log Annotate the `new.bed` with features from `old.bed` for the purpose of gene numbering. Ambiguity in ID assignment can be resolved by either of the following 2 methods: - `alignment`: make use of global sequence alignment score (calc...
[ "def", "annotate", "(", "args", ")", ":", "from", "jcvi", ".", "utils", ".", "grouper", "import", "Grouper", "valid_resolve_choices", "=", "[", "\"alignment\"", ",", "\"overlap\"", "]", "p", "=", "OptionParser", "(", "annotate", ".", "__doc__", ")", "p", "...
37.552846
0.008015
def repr(self, *args, **kwargs): """ Returns the unique string representation of the number. """ if not self.is_numpy: text = "'" + self.str(*args, **kwargs) + "'" else: text = "{} numpy array, {} uncertainties".format(self.shape, len(self.uncertainties)) ...
[ "def", "repr", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "is_numpy", ":", "text", "=", "\"'\"", "+", "self", ".", "str", "(", "*", "args", ",", "*", "*", "kwargs", ")", "+", "\"'\"", "else", "...
39.6
0.009877
def mmi_to_delimited_file(self, force_flag=True): """Save mmi_data to delimited text file suitable for gdal_grid. The output file will be of the same format as strings returned from :func:`mmi_to_delimited_text`. :param force_flag: Whether to force the regeneration of the output ...
[ "def", "mmi_to_delimited_file", "(", "self", ",", "force_flag", "=", "True", ")", ":", "LOGGER", ".", "debug", "(", "'mmi_to_delimited_text requested.'", ")", "csv_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "output_dir", ",", "'mmi.csv'", ...
39.435897
0.001269
def run(self): """ Consume message from the Advanced Message Queuing Protocol (AMPQ) compliant broker as soon as they are queued, and call the instance method ``__on_message_received`` that the inheriting class must have implemented. """ self._setUp() nam...
[ "def", "run", "(", "self", ")", ":", "self", ".", "_setUp", "(", ")", "naming", "=", "'skunkworks.lbs.%s.%s.%s'", "%", "(", "settings", ".", "ENVIRONMENT_STAGE", ",", "self", ".", "service_name", ".", "lower", "(", ")", ",", "self", ".", "message_type", ...
43.25
0.008483
def _fit_diagV_noGP( self, XTY, XTDY, XTFY, YTY_diag, YTDY_diag, YTFY_diag, XTX, XTDX, XTFX, X, Y, X_base, X_res, D, F, run_TRs, current_vec_U_chlsk_l, current_a1, current_logSNR2, idx_param_fitU, idx_param_fitV, l_idx, n_C, n_T, n_V, n_l, n_run, n...
[ "def", "_fit_diagV_noGP", "(", "self", ",", "XTY", ",", "XTDY", ",", "XTFY", ",", "YTY_diag", ",", "YTDY_diag", ",", "YTFY_diag", ",", "XTX", ",", "XTDX", ",", "XTFX", ",", "X", ",", "Y", ",", "X_base", ",", "X_res", ",", "D", ",", "F", ",", "run...
50.142857
0.00031
def part_show(self, part, printout=False): ''' Opens/shows the aggregator's URI for the part. printout: if set, only printout the URI, do not open the browser. ''' result = self._e.parts_match( queries=[{'mpn_or_sku': part}], exact_only=True, ...
[ "def", "part_show", "(", "self", ",", "part", ",", "printout", "=", "False", ")", ":", "result", "=", "self", ".", "_e", ".", "parts_match", "(", "queries", "=", "[", "{", "'mpn_or_sku'", ":", "part", "}", "]", ",", "exact_only", "=", "True", ",", ...
33.76
0.002304
def download_url(self, url, timeout, fail=False, post=None, verify=True): """Download text from the given url. Returns `None` on failure. Arguments --------- self url : str URL web address to download. timeout : int Duration after which U...
[ "def", "download_url", "(", "self", ",", "url", ",", "timeout", ",", "fail", "=", "False", ",", "post", "=", "None", ",", "verify", "=", "True", ")", ":", "_CODE_ERRORS", "=", "[", "500", ",", "307", ",", "404", "]", "import", "requests", "session", ...
32.923077
0.000756
def get_by_details(self, name, type, clazz): """Gets an entry by details. Will return None if there is no matching entry.""" entry = DNSEntry(name, type, clazz) return self.get(entry)
[ "def", "get_by_details", "(", "self", ",", "name", ",", "type", ",", "clazz", ")", ":", "entry", "=", "DNSEntry", "(", "name", ",", "type", ",", "clazz", ")", "return", "self", ".", "get", "(", "entry", ")" ]
42.4
0.009259
def csv_format(csv_data, c_headers=None, r_headers=None, rows=None, **kwargs): """ Format csv rows parsed to Dict or Array """ result = None c_headers = [] if c_headers is None else c_headers r_headers = [] if r_headers is None else r_headers rows = [] if rows is None else rows result_f...
[ "def", "csv_format", "(", "csv_data", ",", "c_headers", "=", "None", ",", "r_headers", "=", "None", ",", "rows", "=", "None", ",", "*", "*", "kwargs", ")", ":", "result", "=", "None", "c_headers", "=", "[", "]", "if", "c_headers", "is", "None", "else...
27.032258
0.001152
def reconstruct_emds(edm, Om, all_points, method=None, **kwargs): """ Reconstruct point set using E(dge)-MDS. """ from .point_set import dm_from_edm N = all_points.shape[0] d = all_points.shape[1] dm = dm_from_edm(edm) if method is None: from .mds import superMDS Xhat, __ = s...
[ "def", "reconstruct_emds", "(", "edm", ",", "Om", ",", "all_points", ",", "method", "=", "None", ",", "*", "*", "kwargs", ")", ":", "from", ".", "point_set", "import", "dm_from_edm", "N", "=", "all_points", ".", "shape", "[", "0", "]", "d", "=", "all...
38.275862
0.001757
def from_file(cls, filename): """ Create a public blob from a ``-cert.pub``-style file on disk. """ with open(filename) as f: string = f.read() return cls.from_string(string)
[ "def", "from_file", "(", "cls", ",", "filename", ")", ":", "with", "open", "(", "filename", ")", "as", "f", ":", "string", "=", "f", ".", "read", "(", ")", "return", "cls", ".", "from_string", "(", "string", ")" ]
31.428571
0.00885
def build(self, input_filepath_list, output_filepath, combine_type, input_volumes=None): '''Builds the output_file by executing the current set of commands. Parameters ---------- input_filepath_list : list of str List of paths to input audio files. outp...
[ "def", "build", "(", "self", ",", "input_filepath_list", ",", "output_filepath", ",", "combine_type", ",", "input_volumes", "=", "None", ")", ":", "file_info", ".", "validate_input_file_list", "(", "input_filepath_list", ")", "file_info", ".", "validate_output_file", ...
38.816901
0.001062
def _loadSubcatRelations( self, inputFile ): ''' Laeb sisendfailist (inputFile) verb-nom/adv-vinf rektsiooniseoste mustrid. Iga muster peab olema failis eraldi real, kujul: (verbikirjeldus)\TAB(nom/adv-kirjeldus)\TAB(vinfkirjeldus) nt leid NEG aeg;S;(...
[ "def", "_loadSubcatRelations", "(", "self", ",", "inputFile", ")", ":", "self", ".", "nomAdvWordTemplates", "=", "dict", "(", ")", "self", ".", "verbRules", "=", "dict", "(", ")", "self", ".", "verbToVinf", "=", "dict", "(", ")", "in_f", "=", "codecs", ...
51.025
0.010096
def check_package(self, package, package_dir): """Check namespace packages' __init__ for declare_namespace""" try: return self.packages_checked[package] except KeyError: pass init_py = orig.build_py.check_package(self, package, package_dir) self.packages_...
[ "def", "check_package", "(", "self", ",", "package", ",", "package_dir", ")", ":", "try", ":", "return", "self", ".", "packages_checked", "[", "package", "]", "except", "KeyError", ":", "pass", "init_py", "=", "orig", ".", "build_py", ".", "check_package", ...
36.096774
0.001741
def jsondel(self, name, path=Path.rootPath()): """ Deletes the JSON value stored at key ``name`` under ``path`` """ return self.execute_command('JSON.DEL', name, str_path(path))
[ "def", "jsondel", "(", "self", ",", "name", ",", "path", "=", "Path", ".", "rootPath", "(", ")", ")", ":", "return", "self", ".", "execute_command", "(", "'JSON.DEL'", ",", "name", ",", "str_path", "(", "path", ")", ")" ]
41
0.009569
def _construct_from_dataframe(self): """Build the network using the significant pathways dataframe by identifying pairwise direct (same-side) relationships. """ direct_edges = {} feature_side_grouping = self.feature_pathway_df.groupby( ["feature", "side"]) for...
[ "def", "_construct_from_dataframe", "(", "self", ")", ":", "direct_edges", "=", "{", "}", "feature_side_grouping", "=", "self", ".", "feature_pathway_df", ".", "groupby", "(", "[", "\"feature\"", ",", "\"side\"", "]", ")", "for", "(", "feature", ",", "_", ")...
47.714286
0.001957
def before_sleep_log(logger, log_level): """Before call strategy that logs to some logger the attempt.""" def log_it(retry_state): if retry_state.outcome.failed: verb, value = 'raised', retry_state.outcome.exception() else: verb, value = 'returned', retry_state.outcome.re...
[ "def", "before_sleep_log", "(", "logger", ",", "log_level", ")", ":", "def", "log_it", "(", "retry_state", ")", ":", "if", "retry_state", ".", "outcome", ".", "failed", ":", "verb", ",", "value", "=", "'raised'", ",", "retry_state", ".", "outcome", ".", ...
41.285714
0.001692
def apply_config_to_machine_group(self, project_name, config_name, group_name): """ apply a logtail config to a machine group Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type config_name: string ...
[ "def", "apply_config_to_machine_group", "(", "self", ",", "project_name", ",", "config_name", ",", "group_name", ")", ":", "headers", "=", "{", "}", "params", "=", "{", "}", "resource", "=", "\"/machinegroups/\"", "+", "group_name", "+", "\"/configs/\"", "+", ...
38.090909
0.008149
def bootstrap_histogram_1D( values, intervals, uncertainties=None, normalisation=False, number_bootstraps=None, boundaries=None): ''' Bootstrap samples a set of vectors :param numpy.ndarray values: The data values :param numpy.ndarray intervals: The bin edges :param ...
[ "def", "bootstrap_histogram_1D", "(", "values", ",", "intervals", ",", "uncertainties", "=", "None", ",", "normalisation", "=", "False", ",", "number_bootstraps", "=", "None", ",", "boundaries", "=", "None", ")", ":", "if", "not", "number_bootstraps", "or", "n...
36.591837
0.00163
def sort_matches(matches): '''Sorts a ``list`` of matches best to worst''' multipliers = {'exact':10**5,'fname':10**4,'fuzzy':10**2,'fuzzy_fragment':1} matches = [(multipliers[x.type]*(x.amount if x.amount else 1),x) for x in matches] return [x[1] for x in sorted(matches,reverse=True)]
[ "def", "sort_matches", "(", "matches", ")", ":", "multipliers", "=", "{", "'exact'", ":", "10", "**", "5", ",", "'fname'", ":", "10", "**", "4", ",", "'fuzzy'", ":", "10", "**", "2", ",", "'fuzzy_fragment'", ":", "1", "}", "matches", "=", "[", "(",...
59.6
0.039735
def select(self, query='', next_token=None, consistent_read=False, max_items=None): """ Returns a set of Attributes for item names within domain_name that match the query. The query must be expressed in using the SELECT style syntax rather than the original SimpleDB query language. ...
[ "def", "select", "(", "self", ",", "query", "=", "''", ",", "next_token", "=", "None", ",", "consistent_read", "=", "False", ",", "max_items", "=", "None", ")", ":", "return", "SelectResultSet", "(", "self", ",", "query", ",", "max_items", "=", "max_item...
48
0.010217
def add_io_macro(self,io,filename): """ Add a variable (macro) for storing the input/output files associated with this node. @param io: macroinput or macrooutput @param filename: filename of input/output file """ io = self.__bad_macro_chars.sub( r'', io ) if io not in self.__opts: ...
[ "def", "add_io_macro", "(", "self", ",", "io", ",", "filename", ")", ":", "io", "=", "self", ".", "__bad_macro_chars", ".", "sub", "(", "r''", ",", "io", ")", "if", "io", "not", "in", "self", ".", "__opts", ":", "self", ".", "__opts", "[", "io", ...
33.076923
0.015837
def wp_is_loiter(self, i): '''return true if waypoint is a loiter waypoint''' loiter_cmds = [mavutil.mavlink.MAV_CMD_NAV_LOITER_UNLIM, mavutil.mavlink.MAV_CMD_NAV_LOITER_TURNS, mavutil.mavlink.MAV_CMD_NAV_LOITER_TIME, mavutil.mavlink.MAV_CMD_NAV_LOITER_TO_...
[ "def", "wp_is_loiter", "(", "self", ",", "i", ")", ":", "loiter_cmds", "=", "[", "mavutil", ".", "mavlink", ".", "MAV_CMD_NAV_LOITER_UNLIM", ",", "mavutil", ".", "mavlink", ".", "MAV_CMD_NAV_LOITER_TURNS", ",", "mavutil", ".", "mavlink", ".", "MAV_CMD_NAV_LOITER...
38
0.014019
def from_cid(cls, cid, **kwargs): """Retrieve the Compound record for the specified CID. Usage:: c = Compound.from_cid(6819) :param int cid: The PubChem Compound Identifier (CID). """ record = json.loads(request(cid, **kwargs).read().decode())['PC_Compounds'][0] ...
[ "def", "from_cid", "(", "cls", ",", "cid", ",", "*", "*", "kwargs", ")", ":", "record", "=", "json", ".", "loads", "(", "request", "(", "cid", ",", "*", "*", "kwargs", ")", ".", "read", "(", ")", ".", "decode", "(", ")", ")", "[", "'PC_Compound...
30.363636
0.008721
def humanize_size(size): """Create a nice human readable representation of the given number (understood as bytes) using the "KiB" and "MiB" suffixes to indicate kibibytes and mebibytes. A kibibyte is defined as 1024 bytes (as opposed to a kilobyte which is 1000 bytes) and a mibibyte is 1024**2 bytes (as...
[ "def", "humanize_size", "(", "size", ")", ":", "for", "factor", ",", "format_string", "in", "(", "(", "1", ",", "'%i'", ")", ",", "(", "1024", ",", "'%iKiB'", ")", ",", "(", "1024", "*", "1024", ",", "'%.1fMiB'", ")", ")", ":", "if", "size", "/",...
43.222222
0.001258
def update_metric(self, metric, labels, pre_sliced=False): """Update metric with the current executor.""" self.curr_execgrp.update_metric(metric, labels, pre_sliced)
[ "def", "update_metric", "(", "self", ",", "metric", ",", "labels", ",", "pre_sliced", "=", "False", ")", ":", "self", ".", "curr_execgrp", ".", "update_metric", "(", "metric", ",", "labels", ",", "pre_sliced", ")" ]
59.666667
0.01105
def to_dict(self): """Convert Image into raw dictionary data.""" if not self.url: return None return { 'url': self.url, 'width': self.width, 'height': self.height }
[ "def", "to_dict", "(", "self", ")", ":", "if", "not", "self", ".", "url", ":", "return", "None", "return", "{", "'url'", ":", "self", ".", "url", ",", "'width'", ":", "self", ".", "width", ",", "'height'", ":", "self", ".", "height", "}" ]
26.222222
0.008197
def tsp(edges, constraint_generation=False): """ Calculates shortest cycle that traverses each node exactly once. Also known as the Traveling Salesman Problem (TSP). """ edges = populate_edge_weights(edges) incoming, outgoing, nodes = node_to_edge(edges) nedges, nnodes = len(edges), len(nod...
[ "def", "tsp", "(", "edges", ",", "constraint_generation", "=", "False", ")", ":", "edges", "=", "populate_edge_weights", "(", "edges", ")", "incoming", ",", "outgoing", ",", "nodes", "=", "node_to_edge", "(", "edges", ")", "nedges", ",", "nnodes", "=", "le...
37.609756
0.000948
def model_fn(features, labels, mode, params, config): """Builds the model function for use in an Estimator. Arguments: features: The input features for the Estimator. labels: The labels, unused here. mode: Signifies whether it is train or test or predict. params: Some hyperparameters as a dictionar...
[ "def", "model_fn", "(", "features", ",", "labels", ",", "mode", ",", "params", ",", "config", ")", ":", "del", "labels", ",", "config", "# Set up the model's learnable parameters.", "logit_concentration", "=", "tf", ".", "compat", ".", "v1", ".", "get_variable",...
37.715447
0.010922
def in_words(self, locale=None, separator=" "): """ Get the current interval in words in the current locale. Ex: 6 jours 23 heures 58 minutes :param locale: The locale to use. Defaults to current locale. :type locale: str :param separator: The separator to use between ...
[ "def", "in_words", "(", "self", ",", "locale", "=", "None", ",", "separator", "=", "\" \"", ")", ":", "periods", "=", "[", "(", "\"year\"", ",", "self", ".", "years", ")", ",", "(", "\"month\"", ",", "self", ".", "months", ")", ",", "(", "\"week\""...
31.883721
0.002123
def system_types(): ''' List the system types that are supported by the installed version of sfdisk CLI Example: .. code-block:: bash salt '*' partition.system_types ''' ret = {} for line in __salt__['cmd.run']('sfdisk -T').splitlines(): if not line: continue ...
[ "def", "system_types", "(", ")", ":", "ret", "=", "{", "}", "for", "line", "in", "__salt__", "[", "'cmd.run'", "]", "(", "'sfdisk -T'", ")", ".", "splitlines", "(", ")", ":", "if", "not", "line", ":", "continue", "if", "line", ".", "startswith", "(",...
23.157895
0.002183
def marker_tags(self, iid): """Generator for all the tags of a certain marker""" tags = self._markers[iid]["tags"] for tag in tags: yield tag
[ "def", "marker_tags", "(", "self", ",", "iid", ")", ":", "tags", "=", "self", ".", "_markers", "[", "iid", "]", "[", "\"tags\"", "]", "for", "tag", "in", "tags", ":", "yield", "tag" ]
34.6
0.011299
def debug(self, *args) -> "Err": """ Creates a debug message """ error = self._create_err("debug", *args) print(self._errmsg(error)) return error
[ "def", "debug", "(", "self", ",", "*", "args", ")", "->", "\"Err\"", ":", "error", "=", "self", ".", "_create_err", "(", "\"debug\"", ",", "*", "args", ")", "print", "(", "self", ".", "_errmsg", "(", "error", ")", ")", "return", "error" ]
26.714286
0.010363
def export_gmf(ekey, dstore): """ :param ekey: export key, i.e. a pair (datastore key, fmt) :param dstore: datastore object """ oq = dstore['oqparam'] if not oq.calculation_mode.startswith('scenario'): return [] sitecol = dstore['sitecol'] investigation_time = (None if oq.calcula...
[ "def", "export_gmf", "(", "ekey", ",", "dstore", ")", ":", "oq", "=", "dstore", "[", "'oqparam'", "]", "if", "not", "oq", ".", "calculation_mode", ".", "startswith", "(", "'scenario'", ")", ":", "return", "[", "]", "sitecol", "=", "dstore", "[", "'site...
38.37931
0.000876
async def update(self, records: Iterable[DataRecord], values: SQLValuesToWrite, returning=False) -> Union[int, Iterable[DataRecord]]: """ :param records: :param values: :param returning: :return: return count if returning is False, otherwise records """ raise NotI...
[ "async", "def", "update", "(", "self", ",", "records", ":", "Iterable", "[", "DataRecord", "]", ",", "values", ":", "SQLValuesToWrite", ",", "returning", "=", "False", ")", "->", "Union", "[", "int", ",", "Iterable", "[", "DataRecord", "]", "]", ":", "...
41.25
0.008902
def layers(self): """Yield a shallow view on a layer of this DAGCircuit for all d layers of this circuit. A layer is a circuit whose gates act on disjoint qubits, i.e. a layer has depth 1. The total number of layers equals the circuit depth d. The layers are indexed from 0 to d-1 with t...
[ "def", "layers", "(", "self", ")", ":", "graph_layers", "=", "self", ".", "multigraph_layers", "(", ")", "try", ":", "next", "(", "graph_layers", ")", "# Remove input nodes", "except", "StopIteration", ":", "return", "def", "add_nodes_from", "(", "layer", ",",...
42.681159
0.001991
def get_file_results(self): """Print the result and return the overall count for this file.""" self._deferred_print.sort() for line_number, offset, code, text, doc in self._deferred_print: print(self._fmt % { 'path': self.filename, 'row': self.line_off...
[ "def", "get_file_results", "(", "self", ")", ":", "self", ".", "_deferred_print", ".", "sort", "(", ")", "for", "line_number", ",", "offset", ",", "code", ",", "text", ",", "doc", "in", "self", ".", "_deferred_print", ":", "print", "(", "self", ".", "_...
43.222222
0.001676
def is_constraint(self): """ returns the expression of the constraint that constrains this parameter """ if self._is_constraint is None: return None return self._bundle.get_parameter(context='constraint', uniqueid=self._is_constraint)
[ "def", "is_constraint", "(", "self", ")", ":", "if", "self", ".", "_is_constraint", "is", "None", ":", "return", "None", "return", "self", ".", "_bundle", ".", "get_parameter", "(", "context", "=", "'constraint'", ",", "uniqueid", "=", "self", ".", "_is_co...
40
0.01049
def handle_data(self): """ handle stock data for trading signal, and make order """ # 读取历史数据,使用sma方式计算均线准确度和数据长度无关,但是在使用ema方式计算均线时建议将历史数据窗口适当放大,结果会更加准确 today = datetime.datetime.today() pre_day = (today - datetime.timedelta(days=self.observation) ).strf...
[ "def", "handle_data", "(", "self", ")", ":", "# 读取历史数据,使用sma方式计算均线准确度和数据长度无关,但是在使用ema方式计算均线时建议将历史数据窗口适当放大,结果会更加准确", "today", "=", "datetime", ".", "datetime", ".", "today", "(", ")", "pre_day", "=", "(", "today", "-", "datetime", ".", "timedelta", "(", "days", "="...
43.156627
0.001638
def _find_ip4_addresses(): """Find all the IP4 addresses currently bound to interfaces """ global _ip4_addresses proto = socket.AF_INET if _ip4_addresses is None: _ip4_addresses = [] # # Determine the interface for the default gateway # (if any) and, later, prioritis...
[ "def", "_find_ip4_addresses", "(", ")", ":", "global", "_ip4_addresses", "proto", "=", "socket", ".", "AF_INET", "if", "_ip4_addresses", "is", "None", ":", "_ip4_addresses", "=", "[", "]", "#", "# Determine the interface for the default gateway", "# (if any) and, later,...
34.892857
0.001992
def sparsity_pattern(self, reordered = True, symmetric = True): """ Returns a sparse matrix with the filled pattern. By default, the routine uses the reordered pattern, and the inverse permutation is applied if `reordered` is `False`. :param reordered: boolean (default:...
[ "def", "sparsity_pattern", "(", "self", ",", "reordered", "=", "True", ",", "symmetric", "=", "True", ")", ":", "return", "cspmatrix", "(", "self", ",", "1.0", ")", ".", "spmatrix", "(", "reordered", "=", "reordered", ",", "symmetric", "=", "symmetric", ...
47.6
0.026804
def create_node(participant_id): """Send a POST request to the node table. This makes a new node for the participant, it calls: 1. exp.get_network_for_participant 2. exp.create_node 3. exp.add_node_to_network 4. exp.node_post_request """ exp = experiment(session) # ...
[ "def", "create_node", "(", "participant_id", ")", ":", "exp", "=", "experiment", "(", "session", ")", "# Get the participant.", "try", ":", "participant", "=", "models", ".", "Participant", ".", "query", ".", "filter_by", "(", "id", "=", "participant_id", ")",...
30.830508
0.001066
def _bind_variables(self, instance, space): """ Bind related variables to the instance """ instance.api = self if space: instance.space = space return instance
[ "def", "_bind_variables", "(", "self", ",", "instance", ",", "space", ")", ":", "instance", ".", "api", "=", "self", "if", "space", ":", "instance", ".", "space", "=", "space", "return", "instance" ]
26.5
0.009132
def get_calling_file(file_path=None, result='name'): """ Retrieve file_name or file_path of calling Python script """ # Get full path of calling python script if file_path is None: path = inspect.stack()[1][1] else: path = file_path name = path.split('/')[-1].split('.')[0] ...
[ "def", "get_calling_file", "(", "file_path", "=", "None", ",", "result", "=", "'name'", ")", ":", "# Get full path of calling python script", "if", "file_path", "is", "None", ":", "path", "=", "inspect", ".", "stack", "(", ")", "[", "1", "]", "[", "1", "]"...
25.294118
0.002242
def echo(self, variableName, verbose=False): """ The echo command will display the value of the variable specified by the variableName argument, or all variables if variableName is not provided. :param variableName: The name of the variable or '*' to display the value of all variables. ...
[ "def", "echo", "(", "self", ",", "variableName", ",", "verbose", "=", "False", ")", ":", "PARAMS", "=", "{", "\"variableName\"", ":", "variableName", "}", "response", "=", "api", "(", "url", "=", "self", ".", "__url", "+", "\"/echo\"", ",", "PARAMS", "...
45.636364
0.015625
def children(self): """ The list of child messages and actions sorted by task level, excluding the start and end messages. """ return pvector( sorted(self._children.values(), key=lambda m: m.task_level))
[ "def", "children", "(", "self", ")", ":", "return", "pvector", "(", "sorted", "(", "self", ".", "_children", ".", "values", "(", ")", ",", "key", "=", "lambda", "m", ":", "m", ".", "task_level", ")", ")" ]
35.571429
0.011765
def _parse_and_format(self): """ Parse and format the results returned by the ACS Zeropoint Calculator. Using ``beautifulsoup4``, find all the ``<tb> </tb>`` tags present in the response. Format the results into an astropy.table.QTable with corresponding units and assign it to the zpt_t...
[ "def", "_parse_and_format", "(", "self", ")", ":", "soup", "=", "BeautifulSoup", "(", "self", ".", "_response", ".", "read", "(", ")", ",", "'html.parser'", ")", "# Grab all elements in the table returned by the ZPT calc.", "td", "=", "soup", ".", "find_all", "(",...
45.355556
0.001918
def draw(self): """ Draw the virtual keyboard into the delegate surface object if enabled. """ if self.state > 0: self.renderer.draw_background(self.surface, self.layout.position, self.layout.size) for row in self.layout.rows: for key in row.keys: ...
[ "def", "draw", "(", "self", ")", ":", "if", "self", ".", "state", ">", "0", ":", "self", ".", "renderer", ".", "draw_background", "(", "self", ".", "surface", ",", "self", ".", "layout", ".", "position", ",", "self", ".", "layout", ".", "size", ")"...
51.285714
0.010959